Files
adblock
addr
addr2line
adler
aho_corasick
backtrace
base64
bitflags
byteorder
cfg_if
crc32fast
ctor
either
error_chain
flate2
foreign_types
foreign_types_shared
ghost
gimli
idna
indoc
indoc_impl
instant
inventory
inventory_impl
itertools
lazy_static
libc
lock_api
log
matches
memchr
miniz_oxide
native_tls
num_traits
object
once_cell
openssl
openssl_probe
openssl_sys
parking_lot
parking_lot_core
paste
paste_impl
percent_encoding
proc_macro2
proc_macro_hack
psl
psl_codegen
psl_lexer
pyo3
pyo3_derive_backend
pyo3cls
quote
regex
regex_syntax
rental
rental_impl
rmp
rmp_serde
rustc_demangle
scopeguard
seahash
sequence_trie
serde
serde_derive
smallvec
stable_deref_trait
syn
thread_local
tinyvec
twoway
unchecked_index
unicode_bidi
unicode_normalization
unicode_xid
unindent
url
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
use crate::ffi;
use crate::types::{PyAny, PyBytes};
use crate::{AsPyPointer, FromPyPointer, PyResult, Python};
use std::os::raw::{c_char, c_int};

/// The current version of the marshal binary format.
pub const VERSION: i32 = 4;

/// Serialize an object to bytes using the Python built-in marshal module.
///
/// The built-in marshalling only supports a limited range of objects.
/// The exact types supported depend on the version argument.
/// The [`VERSION`] constant holds the highest version currently supported.
///
/// See the [Python documentation](https://docs.python.org/3/library/marshal.html) for more details.
///
/// # Example:
/// ```
/// # use pyo3::{marshal, types::PyDict};
/// # let gil = pyo3::Python::acquire_gil();
/// # let py = gil.python();
/// #
/// let dict = PyDict::new(py);
/// dict.set_item("aap", "noot").unwrap();
/// dict.set_item("mies", "wim").unwrap();
/// dict.set_item("zus", "jet").unwrap();
///
/// let bytes = marshal::dumps(py, dict, marshal::VERSION);
/// ```
pub fn dumps<'a>(py: Python<'a>, object: &impl AsPyPointer, version: i32) -> PyResult<&'a PyBytes> {
    unsafe {
        let bytes = ffi::PyMarshal_WriteObjectToString(object.as_ptr(), version as c_int);
        FromPyPointer::from_owned_ptr_or_err(py, bytes)
    }
}

/// Deserialize an object from bytes using the Python built-in marshal module.
pub fn loads<'a, B>(py: Python<'a>, data: &B) -> PyResult<&'a PyAny>
where
    B: AsRef<[u8]> + ?Sized,
{
    let data = data.as_ref();
    unsafe {
        let c_str = data.as_ptr() as *const c_char;
        let object = ffi::PyMarshal_ReadObjectFromString(c_str, data.len() as isize);
        FromPyPointer::from_owned_ptr_or_err(py, object)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::types::PyDict;

    #[test]
    fn marhshal_roundtrip() {
        let gil = Python::acquire_gil();
        let py = gil.python();

        let dict = PyDict::new(py);
        dict.set_item("aap", "noot").unwrap();
        dict.set_item("mies", "wim").unwrap();
        dict.set_item("zus", "jet").unwrap();

        let bytes = dumps(py, dict, VERSION)
            .expect("marshalling failed")
            .as_bytes();
        let deserialzed = loads(py, bytes).expect("unmarshalling failed");

        assert!(equal(py, dict, deserialzed));
    }

    fn equal(_py: Python, a: &impl AsPyPointer, b: &impl AsPyPointer) -> bool {
        unsafe { ffi::PyObject_RichCompareBool(a.as_ptr(), b.as_ptr(), ffi::Py_EQ) != 0 }
    }
}