Skip to content

Commit 1dbf640

Browse files
committed
Add inspect method
1 parent f3fedb5 commit 1dbf640

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

cstruct/abstract.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
from typing import Any, BinaryIO, List, Dict, Optional, Type, Tuple, Union
3030
import hashlib
3131
import sys
32+
from io import StringIO
3233
from enum import IntEnum, EnumMeta, _EnumDict
3334
from unicodedata import name
3435
from .base import STRUCTS, ENUMS, DEFAULT_ENUM_SIZE
@@ -226,6 +227,33 @@ def sizeof(cls) -> int:
226227
"Structure size in bytes (flexible array member size is omitted)"
227228
return cls.__size__
228229

230+
def inspect(self, start_addr: Optional[int] = None, end_addr: Optional[int] = None) -> str:
231+
"""
232+
Return memory content in hexadecimal
233+
234+
Args:
235+
start_addr: start address
236+
end_addr: end address
237+
"""
238+
buffer = StringIO()
239+
if hasattr(self, '__mem__'):
240+
mem = self.__mem__
241+
else:
242+
mem = self.pack()
243+
for i in range(start_addr or 0, end_addr or self.size, 16):
244+
row = mem[i : i + 16]
245+
buffer.write(f"{i:08x} ")
246+
for j, c in enumerate(row):
247+
separator = ' ' if j == 7 else ''
248+
buffer.write(f" {c:02x}{separator}")
249+
buffer.write(" |")
250+
for c in row:
251+
buffer.write(chr(c) if c >= 32 and c < 127 else '.')
252+
buffer.write("|")
253+
buffer.write("\n")
254+
buffer.seek(0, 0)
255+
return buffer.read()
256+
229257
def __eq__(self, other: Any) -> bool:
230258
return other is not None and isinstance(other, self.__class__) and self.__dict__ == other.__dict__
231259

0 commit comments

Comments
 (0)