3 "Utility functions for handling buffers"
8 def hex_bytes(buffer, spaces=None):
9 r"""Pretty-printing for binary buffers.
11 >>> hex_bytes(buffer('\x00\x01\x02\x03\x04'))
13 >>> hex_bytes(buffer('\x00\x01\x02\x03\x04'), spaces=1)
15 >>> hex_bytes(buffer('\x00\x01\x02\x03\x04'), spaces=2)
17 >>> hex_bytes(buffer('\x00\x01\x02\x03\x04\x05\x06'), spaces=2)
19 >>> hex_bytes(buffer('\x00\x01\x02\x03\x04\x05\x06'), spaces=3)
22 hex_bytes = ['{:02x}'.format(ord(x)) for x in buffer]
24 return ''.join(hex_bytes)
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)
31 def assert_null(buffer, strict=True):
32 r"""Ensure an input buffer is entirely zero.
35 >>> assert_null(buffer(''))
36 >>> assert_null(buffer('\x00\x00'))
37 >>> assert_null(buffer('\x00\x01\x02\x03'))
38 Traceback (most recent call last):
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
47 if buffer and ord(max(buffer)) != 0:
48 hex_string = hex_bytes(buffer, spaces=1)
50 raise ValueError(hex_string)
53 'warning: post-data padding not zero: {}\n'.format(hex_string))