String Fields
String fields parse and serialize text data with various encoding options.
Available Types
FixedString- Fixed-length string with paddingString- Variable-length string (length fromRef)NullTerminatedString- C-style null-terminated string
FixedString
Fixed-length string with optional padding:
from pystructs import Struct, FixedString
class UserRecord(Struct):
name = FixedString(length=20, encoding="utf-8", padding=b"\x00")
email = FixedString(length=50)
user = UserRecord(name="Alice", email="alice@example.com")
raw = user.to_bytes() # Name padded to 20 bytes
String (Variable-Length)
Variable-length string with length from another field:
from pystructs import Struct, UInt8, String, Ref
class Message(Struct):
length = UInt8()
text = String(length=Ref("length"))
msg = Message.parse(b"\x05Hello")
print(msg.text) # "Hello"
NullTerminatedString
C-style null-terminated string:
from pystructs import Struct, NullTerminatedString
class CString(Struct):
value = NullTerminatedString()
s = CString.parse(b"Hello\x00World")
print(s.value) # "Hello"
API Reference
- class pystructs.fields.strings.FixedString(length: int, encoding: str = 'utf-8', padding: bytes = b'\x00', default: str | None = None, required: bool = True, validators: List[Callable] | None = None)[source]
Fixed-length string field.
Parses a fixed number of bytes and decodes as string. Supports padding for serialization.
- Examples:
>>> class Record(Struct): ... name = FixedString(20, encoding='utf-8')
- class pystructs.fields.strings.String(length: int | Ref, encoding: str = 'utf-8', default: str | None = None, required: bool = True, validators: List[Callable] | None = None)[source]
Variable-length string field.
Length can be specified as a fixed integer or as a Ref to another field.
- Examples:
>>> class Message(Struct): ... length = UInt8() ... text = String(length=Ref('length'))
- get_size(instance: Struct) int[source]
Get the current size of this field.
- Args:
instance: The struct instance
- Returns:
Size in bytes
- class pystructs.fields.strings.NullTerminatedString(encoding: str = 'utf-8', include_null: bool = True, max_length: int | None = None, default: str | None = None, required: bool = True, validators: List[Callable] | None = None)[source]
Null-terminated string field.
Reads bytes until a null byte is encountered.
- Examples:
>>> class CString(Struct): ... name = NullTerminatedString()
- get_size(instance: Struct) int[source]
Get the size of this field.
Returns the size of the last parsed string (including null if applicable). For unparsed instances, returns 0.