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 core::ffi::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::attach(|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 // SAFETY: `object` is a valid object pointer, and a non-NULL return from
37 // `PyMarshal_WriteObjectToString` is a new owned reference to a bytes
38 // object.
39 unsafe {
40 ffi::PyMarshal_WriteObjectToString(object.as_ptr(), version as c_int)
41 .assume_owned_or_err(object.py())
42 .cast_into_unchecked()
43 }
44}
45
46/// Deserialize an object from bytes using the Python built-in marshal module.
47pub fn loads<'py, B>(py: Python<'py>, data: &B) -> PyResult<Bound<'py, PyAny>>
48where
49 B: AsRef<[u8]> + ?Sized,
50{
51 let data = data.as_ref();
52 // SAFETY: `data` and `len` come from the same byte slice, so `data` points
53 // to `len` readable bytes, and `PyMarshal_ReadObjectFromString` returns a
54 // new owned reference on success, or NULL with an exception set on error.
55 unsafe {
56 ffi::PyMarshal_ReadObjectFromString(data.as_ptr().cast(), data.len() as isize)
57 .assume_owned_or_err(py)
58 }
59}
60
61#[cfg(test)]
62mod tests {
63 use super::*;
64 use crate::types::{bytes::PyBytesMethods, dict::PyDictMethods, PyAnyMethods, PyDict};
65
66 #[test]
67 fn marshal_roundtrip() {
68 Python::attach(|py| {
69 let dict = PyDict::new(py);
70 dict.set_item("aap", "noot").unwrap();
71 dict.set_item("mies", "wim").unwrap();
72 dict.set_item("zus", "jet").unwrap();
73
74 let pybytes = dumps(&dict, VERSION).expect("marshalling failed");
75 let deserialized = loads(py, pybytes.as_bytes()).expect("unmarshalling failed");
76
77 assert!(dict.eq(&deserialized).unwrap());
78 });
79 }
80}