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