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 self.set_inner(value);
50 Ok(())
51 }
52
53 fn __getstate__(&self, py: Python) -> PyResult<Py<PyAny>> {
54 (self.to_string(),).into_py_any(py)
55 }
56
57 fn __reduce__(&self, py: Python) -> PyResult<Py<PyAny>> {
58 let safe_constructor = py.get_type::<Self>().getattr("_safe_constructor")?;
59 let state = self.__getstate__(py)?;
60 (safe_constructor, PyTuple::empty(py), state).into_py_any(py)
61 }
62
63 #[expect(clippy::needless_pass_by_value)]
64 fn __richcmp__(&self, other: Py<PyAny>, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
65 if let Ok(other) = other.extract::<Self>(py) {
66 match op {
67 CompareOp::Eq => self.eq(&other).into_py_any_unwrap(py),
68 CompareOp::Ne => self.ne(&other).into_py_any_unwrap(py),
69 CompareOp::Ge => self.ge(&other).into_py_any_unwrap(py),
70 CompareOp::Gt => self.gt(&other).into_py_any_unwrap(py),
71 CompareOp::Le => self.le(&other).into_py_any_unwrap(py),
72 CompareOp::Lt => self.lt(&other).into_py_any_unwrap(py),
73 }
74 } else {
75 py.NotImplemented()
76 }
77 }
78
79 fn __hash__(&self) -> isize {
80 let mut h = DefaultHasher::new();
81 self.hash(&mut h);
82 h.finish() as isize
83 }
84
85 fn __repr__(&self) -> String {
86 format!("{}('{}')", stringify!(Symbol), self)
87 }
88
89 fn __str__(&self) -> String {
90 self.to_string()
91 }
92
93 #[staticmethod]
94 #[pyo3(name = "from_str")]
95 fn py_from_str(value: &str) -> PyResult<Self> {
96 Self::new_checked(value).map_err(to_pyvalue_err)
97 }
98
99 #[getter]
100 #[pyo3(name = "value")]
101 fn py_value(&self) -> String {
102 self.to_string()
103 }
104
105 #[getter]
107 #[pyo3(name = "is_composite")]
108 fn py_is_composite(&self) -> bool {
109 self.is_composite()
110 }
111
112 #[getter]
119 #[pyo3(name = "root")]
120 fn py_root(&self) -> &str {
121 self.root()
122 }
123
124 #[getter]
129 #[pyo3(name = "topic")]
130 fn py_topic(&self) -> String {
131 self.topic()
132 }
133}