-
Notifications
You must be signed in to change notification settings - Fork 5
Open
Description
Thank you for a useful module.
I found it convenient for C-style null-terminated strings to automatically strip all trailing nulls and convert to Python strings.
I added a new annotation:
ut_host: Annotated[str, dcs.Cstring(256)]
In types.py:
class Cstring(field.Field[str]):
field_type = str
def __init__(self, n: object):
if not isinstance(n, int) or n < 1:
raise ValueError("str length must be positive non-zero int")
self.size = n
def format(self) -> str:
return f"{self.size}s"
def __repr__(self) -> str:
return f"{type(self).__name__}({self.size})"
def unpack(self,b: bytes) -> str:
if b[-1]: raise ValueError(f"String {b!r} does not end in NULL")
return b.partition(b'\x00')[0].decode()
def pack(self,s: str) -> bytes:
b=s.encode()
if len(b)>=self.size: raise ValueError(f"String {s} is longer than {self.size}")
return b.ljust(self.size,b'\x00')
def validate_default(self, s: str) -> None:
if len(s) >= self.size:
raise ValueError(f"String {s} is longer than {self.size}")
In dataclass.py:
def _flattened_attrs(self, outer_self: T) -> list[Any]:
...
for field in self._fields:
attr = getattr(outer_self, field.name)
if isinstance(field.field, Field) and hasattr(field.field,'pack'):
attrs.append(field.field.pack(attr))
else:
self._flatten_attr(attrs, attr)
...
def _generate_args_recursively(
...
elif isinstance(field, Field) and hasattr(field,'unpack'): :
yield field.unpack(next(args))
else:
yield field_type(next(args))
Perhaps you can consider adding a similar functionality as standard.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels