Skip to main content

nsdq_util/types/
string.rs

1
2/// Define a fixed-length string type.
3/// ```
4/// use nsdq_util::define_str;
5///
6/// define_str!(MyStr [4usize] "String with a fixed length of 4 characters.");
7///
8/// let bytes = b"XXXX";
9/// let (_, mystr) = MyStr::parse(bytes).unwrap();
10///
11/// assert_eq!(mystr.encode(), *bytes);
12/// assert_eq!(mystr.to_str(), "XXXX");
13///
14/// assert_eq!(format!("{}", mystr), String::from("XXXX"));
15/// ```
16/// NOTE: `new` or `from_str` functions are not included in this macro,
17/// in case there are special constraints on the character types.
18#[macro_export] macro_rules! define_str {
19    ($name:ident [$len:expr] $doc:expr) => {
20
21        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
22        #[doc = $doc]
23        pub struct $name([u8; $len]);
24
25        impl $name {
26
27            // NOTE: `new` or `from_str` function not included in case 
28            // there are special constraints on the character types.
29
30            /// NOTE: Assumes NASDAQ only sends valid characters,
31            /// and therefore does not check for compliance.
32            pub fn parse(input: &[u8]) -> nom::IResult<&[u8], Self> {
33
34                use nom::bytes::complete::take;
35
36                let (input, bytes) = take($len)(input)?;
37                let chars = bytes.into_iter()
38                    .map(|b| *b)
39                    .collect::<Vec<u8>>()
40                    .try_into()
41                    .expect(&format!("Take {} bytes", $len));
42
43                Ok((input, Self(chars)))
44            }
45
46            /// Extract the data for inclusion in a message.
47            pub fn encode(&self) -> [u8; $len] { self.0 }
48
49            /// Character compliance should be checked when created.
50            ///
51            /// # Panics
52            /// Will panic if the string contains invalid UTF8.
53            pub fn to_str(&self) -> &str {
54                std::str::from_utf8(&self.0)
55                    .expect("Character compliance should be checked by type")
56                    .trim_end()
57            }
58        }
59
60        impl std::fmt::Display for $name {
61            fn fmt(
62                &self, 
63                f: &mut std::fmt::Formatter<'_>
64            ) -> std::fmt::Result {
65                self.to_str().fmt(f)
66            }
67        }
68
69    }
70}
71
72
73define_str!{ FixStr4 [4usize] "Wrappable string type with fixed length 4." }
74define_str!{ FixStr8 [8usize] "Wrappable string type with fixed length 8." }
75define_str!{ FixStr14 [14usize] "Wrappable string type with fixed length 14." }
76
77
78use crate::error::TypeError;
79
80define_str!{ 
81    Mpid [4usize] 
82        "Market Participant Identifier (MPID). \
83        Used for identifying firms registered with FINRA." 
84}
85
86impl Default for Mpid {
87    fn default() -> Self { Mpid(*b"    ") }
88}
89
90impl Mpid {
91
92    /// Generate a new FirmId from a protocol-compliant string.
93    /// Must be four uppercase ASCII characters.
94    /// ```
95    /// use nsdq_util::Mpid;
96    ///
97    /// assert!(Mpid::from("FIRM").is_ok());
98    /// assert!(Mpid::from("Firm").is_err());
99    /// assert!(Mpid::from("F1RM").is_err());
100    /// ```
101    pub fn from(s: impl AsRef<str>) -> Result<Self, TypeError> {
102
103        let s = s.as_ref();
104        if helper::is_uppercase(s) {
105            let fs = helper::fixed_str::<4>(s);
106            Ok(Mpid(fs))
107        } else {
108            Err(TypeError::InvalidString(
109                String::from("MPID"),
110                s.to_string()
111            ))
112        }
113    }
114}
115
116
117
118define_str!{ 
119    StockSymbol [8usize] 
120        "Strong type for stock symbols that ensures protocol compliance. \
121        Nasdaq currently restricts its symbol length to a maximum of 8 chars. \
122        For common stock issuances, NASDAQ, PSX and BX will only assign root \
123        symbols of 1 to 4 characters in length with possible fifth and or \
124        sixth character denoting a suffix. \n \
125        In certain instances, a dot “.” delimiter may be applied to symbols 
126        after the root and between the suffix e.g., XXXX.A. \n \
127        For subordinate securities, Nasdaq and BX will assign a 5 character \
128        symbol for which the last character relays information about the issue \
129        class or issue type. \n \
130        For the current list of fifth and or six character symbol suffixes, \
131        please refer to Ticker Symbol Convention page on the NasdaqTrader \
132        website. \n \
133        For NYSE-, NYSE American- and NYSE Arca-listed securities with \
134        subordinate issue types, please refer to Ticker Symbol Convention page \
135        on the Nasdaq Trader website."
136}
137
138impl Default for StockSymbol {
139    fn default() -> Self { StockSymbol(*b"        ") }
140}
141
142impl StockSymbol {
143
144    /// Generate a new StockSymbol from a protocol-compliant string.
145    /// Must be up to eight alphabetic ASCII characters.
146    /// ```
147    /// use nsdq_util::StockSymbol;
148    ///
149    /// assert!(StockSymbol::from("STOCKSYM").is_ok());
150    /// assert!(StockSymbol::from("Stonks").is_ok());
151    /// assert!(StockSymbol::from("Stock.XX").is_ok());
152    /// assert!(StockSymbol::from("Stonks  ").is_err());
153    /// assert!(StockSymbol::from("St0nks").is_err());
154    /// ```
155    pub fn from(s: impl AsRef<str>) -> Result<Self, TypeError> {
156
157        let s = s.as_ref();
158        if helper::is_alpha_with_suffix(s) {
159            let fs = helper::fixed_str::<8>(s);
160            Ok(StockSymbol(fs))
161        } else {
162            Err(TypeError::InvalidString(
163                String::from("StockSymbol"),
164                s.to_string()
165            ))
166        }
167    }
168}
169
170
171pub mod helper {
172
173    /// Creates a fixed-length string, padding up to length `N` with spaces.
174    pub fn fixed_str<const N: usize>(s: &str) -> [u8; N] {
175        let mut buf = [b' '; N];
176        let chars = s.as_bytes();
177        let copy_len = usize::min(N, chars.len());
178        buf[..copy_len].copy_from_slice(&chars[..copy_len]);
179        buf
180    }
181
182    /// Checks if all characters are uppercase alpha. (e.g. for Mpid)
183    pub fn is_uppercase(s: &str) -> bool {
184        s.chars().all(|c| c.is_ascii_uppercase())
185    }
186
187    /// Checks if all characters are alphabetic.
188    pub fn is_alpha(s: &str) -> bool {
189        s.chars().all(|c| c.is_ascii_alphabetic())
190    }
191
192    /// Checks if all characters are alphabetic or period.
193    /// (e.g. for StockSymbol)
194    pub fn is_alpha_with_suffix(s: &str) -> bool {
195        s.chars().all(|c| c.is_ascii_alphabetic() || c == '.')
196    }
197
198    /// Checks if all characters are alphanumeric or spaces.
199    /// (e.g. for CIOrdId)
200    /// ```
201    /// use nsdq_util::types::string::helper::is_alphanumeric;
202    ///
203    /// assert!(is_alphanumeric("Xy 1"));
204    /// assert!(is_alphanumeric(""));
205    /// assert!(!is_alphanumeric("Xy 1!"));
206    /// ```
207    pub fn is_alphanumeric(s: &str) -> bool {
208        s.chars().all(|c| c.is_ascii_alphanumeric() || c == ' ')
209    }
210}
211