nautilus_model/identifiers/
venue.rs1use std::{
19 fmt::{Debug, Display, Formatter},
20 hash::Hash,
21};
22
23use nautilus_core::correctness::{check_valid_string, FAILED};
24use ustr::Ustr;
25
26use crate::venues::VENUE_MAP;
27
28pub const SYNTHETIC_VENUE: &str = "SYNTH";
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.core.nautilus_pyo3.model")
36)]
37pub struct Venue(Ustr);
38
39impl Venue {
40 pub fn new_checked<T: AsRef<str>>(value: T) -> anyhow::Result<Self> {
51 let value = value.as_ref();
52 check_valid_string(value, stringify!(value))?;
53 Ok(Self(Ustr::from(value)))
54 }
55
56 pub fn new<T: AsRef<str>>(value: T) -> Self {
63 Self::new_checked(value).expect(FAILED)
64 }
65
66 pub(crate) fn set_inner(&mut self, value: &str) {
68 self.0 = Ustr::from(value);
69 }
70
71 #[must_use]
73 pub fn inner(&self) -> Ustr {
74 self.0
75 }
76
77 #[must_use]
79 pub fn as_str(&self) -> &str {
80 self.0.as_str()
81 }
82
83 #[must_use]
84 pub fn from_str_unchecked<T: AsRef<str>>(s: T) -> Self {
85 Self(Ustr::from(s.as_ref()))
86 }
87
88 #[must_use]
89 pub const fn from_ustr_unchecked(s: Ustr) -> Self {
90 Self(s)
91 }
92
93 pub fn from_code(code: &str) -> anyhow::Result<Self> {
94 let map_guard = VENUE_MAP
95 .lock()
96 .map_err(|e| anyhow::anyhow!("Error acquiring lock on `VENUE_MAP`: {e}"))?;
97 map_guard
98 .get(code)
99 .copied()
100 .ok_or_else(|| anyhow::anyhow!("Unknown venue code: {code}"))
101 }
102
103 #[must_use]
104 pub fn synthetic() -> Self {
105 Self::new(SYNTHETIC_VENUE)
107 }
108
109 #[must_use]
110 pub fn is_synthetic(&self) -> bool {
111 self.0.as_str() == SYNTHETIC_VENUE
112 }
113}
114
115impl Debug for Venue {
116 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
117 write!(f, "{:?}", self.0)
118 }
119}
120
121impl Display for Venue {
122 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
123 write!(f, "{}", self.0)
124 }
125}
126
127#[cfg(test)]
131mod tests {
132 use rstest::rstest;
133
134 use crate::identifiers::{stubs::*, Venue};
135
136 #[rstest]
137 fn test_string_reprs(venue_binance: Venue) {
138 assert_eq!(venue_binance.as_str(), "BINANCE");
139 assert_eq!(format!("{venue_binance}"), "BINANCE");
140 }
141}