Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions crates/stdlib/src/pystruct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,10 +289,17 @@ pub(crate) mod _struct {
}
}

#[derive(FromArgs)]
struct StructArgs {
#[pyarg(any)]
format: IntoStructFormatBytes,
}

impl Initializer for PyStruct {
type Args = IntoStructFormatBytes;
type Args = StructArgs;

fn init(zelf: &Py<Self>, fmt: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
let fmt = args.format;
// The format is read before anything is replaced, so a format that
// cannot be read leaves the object as it was.
let spec = fmt.format_spec(vm)?;
Expand Down
18 changes: 18 additions & 0 deletions extra_tests/snippets/stdlib_struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,3 +184,21 @@ def __index__(self):
buffer = bytearray(2)
struct.pack_into("<H", buffer, 0, ClearFormats())
assert buffer == b"\x2a\x00"


# Struct's format is positional-or-keyword, including inherited initialization.
class KeywordStruct(struct.Struct):
pass


for cls in (struct.Struct, KeywordStruct):
for fmt in (">h", b">h"):
s = cls(format=fmt)
assert s.format == ">h"
assert s.pack(7) == b"\x00\x07"
s.__init__(format=">hh")
assert s.unpack(b"\x00\x01\x00\x02") == (1, 2)
with assert_raises(struct.error):
s.__init__(format="$")
assert s.format == ">hh"
assert s.pack(1, 2) == b"\x00\x01\x00\x02"
Loading