nautilus_core/python/serialization.rs
1// -------------------------------------------------------------------------------------------------
2// Copyright (C) 2015-2025 Posei Systems Pty Ltd. All rights reserved.
3// https://poseitrader.io
4//
5// Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6// You may not use this file except in compliance with the License.
7// You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! (De)serialization utilities bridging Rust ↔︎ Python types.
17
18use pyo3::{prelude::*, types::PyDict};
19use serde::{Serialize, de::DeserializeOwned};
20
21use crate::python::to_pyvalue_err;
22
23/// Convert a Python dictionary to a Rust type that implements `DeserializeOwned`.
24///
25/// # Errors
26///
27/// Returns an error if:
28/// - The Python dictionary cannot be serialized to JSON.
29/// - The JSON string cannot be deserialized to type `T`.
30/// - The Python `json` module fails to import or execute.
31pub fn from_dict_pyo3<T>(py: Python<'_>, values: Py<PyDict>) -> Result<T, PyErr>
32where
33 T: DeserializeOwned,
34{
35 // Extract to JSON bytes
36 use crate::python::to_pyvalue_err;
37 let json_str: String = PyModule::import(py, "json")?
38 .call_method("dumps", (values,), None)?
39 .extract()?;
40
41 // Deserialize to object
42 let instance = serde_json::from_str(&json_str).map_err(to_pyvalue_err)?;
43 Ok(instance)
44}
45
46/// Convert a Rust type that implements `Serialize` to a Python dictionary.
47///
48/// # Errors
49///
50/// Returns an error if:
51/// - The Rust value cannot be serialized to JSON.
52/// - The JSON string cannot be parsed into a Python dictionary.
53/// - The Python `json` module fails to import or execute.
54pub fn to_dict_pyo3<T>(py: Python<'_>, value: &T) -> PyResult<Py<PyDict>>
55where
56 T: Serialize,
57{
58 let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
59
60 // Parse JSON into a Python dictionary
61 let py_dict: Py<PyDict> = PyModule::import(py, "json")?
62 .call_method("loads", (json_str,), None)?
63 .extract()?;
64 Ok(py_dict)
65}