2019-04-24 09:04:17 +00:00
|
|
|
use crate::ffi;
|
2019-04-25 13:05:59 +00:00
|
|
|
use crate::types::{PyAny, PyBytes};
|
|
|
|
use crate::{AsPyPointer, FromPyPointer, PyResult, Python};
|
|
|
|
use std::os::raw::{c_char, c_int};
|
2019-04-24 09:04:17 +00:00
|
|
|
|
|
|
|
/// 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 object.
|
|
|
|
/// See the [python documentation](https://docs.python.org/3/library/marshal.html) for more details.
|
2019-04-25 13:05:59 +00:00
|
|
|
pub fn dumps<'a>(py: Python<'a>, object: &impl AsPyPointer, version: i32) -> PyResult<&'a PyBytes> {
|
2019-04-24 09:04:17 +00:00
|
|
|
unsafe {
|
2019-04-25 13:05:59 +00:00
|
|
|
let bytes = ffi::PyMarshal_WriteObjectToString(object.as_ptr(), version as c_int);
|
|
|
|
FromPyPointer::from_owned_ptr_or_err(py, bytes)
|
2019-04-24 09:04:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Deserialize an object from bytes using the Python built-in marshal module.
|
2019-04-25 13:05:59 +00:00
|
|
|
pub fn loads<'a, B>(py: Python<'a>, data: &B) -> PyResult<&'a PyAny>
|
|
|
|
where
|
|
|
|
B: AsRef<[u8]> + ?Sized,
|
|
|
|
{
|
2019-04-24 09:04:17 +00:00
|
|
|
let data = data.as_ref();
|
2019-04-25 13:05:59 +00:00
|
|
|
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)
|
2019-04-24 09:04:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod test {
|
|
|
|
use super::*;
|
2019-04-25 13:05:59 +00:00
|
|
|
use crate::types::PyDict;
|
2019-04-24 09:04:17 +00:00
|
|
|
|
|
|
|
#[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();
|
|
|
|
|
2019-04-25 13:05:59 +00:00
|
|
|
let bytes = dumps(py, dict, VERSION)
|
|
|
|
.expect("marshalling failed")
|
|
|
|
.as_bytes();
|
|
|
|
let deserialzed = loads(py, bytes).expect("unmarshalling failed");
|
2019-04-24 09:04:17 +00:00
|
|
|
|
2019-04-25 13:05:59 +00:00
|
|
|
assert!(equal(py, dict, deserialzed));
|
2019-04-24 09:04:17 +00:00
|
|
|
}
|
|
|
|
|
2019-04-25 13:05:59 +00:00
|
|
|
fn equal(_py: Python, a: &impl AsPyPointer, b: &impl AsPyPointer) -> bool {
|
2019-04-24 09:04:17 +00:00
|
|
|
unsafe { ffi::PyObject_RichCompareBool(a.as_ptr(), b.as_ptr(), ffi::Py_EQ) != 0 }
|
|
|
|
}
|
|
|
|
}
|