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::{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/// Serialize an object to bytes using the Python built-in marshal module.
16///
17/// The built-in marshalling only supports a limited range of objects.
18/// The exact types supported depend on the version argument.
19/// The [`VERSION`] constant holds the highest version currently supported.
20///
21/// See the [Python documentation](https://docs.python.org/3/library/marshal.html) for more details.
22///
23/// # Examples
24/// ```
25/// # use pyo3::{marshal, types::PyDict, prelude::PyDictMethods};
26/// # pyo3::Python::with_gil(|py| {
27/// let dict = PyDict::new(py);
28/// dict.set_item("aap", "noot").unwrap();
29/// dict.set_item("mies", "wim").unwrap();
30/// dict.set_item("zus", "jet").unwrap();
31///
32/// let bytes = marshal::dumps(&dict, marshal::VERSION);
33/// # });
34/// ```
35pub 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 form of [`dumps`].
44#[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
56/// Deserialize an object from bytes using the Python built-in marshal module.
57pub 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 form of [`loads`].
69#[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}
⚠️ Internal Docs ⚠️ Not Public API 👉 Official Docs Here