Created
January 5, 2021 14:50
-
-
Save daniil-konovalenko/41ce420a9bd1d714050bebbafcbfb7aa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use pyo3::prelude::*; | |
use pyo3::type_object::PyBorrowFlagLayout; | |
use pyo3::{PyClass, PyTypeInfo}; | |
use serde::{de, ser, Deserialize, Deserializer, Serialize, Serializer}; | |
pub fn serialize<S, T>(value: &Py<T>, serializer: S) -> Result<S::Ok, S::Error> | |
where | |
S: Serializer, | |
T: Serialize + PyClass, | |
{ | |
Python::with_gil(|py| { | |
value | |
.try_borrow(py) | |
.map_err(|e| ser::Error::custom(e.to_string()))? | |
.serialize(serializer) | |
}) | |
} | |
pub fn deserialize<'de, D, T>(deserializer: D) -> Result<Py<T>, D::Error> | |
where | |
D: Deserializer<'de>, | |
T: Deserialize<'de> + PyClass + Into<PyClassInitializer<T>>, | |
<T as PyTypeInfo>::BaseLayout: PyBorrowFlagLayout<<T as PyTypeInfo>::BaseType>, | |
{ | |
let res = T::deserialize(deserializer)?; | |
Python::with_gil(|py| Py::new(py, res).map_err(|e| de::Error::custom(e.to_string()))) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment