Skip to content

Commit 3bf7d05

Browse files
committed
feat: implement a better to_str
1 parent a6b5924 commit 3bf7d05

3 files changed

Lines changed: 15 additions & 3 deletions

File tree

libdestruct/common/array/array_impl.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,11 @@
88

99
from typing import TYPE_CHECKING
1010

11+
from libdestruct.c.c_integer_types import _c_integer
12+
from libdestruct.c.ctypes_generic import _ctypes_generic
1113
from libdestruct.common.array.array import array
1214
from libdestruct.common.obj import obj
15+
from libdestruct.common.struct.struct import struct
1316

1417
if TYPE_CHECKING: # pragma: no cover
1518
from collections.abc import Generator
@@ -59,7 +62,16 @@ def to_bytes(self: array_impl) -> bytes:
5962

6063
def to_str(self: array_impl, indent: int = 0) -> str:
6164
"""Return the string representation of the array."""
62-
return "[" + ", ".join(x.to_str(indent) for x in self) + "]"
65+
if self._count == 0:
66+
return "[]"
67+
68+
# If the backing type is a struct, we need to indent the output differently
69+
if issubclass(self.backing_type, struct):
70+
padding = ",\n" + " " * (indent + 4)
71+
spacing = " " * (indent + 4)
72+
return "[\n" + spacing + padding.join(x.to_str(indent + 4) for x in self) + "\n" + " " * (indent) + "]"
73+
74+
return "[" + ", ".join(x.to_str(indent + 4) for x in self) + "]"
6375

6476
def __setitem__(self: array_impl, index: int, value: obj) -> None:
6577
"""Set an item in the array."""

libdestruct/common/obj.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ def value(self: obj, value: object) -> None:
110110

111111
def to_str(self: obj, indent: int = 0) -> str:
112112
"""Return a string representation of the object."""
113-
return f"{' ' * indent}{self.get()}"
113+
return f"{self.get()}"
114114

115115
def pdiff(self: obj) -> str:
116116
"""Return a string representation of the difference between the current value and the frozen value."""

libdestruct/common/struct/struct_impl.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ def to_str(self: struct_impl, indent: int = 0) -> str:
104104
"""Return a string representation of the struct."""
105105
members = ",\n".join(
106106
[
107-
f"{' ' * (indent + 4)}{name}: {member.to_str(indent + 4) if isinstance(member, struct) else member.to_str(0)}"
107+
f"{' ' * (indent + 4)}{name}: {member.to_str(indent + 4)}"
108108
for name, member in self._members.items()
109109
],
110110
)

0 commit comments

Comments
 (0)