nautilus_model/python/identifiers/
symbol.rs1use std::{
17 collections::hash_map::DefaultHasher,
18 hash::{Hash, Hasher},
19};
20
21use nautilus_core::python::{IntoPyObjectNautilusExt, to_pyvalue_err};
22use pyo3::{
23 IntoPyObjectExt,
24 prelude::*,
25 pyclass::CompareOp,
26 types::{PyString, PyTuple},
27};
28
29use crate::identifiers::symbol::Symbol;
30
31#[pymethods]
32#[pyo3_stub_gen::derive::gen_stub_pymethods]
33impl Symbol {
34 #[new]
36 fn py_new(value: &str) -> PyResult<Self> {
37 Self::new_checked(value).map_err(to_pyvalue_err)
38 }
39
40 #[staticmethod]
41 fn _safe_constructor() -> Self {
42 Self::from("NULL")
43 }
44
45 fn __setstate__(&mut self, state: &Bound<'_, PyAny>) -> PyResult<()> {
46 let py_tuple: &Bound<'_, PyTuple> = state.cast::<PyTuple>()?;
47 let binding = py_tuple.get_item(0)?;
48 let value = binding.cast::<PyString>()?.extract::<&str>()?;
49 let validated = Self::new_checked(value).map_err(to_pyvalue_err)?;
50 self.set_inner(validated.as_str());
51 Ok(())
52 }
53
54 fn __getstate__(&self, py: Python) -> PyResult<Py<PyAny>> {
55 (self.to_string(),).into_py_any(py)
56 }
57
58 fn __reduce__(&self, py: Python) -> PyResult<Py<PyAny>> {
59 let safe_constructor = py.get_type::<Self>().getattr("_safe_constructor")?;
60 let state = self.__getstate__(py)?;
61 (safe_constructor, PyTuple::empty(py), state).into_py_any(py)
62 }
63
64 #[expect(clippy::needless_pass_by_value)]
65 fn __richcmp__(&self, other: Py<PyAny>, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
66 if let Ok(other) = other.extract::<Self>(py) {
67 match op {
68 CompareOp::Eq => self.eq(&other).into_py_any_unwrap(py),
69 CompareOp::Ne => self.ne(&other).into_py_any_unwrap(py),
70 CompareOp::Ge => self.ge(&other).into_py_any_unwrap(py),
71 CompareOp::Gt => self.gt(&other).into_py_any_unwrap(py),
72 CompareOp::Le => self.le(&other).into_py_any_unwrap(py),
73 CompareOp::Lt => self.lt(&other).into_py_any_unwrap(py),
74 }
75 } else {
76 py.NotImplemented()
77 }
78 }
79
80 fn __hash__(&self) -> isize {
81 let mut h = DefaultHasher::new();
82 self.hash(&mut h);
83 h.finish() as isize
84 }
85
86 fn __repr__(&self) -> String {
87 format!("{}('{}')", stringify!(Symbol), self)
88 }
89
90 fn __str__(&self) -> String {
91 self.to_string()
92 }
93
94 #[staticmethod]
95 #[pyo3(name = "from_str")]
96 fn py_from_str(value: &str) -> PyResult<Self> {
97 Self::new_checked(value).map_err(to_pyvalue_err)
98 }
99
100 #[getter]
101 #[pyo3(name = "value")]
102 fn py_value(&self) -> String {
103 self.to_string()
104 }
105
106 #[getter]
108 #[pyo3(name = "is_composite")]
109 fn py_is_composite(&self) -> bool {
110 self.is_composite()
111 }
112
113 #[getter]
120 #[pyo3(name = "root")]
121 fn py_root(&self) -> &str {
122 self.root()
123 }
124
125 #[getter]
130 #[pyo3(name = "topic")]
131 fn py_topic(&self) -> String {
132 self.topic()
133 }
134}