nautilus_model/identifiers/
position_id.rs1use std::{
19 fmt::{Debug, Display},
20 hash::Hash,
21};
22
23use nautilus_core::correctness::{
24 CorrectnessResult, CorrectnessResultExt, FAILED, check_valid_string_utf8,
25};
26use ustr::Ustr;
27
28#[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", from_py_object)
34)]
35#[cfg_attr(
36 feature = "python",
37 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
38)]
39pub struct PositionId(Ustr);
40
41impl PositionId {
42 pub fn new_checked<T: AsRef<str>>(value: T) -> CorrectnessResult<Self> {
52 let value = value.as_ref();
53 check_valid_string_utf8(value, stringify!(value))?;
54 Ok(Self(Ustr::from(value)))
55 }
56
57 pub fn new<T: AsRef<str>>(value: T) -> Self {
63 Self::new_checked(value).expect_display(FAILED)
64 }
65
66 #[cfg_attr(not(feature = "python"), allow(dead_code))]
68 pub(crate) fn set_inner(&mut self, value: &str) {
69 self.0 = Ustr::from(value);
70 }
71
72 #[must_use]
74 pub fn inner(&self) -> Ustr {
75 self.0
76 }
77
78 #[must_use]
80 pub fn as_str(&self) -> &str {
81 self.0.as_str()
82 }
83
84 #[must_use]
88 pub fn is_virtual(&self) -> bool {
89 self.0.starts_with("P-")
90 }
91}
92
93impl Debug for PositionId {
94 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95 write!(f, "\"{}\"", self.0)
96 }
97}
98impl Display for PositionId {
99 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100 write!(f, "{}", self.0)
101 }
102}
103
104#[cfg(test)]
105mod tests {
106 use rstest::rstest;
107
108 use super::PositionId;
109 use crate::identifiers::stubs::*;
110
111 #[rstest]
112 fn test_string_reprs(position_id_test: PositionId) {
113 assert_eq!(position_id_test.as_str(), "P-123456789");
114 assert_eq!(format!("{position_id_test}"), "P-123456789");
115 }
116
117 #[rstest]
118 #[should_panic(expected = "Condition failed: invalid string for 'value', was empty")]
119 fn test_new_with_empty_string_panics_with_display_format() {
120 let _ = PositionId::new("");
121 }
122
123 #[rstest]
124 fn test_deserialize_json_with_unicode_escapes() {
125 let id: PositionId = serde_json::from_str(r#""P-\u9f99\u867e-1""#).unwrap();
126 assert_eq!(id.as_str(), "P-\u{9f99}\u{867e}-1");
127 }
128
129 #[rstest]
130 fn test_serialization_roundtrip_non_ascii() {
131 let id = PositionId::new("P-\u{9f99}\u{867e}-1");
132 let json = serde_json::to_string(&id).unwrap();
133 assert_eq!(json, "\"P-\u{9f99}\u{867e}-1\"");
134
135 let deserialized: PositionId = serde_json::from_str(&json).unwrap();
136 assert_eq!(deserialized, id);
137 }
138
139 #[rstest]
140 fn test_deserialize_rejects_empty_string() {
141 let result: Result<PositionId, _> = serde_json::from_str(r#""""#);
142 assert!(result.is_err());
143 }
144}