Skip to content

Commit

Permalink
add some useful arguments to unpack method to unpack invalid strings
Browse files Browse the repository at this point in the history
  • Loading branch information
lu-maca committed Oct 27, 2023
1 parent 8a97a36 commit 5145ef1
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions packed_struct/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,14 +285,26 @@ def set_data(self, **kwargs):
# if the key exists, we can set the value
self._data[key].value = item

def unpack(self, byte_string: bytes, byte_endianness: str = "=") -> dict:
def unpack(
self,
byte_string: bytes,
byte_endianness: str = "=",
text_encoding: str = "utf-8",
text_errors: str = "strict",
) -> dict:
"""Unpack `byte_string: bytes` according to the format of the struct.
Text fields are decoded with given encoding `text_encoding` and error
handling as given by `text_errors` (both passed to `bytes.decode()`).
Return a dict containing data.
Arguments:
* `byte_string`: the byte string you want to unpack
* `byte_endianness`: shall be "big", "little" or "=" (default: "=", i.e. native)
* `text_encoding`: passed to `bytes.decode()`
* `text_errors`: passed to `bytes.decode()`
"""
if not byte_endianness in BYTE_ENDIANNESS.keys():
raise Exception("Byte endianness shall be 'little', 'big' or '='")
Expand All @@ -302,7 +314,9 @@ def unpack(self, byte_string: bytes, byte_endianness: str = "=") -> dict:
# set unpack format
fmt = f"{self.fmt}{B_endianness}"

unpacked = bstruct.unpack(fmt, byte_string)
unpacked = bstruct.unpack(
fmt, byte_string, text_encoding=text_encoding, text_errors=text_errors
)
i = 0

def recursive_set(dict_item, idx: int):
Expand Down

0 comments on commit 5145ef1

Please sign in to comment.