nautilus_model/identifiers/
venue.rs
1use std::{
19 fmt::{Debug, Display, Formatter},
20 hash::Hash,
21};
22
23use nautilus_core::correctness::{FAILED, check_valid_string};
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 #[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]
85 pub fn from_str_unchecked<T: AsRef<str>>(s: T) -> Self {
86 Self(Ustr::from(s.as_ref()))
87 }
88
89 #[must_use]
90 pub const fn from_ustr_unchecked(s: Ustr) -> Self {
91 Self(s)
92 }
93
94 pub fn from_code(code: &str) -> anyhow::Result<Self> {
95 let map_guard = VENUE_MAP
96 .lock()
97 .map_err(|e| anyhow::anyhow!("Error acquiring lock on `VENUE_MAP`: {e}"))?;
98 map_guard
99 .get(code)
100 .copied()
101 .ok_or_else(|| anyhow::anyhow!("Unknown venue code: {code}"))
102 }
103
104 #[must_use]
105 pub fn synthetic() -> Self {
106 Self::new(SYNTHETIC_VENUE)
108 }
109
110 #[must_use]
111 pub fn is_synthetic(&self) -> bool {
112 self.0.as_str() == SYNTHETIC_VENUE
113 }
114}
115
116impl Debug for Venue {
117 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
118 write!(f, "{:?}", self.0)
119 }
120}
121
122impl Display for Venue {
123 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
124 write!(f, "{}", self.0)
125 }
126}
127
128#[cfg(test)]
132mod tests {
133 use rstest::rstest;
134
135 use crate::identifiers::{Venue, stubs::*};
136
137 #[rstest]
138 fn test_string_reprs(venue_binance: Venue) {
139 assert_eq!(venue_binance.as_str(), "BINANCE");
140 assert_eq!(format!("{venue_binance}"), "BINANCE");
141 }
142}