Skip to content

Fix struct tests #5813

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 22, 2025
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
4 changes: 0 additions & 4 deletions Lib/test/test_struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -718,8 +718,6 @@ def test__struct_types_immutable(self):
cls.x = 1


# TODO: RUSTPYTHON
@unittest.expectedFailure
def test_issue35714(self):
# Embedded null characters should not be allowed in format strings.
for s in '\0', '2\0i', b'\0':
Expand Down Expand Up @@ -790,8 +788,6 @@ def __init__(self):
my_struct = MyStruct()
self.assertEqual(my_struct.pack(12345), b'\x30\x39')

# TODO: RUSTPYTHON
@unittest.expectedFailure
def test_repr(self):
s = struct.Struct('=i2H')
self.assertEqual(repr(s), f'Struct({s.format!r})')
Expand Down
11 changes: 9 additions & 2 deletions stdlib/src/pystruct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub(crate) mod _struct {
function::{ArgBytesLike, ArgMemoryBuffer, PosArgs},
match_class,
protocol::PyIterReturn,
types::{Constructor, IterNext, Iterable, SelfIter},
types::{Constructor, IterNext, Iterable, Representable, SelfIter},
};
use crossbeam_utils::atomic::AtomicCell;

Expand Down Expand Up @@ -251,7 +251,7 @@ pub(crate) mod _struct {
}
}

#[pyclass(with(Constructor))]
#[pyclass(with(Constructor, Representable))]
impl PyStruct {
#[pygetset]
fn format(&self) -> PyStrRef {
Expand Down Expand Up @@ -306,6 +306,13 @@ pub(crate) mod _struct {
}
}

impl Representable for PyStruct {
#[inline]
fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
Ok(format!("Struct('{}')", zelf.format.as_str()))
}
}

// seems weird that this is part of the "public" API, but whatever
// TODO: implement a format code->spec cache like CPython does?
#[pyfunction]
Expand Down
6 changes: 6 additions & 0 deletions vm/src/buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,12 @@ impl FormatCode {
let c = chars
.next()
.ok_or_else(|| "repeat count given without format specifier".to_owned())?;

// Check for embedded null character
if c == 0 {
return Err("embedded null character".to_owned());
}

let code = FormatType::try_from(c)
.ok()
.filter(|c| match c {
Expand Down
Loading