nautilus_model/python/identifiers/
trade_id.rs1#![allow(deprecated)]
17use 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 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}