kuba2k2 / datastruct

Combination of struct and dataclasses for easy parsing of binary formats
MIT License
6 stars 1 forks source link

How to use adapters? #1

Closed disazoz closed 2 months ago

disazoz commented 2 months ago

How to use adapters? For example, how to use ipv4_field adapter?

kuba2k2 commented 2 months ago

See here: https://github.com/tuya-cloudcutter/cloudcutter-universal/blob/master/cloudcutter/modules/dhcp/structs.py#L86 Note that this adapter uses a binary representation of the IP address (4 bytes), not a textual representation like a.b.c.d.

disazoz commented 2 months ago

Thanks a lot!

kuba2k2 commented 2 months ago

There's an UTF16LE field as well: https://github.com/kuba2k2/datastruct/blob/master/datastruct/adapters/misc.py#L16 However, I'm not sure if it will suit your use case. The text fields (strings, etc.) are a bit messy, because there are just so many ways of representing strings - fixed-length, variable length 0x00-padded, variable length with length prefix...

The existing fields try to cover most of the use cases, however (because of no documentation) it's advised to inspect the source code of datastruct first, to understand what they do.

The text() field is somewhat universal, it stores a fixed- or variable-length string (variable=True/False) that is padded to match the byte length (when encoding) and stripped when decoding. The vartext() is just the same field with variable=True. The utf16le_field() stores an UTF-16 string (str) that is terminated by 0x00. Note that the length is counted in bytes, not characters. There is also bytestr() which is just like using a field(length) to get a bytes property, but it additionally pads the string to match the length.