nautilus_model/identifiers/
component_id.rs1use std::{
19 fmt::{Debug, Display},
20 hash::Hash,
21};
22
23use nautilus_core::correctness::{
24 CorrectnessResult, CorrectnessResultExt, FAILED, check_valid_string_ascii,
25};
26use ustr::Ustr;
27
28use crate::identifiers::{ActorId, ExecAlgorithmId, StrategyId};
29
30#[repr(C)]
32#[derive(Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
33#[cfg_attr(
34 feature = "python",
35 pyo3::pyclass(module = "nautilus_trader.model", from_py_object)
36)]
37#[cfg_attr(
38 feature = "python",
39 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
40)]
41pub struct ComponentId(Ustr);
42
43impl ComponentId {
44 pub fn new_checked<T: AsRef<str>>(value: T) -> CorrectnessResult<Self> {
54 let value = value.as_ref();
55 check_valid_string_ascii(value, stringify!(value))?;
56 Ok(Self(Ustr::from(value)))
57 }
58
59 pub fn new<T: AsRef<str>>(value: T) -> Self {
65 Self::new_checked(value).expect_display(FAILED)
66 }
67
68 #[cfg_attr(not(feature = "python"), allow(dead_code))]
70 pub(crate) fn set_inner(&mut self, value: &str) {
71 self.0 = Ustr::from(value);
72 }
73
74 #[must_use]
76 pub fn inner(&self) -> Ustr {
77 self.0
78 }
79
80 #[must_use]
82 pub fn as_str(&self) -> &str {
83 self.0.as_str()
84 }
85}
86
87impl_from_identifier_for_component_id!(ActorId);
88impl_from_identifier_for_component_id!(ExecAlgorithmId);
89impl_from_identifier_for_component_id!(StrategyId);
90
91impl Debug for ComponentId {
92 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
93 write!(f, "\"{}\"", self.0)
94 }
95}
96
97impl Display for ComponentId {
98 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99 write!(f, "{}", self.0)
100 }
101}
102
103#[cfg(test)]
104mod tests {
105 use rstest::rstest;
106
107 use super::ComponentId;
108 use crate::identifiers::{ActorId, ExecAlgorithmId, StrategyId, stubs::*};
109
110 #[rstest]
111 fn test_string_reprs(component_risk_engine: ComponentId) {
112 assert_eq!(component_risk_engine.as_str(), "RiskEngine");
113 assert_eq!(format!("{component_risk_engine}"), "RiskEngine");
114 }
115
116 #[rstest]
117 fn test_from_actor_id() {
118 let component_id = ComponentId::from(ActorId::from("MyActor"));
119 assert_eq!(component_id, ComponentId::from("MyActor"));
120 }
121
122 #[rstest]
123 fn test_from_exec_algorithm_id() {
124 let component_id = ComponentId::from(ExecAlgorithmId::from("TWAP"));
125 assert_eq!(component_id, ComponentId::from("TWAP"));
126 }
127
128 #[rstest]
129 fn test_from_strategy_id() {
130 let component_id = ComponentId::from(StrategyId::from("EMACross-001"));
131 assert_eq!(component_id, ComponentId::from("EMACross-001"));
132 }
133
134 #[rstest]
135 #[should_panic(expected = "Condition failed: invalid string for 'value', was empty")]
136 fn test_new_with_empty_string_panics_with_display_format() {
137 let _ = ComponentId::new("");
138 }
139}