pyo3/
marshal.rs

1#![cfg(not(Py_LIMITED_API))]
2
3//! Support for the Python `marshal` format.
4
5use 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
12/// The current version of the marshal binary format.
13pub const VERSION: i32 = 4;
14
15/// Deprecated form of [`dumps_bound`]
16#[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
29/// Serialize an object to bytes using the Python built-in marshal module.
30///
31/// The built-in marshalling only supports a limited range of objects.
32/// The exact types supported depend on the version argument.
33/// The [`VERSION`] constant holds the highest version currently supported.
34///
35/// See the [Python documentation](https://docs.python.org/3/library/marshal.html) for more details.
36///
37/// # Examples
38/// ```
39/// # use pyo3::{marshal, types::PyDict, prelude::PyDictMethods};
40/// # pyo3::Python::with_gil(|py| {
41/// let dict = PyDict::new_bound(py);
42/// dict.set_item("aap", "noot").unwrap();
43/// dict.set_item("mies", "wim").unwrap();
44/// dict.set_item("zus", "jet").unwrap();
45///
46/// let bytes = marshal::dumps_bound(py, &dict, marshal::VERSION);
47/// # });
48/// ```
49pub 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/// Deprecated form of [`loads_bound`]
62#[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
74/// Deserialize an object from bytes using the Python built-in marshal module.
75pub 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}