Visitar URL original
marshal.dumps: support buffer protocol objects · RustPython/RustPython@e870eb6 · GitHub
Skip to content

Commit e870eb6

Browse files
committed
marshal.dumps: support buffer protocol objects
Add fallback to buffer protocol in marshal.dumps for bytes-like objects (memoryview, array.array, etc.) that don't match any specific type in the Dumpable trait. Remove expectedFailure from test_memoryview and test_array in test_marshal.
1 parent 2a403a2 commit e870eb6

2 files changed

Lines changed: 17 additions & 8 deletions

File tree

‎Lib/test/test_marshal.py‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -233,14 +233,12 @@ def test_bytearray(self):
233233
new = marshal.loads(marshal.dumps(b))
234234
self.assertEqual(type(new), bytes)
235235

236-
@unittest.expectedFailure # TODO: RUSTPYTHON
237236
def test_memoryview(self):
238237
b = memoryview(b"abc")
239238
self.helper(b)
240239
new = marshal.loads(marshal.dumps(b))
241240
self.assertEqual(type(new), bytes)
242241

243-
@unittest.expectedFailure # TODO: RUSTPYTHON
244242
def test_array(self):
245243
a = array.array('B', b"abc")
246244
new = marshal.loads(marshal.dumps(a))

‎crates/vm/src/stdlib/marshal.rs‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -99,14 +99,25 @@ mod decl {
9999
) -> PyResult<PyBytes> {
100100
use marshal::Dumpable;
101101
let mut buf = Vec::new();
102-
value
102+
let result = value
103103
.with_dump(|val| marshal::serialize_value(&mut buf, val))
104-
.unwrap_or_else(Err)
105-
.map_err(|DumpError| {
106-
vm.new_not_implemented_error(
107-
"TODO: not implemented yet or marshal unsupported type",
104+
.unwrap_or_else(Err);
105+
if result.is_err() {
106+
// Fall back: try buffer protocol for bytes-like objects
107+
if let Ok(bytes_like) = ArgBytesLike::try_from_object(vm, value) {
108+
let borrowed = bytes_like.borrow_buf();
109+
buf.clear();
110+
marshal::serialize_value::<Vec<u8>, PyObjectRef>(
111+
&mut buf,
112+
marshal::DumpableValue::Bytes(&borrowed),
108113
)
109-
})?;
114+
.unwrap_or_else(|DumpError| {});
115+
return Ok(PyBytes::from(buf));
116+
}
117+
return Err(vm.new_not_implemented_error(
118+
"TODO: not implemented yet or marshal unsupported type",
119+
));
120+
}
110121
Ok(PyBytes::from(buf))
111122
}
112123

0 commit comments

Comments
 (0)