Skip to main content

af_price_updates/
stork_small_id.rs

1use crate::str_interner::StrInterner;
2use serde::{Deserialize, Serialize};
3
4static ASSET_ID_INTERNER: StrInterner = StrInterner::new(1024, 2 * 1024);
5
6/// Copyable and smaller version of Stork asset id.
7///
8/// Equal asset ids share one interned string, so equality and hashing compare addresses in constant
9/// time. Every distinct asset id is kept until the process exits, so do not create them from
10/// untrusted input.
11///
12/// Deserialization never interns: it accepts only the empty ID and non-empty IDs previously
13/// introduced through [`Self::intern`]. Use [`Self::find`] for the same lookup without serde.
14#[derive(Clone, Copy, Debug, Eq, Ord, PartialOrd, Serialize)]
15pub struct SmallAssetId(&'static str);
16
17impl SmallAssetId {
18    /// Interns a trusted, bounded asset ID for the lifetime of the process.
19    ///
20    /// Every distinct string remains allocated until the process exits. Use [`Self::find`] or an
21    /// owned string for untrusted or unbounded input.
22    pub fn intern(s: &str) -> Self {
23        Self(ASSET_ID_INTERNER.get(s))
24    }
25    /// Returns the asset id `s` if it was created before.
26    ///
27    /// Unlike [`Self::intern`], this never interns `s`, so it suits untrusted input such as asset
28    /// IDs requested by clients.
29    pub fn find(s: &str) -> Option<Self> {
30        ASSET_ID_INTERNER.find(s).map(Self)
31    }
32}
33
34impl Default for SmallAssetId {
35    fn default() -> Self {
36        Self(ASSET_ID_INTERNER.get(""))
37    }
38}
39
40impl AsRef<str> for SmallAssetId {
41    fn as_ref(&self) -> &str {
42        self.0
43    }
44}
45
46impl std::ops::Deref for SmallAssetId {
47    type Target = str;
48    fn deref(&self) -> &Self::Target {
49        self.0
50    }
51}
52
53impl<'de> Deserialize<'de> for SmallAssetId {
54    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
55    where
56        D: serde::Deserializer<'de>,
57    {
58        struct AssetIdVisitor;
59
60        impl serde::de::Visitor<'_> for AssetIdVisitor {
61            type Value = SmallAssetId;
62
63            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64                f.write_str("a previously interned Stork asset ID")
65            }
66
67            fn visit_str<E: serde::de::Error>(self, s: &str) -> Result<Self::Value, E> {
68                SmallAssetId::find(s)
69                    .ok_or_else(|| E::custom(format_args!("unknown Stork asset ID: {s}")))
70            }
71        }
72
73        deserializer.deserialize_str(AssetIdVisitor)
74    }
75}
76
77impl std::fmt::Display for SmallAssetId {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        self.0.fmt(f)
80    }
81}
82
83impl PartialEq for SmallAssetId {
84    fn eq(&self, other: &Self) -> bool {
85        std::ptr::addr_eq(self.0, other.0)
86    }
87}
88
89impl std::hash::Hash for SmallAssetId {
90    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
91        self.0.as_ptr().hash(state);
92    }
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    #[test]
100    fn copyable_asset_id() {
101        let a1 = SmallAssetId::intern("BTCUSD");
102        let a2 = SmallAssetId::intern("BTCUSD");
103        assert_eq!(a1, a2);
104        assert_eq!(a1.0.as_ptr(), a2.0.as_ptr());
105        let a3 = SmallAssetId::intern("ETCUSD");
106        assert_ne!(a1, a3);
107    }
108    #[test]
109    fn find_does_not_intern() {
110        // Not used by other tests, which share the interner.
111        const ASSET_ID: &str = "FINDTESTUSD";
112
113        assert_eq!(SmallAssetId::find(ASSET_ID), None);
114        assert_eq!(SmallAssetId::find(ASSET_ID), None);
115        let interned = SmallAssetId::intern(ASSET_ID);
116        assert_eq!(SmallAssetId::find(ASSET_ID), Some(interned));
117        assert_eq!(SmallAssetId::find(""), Some(SmallAssetId::default()));
118    }
119    #[test]
120    fn deserialization_rejects_unknown_id_without_interning_it() {
121        // Not used by other tests, which share the interner.
122        const ASSET_ID: &str = "UNKNOWNDESERIALIZATIONTESTUSD";
123
124        assert_eq!(SmallAssetId::find(ASSET_ID), None);
125        assert!(serde_json::from_str::<SmallAssetId>(&format!(r#""{ASSET_ID}""#)).is_err());
126        assert_eq!(SmallAssetId::find(ASSET_ID), None);
127    }
128    #[test]
129    fn small_asset_id_hashes_by_canonical_address() {
130        let first = SmallAssetId::intern("BTCUSD");
131        let same = SmallAssetId::intern(&String::from("BTCUSD"));
132        let different = SmallAssetId::intern("ETHUSD");
133        let set = std::collections::HashSet::from([first, same, different]);
134
135        assert_eq!(set.len(), 2);
136    }
137    #[test]
138    fn empty_asset_id_is_canonical() {
139        let default = SmallAssetId::default();
140        let from_str = SmallAssetId::intern("");
141        let deserialized = serde_json::from_str::<SmallAssetId>(r#""""#).unwrap();
142
143        assert!(std::ptr::addr_eq(default.0, from_str.0));
144        assert!(std::ptr::addr_eq(default.0, deserialized.0));
145
146        let set = std::collections::HashSet::from([default, from_str, deserialized]);
147        assert_eq!(set.len(), 1);
148    }
149    #[test]
150    fn copyable_asset_id_serde() {
151        #[derive(Debug, Deserialize, Eq, PartialEq, Serialize)]
152        struct Data {
153            assets: Vec<SmallAssetId>,
154        }
155        let data = Data {
156            assets: vec![
157                SmallAssetId::intern("BTCUSD"),
158                SmallAssetId::intern("ETHUSD"),
159            ],
160        };
161        const EXPECTED: &str = r#"{"assets":["BTCUSD","ETHUSD"]}"#;
162        let s = serde_json::to_string(&data).unwrap();
163        assert_eq!(s, EXPECTED);
164        let data2: Data = serde_json::from_str(EXPECTED).unwrap();
165        assert_eq!(data, data2);
166    }
167    #[test]
168    fn deserializes_transient_and_owned_strings() {
169        // None of these lend a `&str` borrowed from the input.
170        let expected = SmallAssetId::intern("BTCUSD");
171
172        assert_eq!(
173            serde_json::from_str::<SmallAssetId>(r#""BTC\u0055SD""#).unwrap(),
174            expected
175        );
176        assert_eq!(
177            serde_json::from_reader::<_, SmallAssetId>(&br#""BTCUSD""#[..]).unwrap(),
178            expected
179        );
180        assert_eq!(
181            serde_json::from_value::<SmallAssetId>(serde_json::Value::String("BTCUSD".into()))
182                .unwrap(),
183            expected
184        );
185    }
186}