nautilus_model/identifiers/
client_order_id.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 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 client order ID (assigned by the Nautilus system).
17
18use std::{
19    fmt::{Debug, Display, Formatter},
20    hash::Hash,
21};
22
23use nautilus_core::correctness::{check_valid_string, FAILED};
24use ustr::Ustr;
25
26/// Represents a valid client order ID (assigned by the Nautilus system).
27#[repr(C)]
28#[derive(Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
29#[cfg_attr(
30    feature = "python",
31    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.model")
32)]
33pub struct ClientOrderId(Ustr);
34
35impl ClientOrderId {
36    /// Creates a new [`ClientOrderId`] instance with correctness checking.
37    ///
38    /// # Errors
39    ///
40    /// This function returns an error:
41    /// - If `value` is not a valid string.
42    ///
43    /// # Notes
44    ///
45    /// PyO3 requires a `Result` type for proper error handling and stacktrace printing in Python.
46    pub fn new_checked<T: AsRef<str>>(value: T) -> anyhow::Result<Self> {
47        let value = value.as_ref();
48        check_valid_string(value, stringify!(value))?;
49        Ok(Self(Ustr::from(value)))
50    }
51
52    /// Creates a new [`ClientOrderId`] instance.
53    ///
54    /// # Panics
55    ///
56    /// This function panics:
57    /// - If `value` is not a valid string.
58    pub fn new<T: AsRef<str>>(value: T) -> Self {
59        Self::new_checked(value).expect(FAILED)
60    }
61
62    /// Sets the inner identifier value.
63    pub(crate) fn set_inner(&mut self, value: &str) {
64        self.0 = Ustr::from(value);
65    }
66
67    /// Returns the inner identifier value.
68    #[must_use]
69    pub fn inner(&self) -> Ustr {
70        self.0
71    }
72
73    /// Returns the inner identifier value as a string slice.
74    #[must_use]
75    pub fn as_str(&self) -> &str {
76        self.0.as_str()
77    }
78}
79
80impl Debug for ClientOrderId {
81    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
82        write!(f, "{:?}", self.0)
83    }
84}
85
86impl Display for ClientOrderId {
87    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
88        write!(f, "{}", self.0)
89    }
90}
91
92#[must_use]
93pub fn optional_ustr_to_vec_client_order_ids(s: Option<Ustr>) -> Option<Vec<ClientOrderId>> {
94    s.map(|ustr| {
95        let s_str = ustr.to_string();
96        s_str
97            .split(',')
98            .map(ClientOrderId::new)
99            .collect::<Vec<ClientOrderId>>()
100    })
101}
102
103#[must_use]
104pub fn optional_vec_client_order_ids_to_ustr(vec: Option<Vec<ClientOrderId>>) -> Option<Ustr> {
105    vec.map(|client_order_ids| {
106        let s: String = client_order_ids
107            .into_iter()
108            .map(|id| id.to_string())
109            .collect::<Vec<String>>()
110            .join(",");
111        Ustr::from(&s)
112    })
113}
114
115////////////////////////////////////////////////////////////////////////////////
116// Tests
117////////////////////////////////////////////////////////////////////////////////
118#[cfg(test)]
119mod tests {
120    use rstest::rstest;
121    use ustr::Ustr;
122
123    use super::ClientOrderId;
124    use crate::identifiers::{
125        client_order_id::{
126            optional_ustr_to_vec_client_order_ids, optional_vec_client_order_ids_to_ustr,
127        },
128        stubs::*,
129    };
130
131    #[rstest]
132    fn test_string_reprs(client_order_id: ClientOrderId) {
133        assert_eq!(client_order_id.as_str(), "O-19700101-000000-001-001-1");
134        assert_eq!(format!("{client_order_id}"), "O-19700101-000000-001-001-1");
135    }
136
137    #[rstest]
138    fn test_optional_ustr_to_vec_client_order_ids() {
139        // Test with None
140        assert_eq!(optional_ustr_to_vec_client_order_ids(None), None);
141
142        // Test with Some
143        let ustr = Ustr::from("id1,id2,id3");
144        let client_order_ids = optional_ustr_to_vec_client_order_ids(Some(ustr)).unwrap();
145        assert_eq!(client_order_ids[0].as_str(), "id1");
146        assert_eq!(client_order_ids[1].as_str(), "id2");
147        assert_eq!(client_order_ids[2].as_str(), "id3");
148    }
149
150    #[rstest]
151    fn test_optional_vec_client_order_ids_to_ustr() {
152        // Test with None
153        assert_eq!(optional_vec_client_order_ids_to_ustr(None), None);
154
155        // Test with Some
156        let client_order_ids = vec![
157            ClientOrderId::from("id1"),
158            ClientOrderId::from("id2"),
159            ClientOrderId::from("id3"),
160        ];
161        let ustr = optional_vec_client_order_ids_to_ustr(Some(client_order_ids)).unwrap();
162        assert_eq!(ustr.to_string(), "id1,id2,id3");
163    }
164}