over.core.misc.hexdump

- fix crash on empty data
- add option for string output
This commit is contained in:
Martinez 2016-01-22 11:29:42 +01:00
parent 6d854fefc6
commit bd216a2e7a

View file

@ -3,6 +3,7 @@
import copy import copy
import imp import imp
import io
import math import math
import os import os
import sys import sys
@ -96,13 +97,15 @@ def hexdump(data, indent=0, offset=16, show_header=True, show_offsets=True, show
If show_offsets is True, each line is prefixed with the address of the first byte of that line. If show_offsets is True, each line is prefixed with the address of the first byte of that line.
If show_ascii is True, each line is suffixed with its ASCII representation. Unprintable characters If show_ascii is True, each line is suffixed with its ASCII representation. Unprintable characters
are replaced with a dot. are replaced with a dot.
The 'output' must implement a .write(str) method. The 'output' must implement a .write(str) method. If 'output' is None, the string is returned instead.
""" """
output_io = io.StringIO() if not output else output
if type(data) is not bytes: if type(data) is not bytes:
raise ValueError('data must be bytes') raise ValueError('data must be bytes')
offset_figures = math.ceil(math.log2(len(data)) / 8) * 2 offset_figures = math.ceil(math.log2(len(data)) / 8) * 2 if data else 2
format_str = '%%0%dx ' %(offset_figures) format_str = '%%0%dx ' %(offset_figures)
ptr = 0 ptr = 0
@ -118,14 +121,14 @@ def hexdump(data, indent=0, offset=16, show_header=True, show_offsets=True, show
if show_ascii: if show_ascii:
line.append(' ASCII') line.append(' ASCII')
output.write(' '.join(line) + '\n') output_io.write(' '.join(line) + '\n')
while data[ptr:]: while data[ptr:]:
if indent: if indent:
output.write(' ' * indent) output_io.write(' ' * indent)
if show_offsets: if show_offsets:
output.write(format_str %(ptr)) output_io.write(format_str %(ptr))
hex_bytes = [] hex_bytes = []
ascii_bytes = [] ascii_bytes = []
@ -142,11 +145,15 @@ def hexdump(data, indent=0, offset=16, show_header=True, show_offsets=True, show
elif i == len(data): elif i == len(data):
hex_bytes.extend([' '] * (offset - local_i)) hex_bytes.extend([' '] * (offset - local_i))
output.write(' '.join(hex_bytes)) output_io.write(' '.join(hex_bytes))
if show_ascii: if show_ascii:
output.write(' |' + ''.join(ascii_bytes) + '|') output_io.write(' |' + ''.join(ascii_bytes) + '|')
output.write('\n') output_io.write('\n')
ptr += offset ptr += offset
if not output:
output_io.seek(0)
return output_io.read()