Skip to main content

nautilus_model/identifiers/
component_id.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Represents a valid component ID.
17
18use 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/// Represents a valid component ID.
31#[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    /// Creates a new [`ComponentId`] instance with correctness checking.
45    ///
46    /// # Errors
47    ///
48    /// Returns an error if `value` is not a valid string.
49    ///
50    /// # Notes
51    ///
52    /// PyO3 requires a `Result` type for proper error handling and stacktrace printing in Python.
53    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    /// Creates a new [`ComponentId`] instance.
60    ///
61    /// # Panics
62    ///
63    /// Panics if `value` is not a valid string.
64    pub fn new<T: AsRef<str>>(value: T) -> Self {
65        Self::new_checked(value).expect_display(FAILED)
66    }
67
68    /// Sets the inner identifier value.
69    #[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    /// Returns the inner identifier value.
75    #[must_use]
76    pub fn inner(&self) -> Ustr {
77        self.0
78    }
79
80    /// Returns the inner identifier value as a string slice.
81    #[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}