Skip to main content

aimdb_core/
inbound_key.rs

1//! Keys: small integers standing for the values of one capture, one table per
2//! record.
3
4use alloc::{sync::Arc, vec::Vec};
5use core::num::NonZeroU16;
6use core::sync::atomic::{AtomicU32, Ordering};
7
8use hashbrown::HashMap;
9
10#[cfg(feature = "std")]
11type Mutex<T> = std::sync::Mutex<T>;
12#[cfg(not(feature = "std"))]
13type Mutex<T> = spin::Mutex<T>;
14
15#[cfg(feature = "std")]
16fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
17    m.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
18}
19#[cfg(not(feature = "std"))]
20fn lock<T>(m: &Mutex<T>) -> spin::MutexGuard<'_, T> {
21    m.lock()
22}
23
24/// A capture value's key, assigned the first time the value is seen. Only
25/// meaningful for the record whose link produced it.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
27pub struct KeyId(NonZeroU16);
28
29impl KeyId {
30    /// 0-based, for indexing per-key state.
31    pub fn index(self) -> usize {
32        usize::from(self.0.get()) - 1
33    }
34}
35
36/// A record's key table. Grows as values arrive, up to `capacity`.
37pub(crate) struct KeyTable {
38    capacity: NonZeroU16,
39    keys: Mutex<Keys>,
40    dropped: AtomicU32,
41}
42
43#[derive(Default)]
44struct Keys {
45    by_name: HashMap<Arc<str>, KeyId>,
46    names: Vec<Arc<str>>,
47}
48
49impl KeyTable {
50    pub(crate) fn new(capacity: NonZeroU16) -> Self {
51        Self {
52            capacity,
53            keys: Mutex::new(Keys::default()),
54            dropped: AtomicU32::new(0),
55        }
56    }
57
58    /// The key for `name`, assigned if new. `None` when the table is full;
59    /// the caller drops the message and it is counted.
60    pub(crate) fn key(&self, name: &str) -> Option<KeyId> {
61        let mut keys = lock(&self.keys);
62        if let Some(&id) = keys.by_name.get(name) {
63            return Some(id);
64        }
65        let Some(id) = u16::try_from(keys.names.len() + 1)
66            .ok()
67            .filter(|&n| n <= self.capacity.get())
68            .and_then(NonZeroU16::new)
69            .map(KeyId)
70        else {
71            let _ = self
72                .dropped
73                .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_add(1));
74            return None;
75        };
76        let name: Arc<str> = name.into();
77        keys.names.push(name.clone());
78        keys.by_name.insert(name, id);
79        Some(id)
80    }
81
82    /// The value `key` stands for.
83    pub(crate) fn name(&self, key: KeyId) -> Option<Arc<str>> {
84        lock(&self.keys).names.get(key.index()).cloned()
85    }
86
87    #[cfg(any(test, feature = "remote"))]
88    pub(crate) fn capacity(&self) -> u16 {
89        self.capacity.get()
90    }
91
92    #[cfg(any(test, feature = "remote"))]
93    pub(crate) fn assigned(&self) -> usize {
94        lock(&self.keys).names.len()
95    }
96
97    /// Messages turned away because the table was full, once per matching
98    /// keyed link.
99    #[cfg(any(test, feature = "remote"))]
100    pub(crate) fn dropped(&self) -> u32 {
101        self.dropped.load(Ordering::Relaxed)
102    }
103}
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108
109    fn table(capacity: u16) -> KeyTable {
110        KeyTable::new(NonZeroU16::new(capacity).unwrap())
111    }
112
113    #[test]
114    fn keys_are_assigned_in_order_and_stable() {
115        let t = table(4);
116        let a = t.key("kitchen").unwrap();
117        let b = t.key("hall").unwrap();
118        assert_eq!((a.index(), b.index()), (0, 1));
119        assert_eq!(t.key("kitchen"), Some(a));
120        assert_eq!(t.assigned(), 2);
121        assert_eq!(t.name(a).as_deref(), Some("kitchen"));
122        assert_eq!(t.name(b).as_deref(), Some("hall"));
123    }
124
125    #[test]
126    fn full_table_drops_new_values_and_keeps_known_ones() {
127        let t = table(2);
128        let a = t.key("a").unwrap();
129        t.key("b").unwrap();
130        assert_eq!(t.key("c"), None);
131        assert_eq!(t.key("d"), None);
132        assert_eq!(t.key("a"), Some(a));
133        assert_eq!((t.capacity(), t.assigned(), t.dropped()), (2, 2, 2));
134    }
135
136    #[test]
137    fn unknown_key_has_no_name() {
138        let big = table(8);
139        let foreign = big.key("x").and(big.key("y")).unwrap();
140        assert_eq!(table(8).name(foreign), None);
141    }
142
143    #[test]
144    fn full_u16_capacity_does_not_overflow() {
145        let t = table(u16::MAX);
146        for i in 0..u16::MAX {
147            assert_eq!(
148                t.key(&alloc::format!("{i}")).map(KeyId::index),
149                Some(usize::from(i))
150            );
151        }
152        assert_eq!(t.key("one more"), None);
153        assert_eq!(t.dropped(), 1);
154    }
155}