nautilus_model/identifiers/account_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 account ID.
17
18use std::{
19 fmt::{Debug, Display, Formatter},
20 hash::Hash,
21};
22
23use nautilus_core::correctness::{check_string_contains, check_valid_string, FAILED};
24use ustr::Ustr;
25
26use super::Venue;
27
28/// Represents a valid account ID.
29#[repr(C)]
30#[derive(Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
31#[cfg_attr(
32 feature = "python",
33 pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.model")
34)]
35pub struct AccountId(Ustr);
36
37impl AccountId {
38 /// Creates a new [`AccountId`] instance with correctness checking.
39 ///
40 /// Must be correctly formatted with two valid strings either side of a hyphen '-'.
41 ///
42 /// It is expected an account ID is the name of the issuer with an account number
43 /// separated by a hyphen.
44 ///
45 /// # Errors
46 ///
47 /// This function returns an error:
48 /// - If `value` is not a valid string.
49 /// - If `value` length is greater than 36.
50 ///
51 /// # Notes
52 ///
53 /// PyO3 requires a `Result` type for proper error handling and stacktrace printing in Python.
54 pub fn new_checked<T: AsRef<str>>(value: T) -> anyhow::Result<Self> {
55 let value = value.as_ref();
56 check_valid_string(value, stringify!(value))?;
57 check_string_contains(value, "-", stringify!(value))?;
58 Ok(Self(Ustr::from(value)))
59 }
60
61 /// Creates a new [`AccountId`] instance.
62 ///
63 /// # Panics
64 ///
65 /// This function panics:
66 /// - If `value` is not a valid string, or value length is greater than 36.
67 pub fn new<T: AsRef<str>>(value: T) -> Self {
68 Self::new_checked(value).expect(FAILED)
69 }
70
71 /// Sets the inner identifier value.
72 pub(crate) fn set_inner(&mut self, value: &str) {
73 self.0 = Ustr::from(value);
74 }
75
76 /// Returns the inner identifier value.
77 #[must_use]
78 pub fn inner(&self) -> Ustr {
79 self.0
80 }
81
82 /// Returns the inner identifier value as a string slice.
83 #[must_use]
84 pub fn as_str(&self) -> &str {
85 self.0.as_str()
86 }
87
88 /// Returns the account issuer for this identifier.
89 #[must_use]
90 pub fn get_issuer(&self) -> Venue {
91 // SAFETY: Account ID is guaranteed to have chars either side of a hyphen
92 Venue::from_str_unchecked(self.0.split('-').collect::<Vec<&str>>().first().unwrap())
93 }
94
95 /// Returns the account ID assigned by the issuer.
96 #[must_use]
97 pub fn get_issuers_id(&self) -> &str {
98 // SAFETY: Account ID is guaranteed to have chars either side of a hyphen
99 self.0.split('-').collect::<Vec<&str>>().last().unwrap()
100 }
101}
102
103impl Debug for AccountId {
104 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
105 write!(f, "{:?}", self.0)
106 }
107}
108
109impl Display for AccountId {
110 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
111 write!(f, "{}", self.0)
112 }
113}
114
115////////////////////////////////////////////////////////////////////////////////
116// Tests
117////////////////////////////////////////////////////////////////////////////////
118#[cfg(test)]
119mod tests {
120 use rstest::rstest;
121
122 use super::*;
123 use crate::identifiers::stubs::*;
124
125 #[rstest]
126 #[should_panic]
127 fn test_account_id_new_invalid_string() {
128 AccountId::new("");
129 }
130
131 #[rstest]
132 #[should_panic]
133 fn test_account_id_new_missing_hyphen() {
134 AccountId::new("123456789");
135 }
136
137 #[rstest]
138 fn test_account_id_fmt() {
139 let s = "IB-U123456789";
140 let account_id = AccountId::new(s);
141 let formatted = format!("{account_id}");
142 assert_eq!(formatted, s);
143 }
144
145 #[rstest]
146 fn test_string_reprs(account_ib: AccountId) {
147 assert_eq!(account_ib.as_str(), "IB-1234567890");
148 }
149
150 #[rstest]
151 fn test_get_issuer(account_ib: AccountId) {
152 assert_eq!(account_ib.get_issuer(), Venue::new("IB"));
153 }
154
155 #[rstest]
156 fn test_get_issuers_id(account_ib: AccountId) {
157 assert_eq!(account_ib.get_issuers_id(), "1234567890");
158 }
159}