1#![cfg(not(Py_LIMITED_API))]
2
3use crate::ffi_ptr_ext::FfiPtrExt;
6use crate::py_result_ext::PyResultExt;
7use crate::types::{PyAny, PyBytes};
8use crate::{ffi, Bound};
9use crate::{PyResult, Python};
10use std::os::raw::c_int;
11
12pub const VERSION: i32 = 4;
14
15pub fn dumps<'py>(object: &Bound<'py, PyAny>, version: i32) -> PyResult<Bound<'py, PyBytes>> {
36 unsafe {
37 ffi::PyMarshal_WriteObjectToString(object.as_ptr(), version as c_int)
38 .assume_owned_or_err(object.py())
39 .downcast_into_unchecked()
40 }
41}
42
43#[deprecated(since = "0.23.0", note = "use `dumps` instead")]
45pub fn dumps_bound<'py>(
46 py: Python<'py>,
47 object: &impl crate::AsPyPointer,
48 version: i32,
49) -> PyResult<Bound<'py, PyBytes>> {
50 dumps(
51 unsafe { object.as_ptr().assume_borrowed(py) }.as_any(),
52 version,
53 )
54}
55
56pub fn loads<'py, B>(py: Python<'py>, data: &B) -> PyResult<Bound<'py, PyAny>>
58where
59 B: AsRef<[u8]> + ?Sized,
60{
61 let data = data.as_ref();
62 unsafe {
63 ffi::PyMarshal_ReadObjectFromString(data.as_ptr().cast(), data.len() as isize)
64 .assume_owned_or_err(py)
65 }
66}
67
68#[deprecated(since = "0.23.0", note = "renamed to `loads`")]
70pub fn loads_bound<'py>(py: Python<'py>, data: &[u8]) -> PyResult<Bound<'py, PyAny>> {
71 loads(py, data)
72}
73
74#[cfg(test)]
75mod tests {
76 use super::*;
77 use crate::types::{bytes::PyBytesMethods, dict::PyDictMethods, PyAnyMethods, PyDict};
78
79 #[test]
80 fn marshal_roundtrip() {
81 Python::with_gil(|py| {
82 let dict = PyDict::new(py);
83 dict.set_item("aap", "noot").unwrap();
84 dict.set_item("mies", "wim").unwrap();
85 dict.set_item("zus", "jet").unwrap();
86
87 let pybytes = dumps(&dict, VERSION).expect("marshalling failed");
88 let deserialized = loads(py, pybytes.as_bytes()).expect("unmarshalling failed");
89
90 assert!(dict.eq(&deserialized).unwrap());
91 });
92 }
93}