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::{AsPyPointer, PyResult, Python};
10use std::os::raw::c_int;
11
12pub const VERSION: i32 = 4;
14
15#[cfg(feature = "gil-refs")]
17#[deprecated(
18 since = "0.21.0",
19 note = "`dumps` will be replaced by `dumps_bound` in a future PyO3 version"
20)]
21pub fn dumps<'py>(
22 py: Python<'py>,
23 object: &impl AsPyPointer,
24 version: i32,
25) -> PyResult<&'py PyBytes> {
26 dumps_bound(py, object, version).map(Bound::into_gil_ref)
27}
28
29pub fn dumps_bound<'py>(
50 py: Python<'py>,
51 object: &impl AsPyPointer,
52 version: i32,
53) -> PyResult<Bound<'py, PyBytes>> {
54 unsafe {
55 ffi::PyMarshal_WriteObjectToString(object.as_ptr(), version as c_int)
56 .assume_owned_or_err(py)
57 .downcast_into_unchecked()
58 }
59}
60
61#[cfg(feature = "gil-refs")]
63#[deprecated(
64 since = "0.21.0",
65 note = "`loads` will be replaced by `loads_bound` in a future PyO3 version"
66)]
67pub fn loads<'py, B>(py: Python<'py>, data: &B) -> PyResult<&'py PyAny>
68where
69 B: AsRef<[u8]> + ?Sized,
70{
71 loads_bound(py, data).map(Bound::into_gil_ref)
72}
73
74pub fn loads_bound<'py, B>(py: Python<'py>, data: &B) -> PyResult<Bound<'py, PyAny>>
76where
77 B: AsRef<[u8]> + ?Sized,
78{
79 let data = data.as_ref();
80 unsafe {
81 ffi::PyMarshal_ReadObjectFromString(data.as_ptr().cast(), data.len() as isize)
82 .assume_owned_or_err(py)
83 }
84}
85
86#[cfg(test)]
87mod tests {
88 use super::*;
89 use crate::types::{bytes::PyBytesMethods, dict::PyDictMethods, PyDict};
90
91 #[test]
92 fn marshal_roundtrip() {
93 Python::with_gil(|py| {
94 let dict = PyDict::new_bound(py);
95 dict.set_item("aap", "noot").unwrap();
96 dict.set_item("mies", "wim").unwrap();
97 dict.set_item("zus", "jet").unwrap();
98
99 let pybytes = dumps_bound(py, &dict, VERSION).expect("marshalling failed");
100 let deserialized = loads_bound(py, pybytes.as_bytes()).expect("unmarshalling failed");
101
102 assert!(equal(py, &dict, &deserialized));
103 });
104 }
105
106 fn equal(_py: Python<'_>, a: &impl AsPyPointer, b: &impl AsPyPointer) -> bool {
107 unsafe { ffi::PyObject_RichCompareBool(a.as_ptr(), b.as_ptr(), ffi::Py_EQ) != 0 }
108 }
109}