commonware_utils/
priority_set.rs

1use std::{
2    cmp::Ordering,
3    collections::{BTreeSet, HashMap, HashSet},
4    hash::Hash,
5};
6
7/// An entry in the `PrioritySet`.
8#[derive(Eq, PartialEq)]
9struct Entry<I: Ord + Hash + Clone, P: Ord + Copy> {
10    item: I,
11    priority: P,
12}
13
14impl<I: Ord + Hash + Clone, P: Ord + Copy> Ord for Entry<I, P> {
15    fn cmp(&self, other: &Self) -> Ordering {
16        match self.priority.cmp(&other.priority) {
17            Ordering::Equal => self.item.cmp(&other.item),
18            other => other,
19        }
20    }
21}
22
23impl<I: Ord + Hash + Clone, V: Ord + Copy> PartialOrd for Entry<I, V> {
24    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
25        Some(self.cmp(other))
26    }
27}
28
29/// A set that offers efficient iteration over
30/// its elements in priority-ascending order.
31pub struct PrioritySet<I: Ord + Hash + Clone, P: Ord + Copy> {
32    entries: BTreeSet<Entry<I, P>>,
33    keys: HashMap<I, P>,
34}
35
36impl<I: Ord + Hash + Clone, P: Ord + Copy> PrioritySet<I, P> {
37    /// Create a new `PrioritySet`.
38    #[allow(clippy::new_without_default)]
39    pub fn new() -> Self {
40        Self {
41            entries: BTreeSet::new(),
42            keys: HashMap::new(),
43        }
44    }
45
46    /// Insert an item with a priority, overwriting the previous priority if it exists.
47    pub fn put(&mut self, item: I, priority: P) {
48        // Remove old entry, if it exists
49        let entry = if let Some(old_priority) = self.keys.remove(&item) {
50            // Remove the item from the old priority's set
51            let mut old_entry = Entry {
52                item: item.clone(),
53                priority: old_priority,
54            };
55            self.entries.remove(&old_entry);
56
57            // We reuse the entry to avoid another item clone
58            old_entry.priority = priority;
59            old_entry
60        } else {
61            Entry { item, priority }
62        };
63
64        // Insert the entry
65        self.keys.insert(entry.item.clone(), entry.priority);
66        self.entries.insert(entry);
67    }
68
69    /// Get the current priority of an item.
70    pub fn get(&self, item: &I) -> Option<P> {
71        self.keys.get(item).cloned()
72    }
73
74    /// Remove an item from the set.
75    ///
76    /// Returns `true` if the item was present.
77    pub fn remove(&mut self, item: &I) -> bool {
78        let Some(entry) = self.keys.remove(item).map(|priority| Entry {
79            item: item.clone(),
80            priority,
81        }) else {
82            return false;
83        };
84        assert!(self.entries.remove(&entry));
85        true
86    }
87
88    /// Remove all previously inserted items not included in `keep`
89    /// and add any items not yet seen with a priority of `initial`.
90    pub fn reconcile(&mut self, keep: &[I], default: P) {
91        // Remove items not in keep
92        let mut retained: HashSet<_> = keep.iter().collect();
93        let to_remove = self
94            .keys
95            .keys()
96            .filter(|item| !retained.remove(*item))
97            .cloned()
98            .collect::<Vec<_>>();
99        for item in to_remove {
100            let priority = self.keys.remove(&item).unwrap();
101            let entry = Entry { item, priority };
102            self.entries.remove(&entry);
103        }
104
105        // Add any items not yet removed with the initial priority
106        for item in retained {
107            self.put(item.clone(), default);
108        }
109    }
110
111    /// Returns `true` if the set contains the item.
112    pub fn contains(&self, item: &I) -> bool {
113        self.keys.contains_key(item)
114    }
115
116    /// Returns the item with the highest priority.
117    pub fn peek(&self) -> Option<(&I, &P)> {
118        self.entries
119            .iter()
120            .next()
121            .map(|entry| (&entry.item, &entry.priority))
122    }
123
124    /// Removes and returns the item with the highest priority.
125    pub fn pop(&mut self) -> Option<(I, P)> {
126        self.entries.pop_first().map(|entry| {
127            self.keys.remove(&entry.item);
128            (entry.item, entry.priority)
129        })
130    }
131
132    /// Returns an iterator over all items in the set in priority-ascending order.
133    pub fn iter(&self) -> impl Iterator<Item = (&I, &P)> {
134        self.entries
135            .iter()
136            .map(|entry| (&entry.item, &entry.priority))
137    }
138
139    /// Returns the number of items in the set.
140    pub fn len(&self) -> usize {
141        self.entries.len()
142    }
143
144    /// Returns `true` if the set is empty.
145    pub fn is_empty(&self) -> bool {
146        self.entries.is_empty()
147    }
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153    use std::time::Duration;
154
155    #[test]
156    fn test_put_remove_and_iter() {
157        // Create a new PrioritySet
158        let mut pq = PrioritySet::new();
159
160        // Add items with different priorities
161        let key1 = "key1";
162        let key2 = "key2";
163        pq.put(key1, Duration::from_secs(10));
164        pq.put(key2, Duration::from_secs(5));
165
166        // Verify iteration order
167        let entries: Vec<_> = pq.iter().collect();
168        assert_eq!(entries.len(), 2);
169        assert_eq!(*entries[0].0, key2);
170        assert_eq!(*entries[1].0, key1);
171
172        // Remove existing item
173        pq.remove(&key1);
174
175        // Verify new iteration order
176        let entries: Vec<_> = pq.iter().collect();
177        assert_eq!(entries.len(), 1);
178        assert_eq!(*entries[0].0, key2);
179
180        // Remove non-existing item
181        pq.remove(&key1);
182
183        // Verify iteration order is still the same
184        let entries: Vec<_> = pq.iter().collect();
185        assert_eq!(entries.len(), 1);
186        assert_eq!(*entries[0].0, key2);
187    }
188
189    #[test]
190    fn test_update() {
191        // Create a new PrioritySet
192        let mut pq = PrioritySet::new();
193
194        // Add an item with a priority and verify it can be retrieved
195        let key = "key";
196        pq.put(key, Duration::from_secs(10));
197        assert_eq!(pq.get(&key).unwrap(), Duration::from_secs(10));
198
199        // Update the priority and verify it has changed
200        pq.put(key, Duration::from_secs(5));
201        assert_eq!(pq.get(&key).unwrap(), Duration::from_secs(5));
202
203        // Verify updated priority is in the iteration
204        let entries: Vec<_> = pq.iter().collect();
205        assert_eq!(entries.len(), 1);
206        assert_eq!(*entries[0].1, Duration::from_secs(5));
207    }
208
209    #[test]
210    fn test_reconcile() {
211        // Create a new PrioritySet
212        let mut pq = PrioritySet::new();
213
214        // Add 2 items with different priorities
215        let key1 = "key1";
216        let key2 = "key2";
217        pq.put(key1, Duration::from_secs(10));
218        pq.put(key2, Duration::from_secs(5));
219
220        // Introduce a new item and remove an existing one
221        let key3 = "key3";
222        pq.reconcile(&[key1, key3], Duration::from_secs(2));
223
224        // Verify iteration over only the kept items
225        let entries: Vec<_> = pq.iter().collect();
226        assert_eq!(entries.len(), 2);
227        assert!(entries
228            .iter()
229            .any(|e| *e.0 == key1 && *e.1 == Duration::from_secs(10)));
230        assert!(entries
231            .iter()
232            .any(|e| *e.0 == key3 && *e.1 == Duration::from_secs(2)));
233    }
234}