7b2c34fe6e3fb84bb4b7c720fbe8d4582e957468
[igor.git] / igor / util.py
1 # Copyright
2
3 "Utility functions for handling buffers"
4
5 import sys as _sys
6
7
8 def hex_bytes(buffer, spaces=None):
9     r"""Pretty-printing for binary buffers.
10
11     >>> hex_bytes(buffer('\x00\x01\x02\x03\x04'))
12     '0001020304'
13     >>> hex_bytes(buffer('\x00\x01\x02\x03\x04'), spaces=1)
14     '00 01 02 03 04'
15     >>> hex_bytes(buffer('\x00\x01\x02\x03\x04'), spaces=2)
16     '0001 0203 04'
17     >>> hex_bytes(buffer('\x00\x01\x02\x03\x04\x05\x06'), spaces=2)
18     '0001 0203 0405 06'
19     >>> hex_bytes(buffer('\x00\x01\x02\x03\x04\x05\x06'), spaces=3)
20     '000102 030405 06'
21     """
22     hex_bytes = ['{:02x}'.format(ord(x)) for x in buffer]
23     if spaces is None:
24         return ''.join(hex_bytes)
25     elif spaces is 1:
26         return ' '.join(hex_bytes)
27     for i in range(len(hex_bytes)//spaces):
28         hex_bytes.insert((spaces+1)*(i+1)-1, ' ')
29     return ''.join(hex_bytes)
30
31 def assert_null(buffer, strict=True):
32     r"""Ensure an input buffer is entirely zero.
33
34     >>> import sys
35     >>> assert_null(buffer(''))
36     >>> assert_null(buffer('\x00\x00'))
37     >>> assert_null(buffer('\x00\x01\x02\x03'))
38     Traceback (most recent call last):
39       ...
40     ValueError: 00 01 02 03
41     >>> stderr = sys.stderr
42     >>> sys.stderr = sys.stdout
43     >>> assert_null(buffer('\x00\x01\x02\x03'), strict=False)
44     warning: post-data padding not zero: 00 01 02 03
45     >>> sys.stderr = stderr
46     """
47     if buffer and ord(max(buffer)) != 0:
48         hex_string = hex_bytes(buffer, spaces=1)
49         if strict:
50             raise ValueError(hex_string)
51         else:
52             _sys.stderr.write(
53                 'warning: post-data padding not zero: {}\n'.format(hex_string))