nautilus_model/python/identifiers/
trade_id.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.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#![allow(deprecated)]
17// TODO: We still rely on `IntoPy` for now, so temporarily ignore
18// these deprecations until fully migrated to `IntoPyObject`.
19
20use std::{
21    collections::hash_map::DefaultHasher,
22    ffi::CString,
23    hash::{Hash, Hasher},
24};
25
26use nautilus_core::python::to_pyvalue_err;
27use pyo3::{
28    prelude::*,
29    pyclass::CompareOp,
30    types::{PyString, PyTuple},
31};
32
33use crate::identifiers::trade_id::{TradeId, TRADE_ID_LEN};
34
35#[pymethods]
36impl TradeId {
37    #[new]
38    fn py_new(value: &str) -> PyResult<Self> {
39        Self::new_checked(value).map_err(to_pyvalue_err)
40    }
41
42    fn __setstate__(&mut self, state: &Bound<'_, PyAny>) -> PyResult<()> {
43        let py_tuple: &Bound<'_, PyTuple> = state.downcast::<PyTuple>()?;
44        let binding = py_tuple.get_item(0)?;
45        let value_str = binding.downcast::<PyString>()?.extract::<&str>()?;
46
47        // TODO: Extract this to single function
48        let c_string = CString::new(value_str).expect("`CString` conversion failed");
49        let bytes = c_string.as_bytes_with_nul();
50        let mut value = [0; TRADE_ID_LEN];
51        value[..bytes.len()].copy_from_slice(bytes);
52        self.value = value;
53
54        Ok(())
55    }
56
57    fn __getstate__(&self, py: Python) -> PyResult<PyObject> {
58        Ok((self.to_string(),).to_object(py))
59    }
60
61    fn __reduce__(&self, py: Python) -> PyResult<PyObject> {
62        let safe_constructor = py.get_type_bound::<Self>().getattr("_safe_constructor")?;
63        let state = self.__getstate__(py)?;
64        Ok((safe_constructor, PyTuple::empty(py), state).to_object(py))
65    }
66
67    #[staticmethod]
68    fn _safe_constructor() -> Self {
69        Self::from("NULL")
70    }
71
72    fn __richcmp__(&self, other: PyObject, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
73        if let Ok(other) = other.extract::<Self>(py) {
74            match op {
75                CompareOp::Eq => self.eq(&other).into_py(py),
76                CompareOp::Ne => self.ne(&other).into_py(py),
77                CompareOp::Ge => self.ge(&other).into_py(py),
78                CompareOp::Gt => self.gt(&other).into_py(py),
79                CompareOp::Le => self.le(&other).into_py(py),
80                CompareOp::Lt => self.lt(&other).into_py(py),
81            }
82        } else {
83            py.NotImplemented()
84        }
85    }
86
87    fn __hash__(&self) -> isize {
88        let mut h = DefaultHasher::new();
89        self.hash(&mut h);
90        h.finish() as isize
91    }
92
93    fn __repr__(&self) -> String {
94        format!("{}('{}')", stringify!(TradeId), self)
95    }
96
97    fn __str__(&self) -> String {
98        self.to_string()
99    }
100
101    #[getter]
102    fn value(&self) -> String {
103        self.to_string()
104    }
105
106    #[staticmethod]
107    #[pyo3(name = "from_str")]
108    fn py_from_str(value: &str) -> PyResult<Self> {
109        Self::new_checked(value).map_err(to_pyvalue_err)
110    }
111}
112
113impl ToPyObject for TradeId {
114    fn to_object(&self, py: Python) -> PyObject {
115        self.into_py(py)
116    }
117}