hexdump: skip lines if the content is the same

This commit is contained in:
Martin Sekera 2019-03-31 00:13:55 +01:00
parent f31e2137ac
commit 430ed6e34d
2 changed files with 33 additions and 11 deletions

View file

@ -110,7 +110,7 @@ def debugger():
# --------------------------------------------------
def hexdump(data, indent=0, width=16, show_header=True, show_offsets=True, show_ascii=True, use_colors=True, initial_offset=0, output=sys.stdout):
def hexdump(data, indent=0, width=16, show_header=True, show_offsets=True, show_ascii=True, use_colors=True, initial_offset=0, output=sys.stdout, skip_same=True):
"""
Writes a hex dump of `data` to `output`.
@ -120,6 +120,7 @@ def hexdump(data, indent=0, width=16, show_header=True, show_offsets=True, show_
If `show_ascii` is True, each line is suffixed with its ASCII representation. Unprintable characters
are replaced with a dot.
The `output` must implement a .write(str x) method. If `output` is None, the string is returned instead.
If `skip_same` is True, lines with identical content are abbreviated (omitted).
@while creating a hex dump
"""
@ -153,13 +154,10 @@ def hexdump(data, indent=0, width=16, show_header=True, show_offsets=True, show_
output_io.write(" ".join(line) + "\n")
skip_cnt = 0
last_hex_bytes = None
while data[ptr:]:
if indent:
output_io.write(" " * indent)
if show_offsets:
output_io.write(format_str %(initial_offset + ptr))
hex_bytes = []
ascii_bytes = []
@ -175,6 +173,29 @@ def hexdump(data, indent=0, width=16, show_header=True, show_offsets=True, show_
elif i == len(data):
hex_bytes.extend([" "] * (width - local_i))
ptr += width
# the rest is just rendering
if skip_same:
if hex_bytes == last_hex_bytes:
skip_cnt += 1
else:
if skip_cnt:
output_io.write("(skipped %d lines, %d B)\n" %(skip_cnt, skip_cnt * width))
skip_cnt = 0
last_hex_bytes = hex_bytes
if skip_cnt:
continue
if indent:
output_io.write(" " * indent)
if show_offsets:
output_io.write(format_str %(initial_offset + ptr))
if use_colors: output_io.write(text.render("<W>"))
output_io.write(" ".join(hex_bytes))
if use_colors: output_io.write(text.render("<.>"))
@ -185,8 +206,9 @@ def hexdump(data, indent=0, width=16, show_header=True, show_offsets=True, show_
output_io.write(text.render("<.>|") if use_colors else "|")
output_io.write("\n")
ptr += width
if skip_cnt:
output_io.write("(skipped %d lines, %d B)\n" %(skip_cnt, skip_cnt * width))
if not output:
output_io.seek(0)

View file

@ -4,5 +4,5 @@
major = 2 # VERSION_MAJOR_IDENTIFIER
minor = 1 # VERSION_MINOR_IDENTIFIER
# VERSION_LAST_MM 2.1
patch = 0 # VERSION_PATCH_IDENTIFIER
str = "2.1.0" # VERSION_STRING_IDENTIFIER
patch = 1 # VERSION_PATCH_IDENTIFIER
str = "2.1.1" # VERSION_STRING_IDENTIFIER