Skip to main content

af_price_updates/
pyth_id_set.rs

1use crate::{pyth::PriceFeedId, slice_interner::SliceInterner, sorted_set::SortedSetSlice};
2use std::ops::Deref;
3
4static PRICE_FEED_ID_SET_INTERNER: SliceInterner<PriceFeedId> = SliceInterner::new(1024, 2 * 1024);
5
6/// A compact, copyable set of Pyth price feed IDs.
7///
8/// [`Self::intern`] stores an already sorted and deduplicated set in process-global storage.
9/// Equal sets share one canonical slice for the lifetime of the process. Consequently, cloning
10/// this type only copies a slice reference, while equality and hashing compare the canonical
11/// address in constant time.
12///
13/// It dereferences to [`SortedSetSlice`], so set queries such as [`SortedSetSlice::is_superset`]
14/// work alike on interned, owned and borrowed sets.
15///
16/// Ordering remains lexicographic by feed ID, and serialization emits the slice contents rather
17/// than its process-local identity. Parse or deserialize dynamic input into a
18/// [`SortedSet`](crate::sorted_set::SortedSet), then explicitly intern it if the values are trusted
19/// and bounded.
20///
21/// Every distinct set is kept until the process exits, so do not build sets from untrusted input;
22/// use [`SortedSet`](crate::sorted_set::SortedSet) for that instead, and [`Self::find`] to look up
23/// a set without interning it.
24#[derive(Clone, Copy, Debug, Eq, Ord, PartialOrd, serde::Serialize)]
25#[serde(transparent)]
26pub struct PriceFeedIdSet(&'static [PriceFeedId]);
27
28impl PriceFeedIdSet {
29    /// Interns a sorted, deduplicated set of trusted feed IDs.
30    ///
31    /// Every distinct set remains allocated until the process exits. Keep untrusted or unbounded
32    /// input in an owned [`SortedSet`](crate::sorted_set::SortedSet) instead.
33    pub fn intern(ids: &SortedSetSlice<PriceFeedId>) -> Self {
34        Self(PRICE_FEED_ID_SET_INTERNER.get(ids))
35    }
36    /// Returns the set of `ids` if an equal set was created before.
37    ///
38    /// Unlike [`Self::intern`], this never interns `ids`, so it suits untrusted input such as feed
39    /// ID sets requested by clients.
40    pub fn find(ids: &SortedSetSlice<PriceFeedId>) -> Option<Self> {
41        PRICE_FEED_ID_SET_INTERNER.find(ids).map(Self)
42    }
43}
44
45impl Default for PriceFeedIdSet {
46    fn default() -> Self {
47        Self(PRICE_FEED_ID_SET_INTERNER.get(&[]))
48    }
49}
50
51impl Deref for PriceFeedIdSet {
52    type Target = SortedSetSlice<PriceFeedId>;
53    fn deref(&self) -> &Self::Target {
54        SortedSetSlice::from_sorted_slice(self.0)
55    }
56}
57
58impl AsRef<[PriceFeedId]> for PriceFeedIdSet {
59    fn as_ref(&self) -> &[PriceFeedId] {
60        self.0
61    }
62}
63
64impl AsRef<SortedSetSlice<PriceFeedId>> for PriceFeedIdSet {
65    fn as_ref(&self) -> &SortedSetSlice<PriceFeedId> {
66        self
67    }
68}
69
70impl<const N: usize> From<[PriceFeedId; N]> for PriceFeedIdSet {
71    /// Sorts, deduplicates, and interns a fixed-size array.
72    ///
73    /// This conversion is intended for bounded, program-controlled values such as array literals.
74    /// Use [`Self::intern`] to make interning explicit for dynamically sourced input.
75    fn from(mut ids: [PriceFeedId; N]) -> Self {
76        Self::intern(SortedSetSlice::sort_dedup(&mut ids))
77    }
78}
79
80impl IntoIterator for PriceFeedIdSet {
81    type Item = PriceFeedId;
82    type IntoIter = std::iter::Copied<std::slice::Iter<'static, PriceFeedId>>;
83    fn into_iter(self) -> Self::IntoIter {
84        self.0.iter().copied()
85    }
86}
87
88impl PartialEq for PriceFeedIdSet {
89    fn eq(&self, other: &Self) -> bool {
90        std::ptr::addr_eq(self.0, other.0)
91    }
92}
93
94impl std::hash::Hash for PriceFeedIdSet {
95    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
96        self.0.as_ptr().hash(state);
97    }
98}
99
100impl std::fmt::Display for PriceFeedIdSet {
101    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102        <SortedSetSlice<PriceFeedId> as std::fmt::Display>::fmt(&**self, f)
103    }
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109    use crate::{U256, sorted_set::SortedSet};
110
111    fn id(value: u8) -> PriceFeedId {
112        PriceFeedId(U256::from(u64::from(value)))
113    }
114
115    fn intern(ids: impl IntoIterator<Item = PriceFeedId>) -> PriceFeedIdSet {
116        let ids = ids.into_iter().collect::<SortedSet<_>>();
117        PriceFeedIdSet::intern(&ids)
118    }
119
120    #[test]
121    fn canonicalizes_dynamic_sets_before_interning() {
122        let first = intern([id(1), id(3), id(1), id(2)]);
123        let same = intern([id(2), id(1), id(3)]);
124
125        assert_eq!(first.as_slice(), &[id(1), id(2), id(3)]);
126        assert_eq!(first, same);
127        assert!(std::ptr::addr_eq(first.0, same.0));
128    }
129
130    #[test]
131    fn interns_sorted_set() {
132        let ids = SortedSet::from([id(3), id(1), id(3)]);
133
134        assert_eq!(
135            PriceFeedIdSet::intern(&ids),
136            PriceFeedIdSet::from([id(3), id(1), id(3)])
137        );
138    }
139
140    #[test]
141    fn find_does_not_intern() {
142        // Not used by other tests, which share the interner.
143        let ids = SortedSet::from([
144            PriceFeedId(U256::from(u64::MAX)),
145            PriceFeedId(U256::from(u64::MAX - 1)),
146        ]);
147
148        assert_eq!(PriceFeedIdSet::find(&ids), None);
149        assert_eq!(PriceFeedIdSet::find(&ids), None);
150        let interned = PriceFeedIdSet::intern(&ids);
151        assert_eq!(PriceFeedIdSet::find(&ids), Some(interned));
152        assert_eq!(
153            PriceFeedIdSet::find(&SortedSet::default()),
154            Some(PriceFeedIdSet::default())
155        );
156    }
157
158    #[test]
159    fn empty_set_is_canonical() {
160        let default = PriceFeedIdSet::default();
161        let from_iter = intern([]);
162        let from_array = PriceFeedIdSet::from([]);
163        let parsed = "[]".parse::<SortedSet<PriceFeedId>>().unwrap();
164        let parsed = PriceFeedIdSet::intern(&parsed);
165
166        assert!(std::ptr::addr_eq(default.0, from_iter.0));
167        assert!(std::ptr::addr_eq(default.0, from_array.0));
168        assert!(std::ptr::addr_eq(default.0, parsed.0));
169    }
170
171    #[test]
172    fn hashes_by_canonical_address() {
173        let first = intern([id(1), id(2)]);
174        let same = intern([id(2), id(1)]);
175        let different = intern([id(1)]);
176        let set = std::collections::HashSet::from([first, same, different]);
177
178        assert_eq!(set.len(), 2);
179    }
180
181    #[test]
182    fn display_and_parse_round_trip() {
183        let set = intern([id(1), id(2)]);
184        let serialized = set.to_string();
185        let parsed = serialized.parse::<SortedSet<PriceFeedId>>().unwrap();
186
187        assert_eq!(PriceFeedIdSet::intern(&parsed), set);
188        assert!("1,2".parse::<SortedSet<PriceFeedId>>().is_err());
189        assert!("[1,nope]".parse::<SortedSet<PriceFeedId>>().is_err());
190    }
191
192    #[test]
193    fn serde_uses_owned_set_before_explicit_interning() {
194        let set = PriceFeedIdSet::from([id(1), id(3)]);
195        let unsorted = serde_json::to_string(&[id(3), id(1), id(3)]).unwrap();
196        let owned = serde_json::from_str::<SortedSet<PriceFeedId>>(&unsorted).unwrap();
197
198        assert_eq!(PriceFeedIdSet::intern(&owned), set);
199        assert_eq!(
200            serde_json::to_string(&set).unwrap(),
201            serde_json::to_string(&owned).unwrap()
202        );
203    }
204
205    #[test]
206    fn checks_supersets_through_sorted_set_slice() {
207        let superset = intern([id(1), id(2), id(3)]);
208        let subset = intern([id(3), id(1)]);
209
210        assert!(superset.is_superset(&subset));
211        assert!(superset.is_superset(&SortedSet::from([id(2)])));
212        assert!(!subset.is_superset(&superset));
213    }
214}