1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//! An ordered set of items with one key each ([`KeyedSet`]), supporting replace and remove
//! by item.
use alloc::collections::BTreeSet;
use alloc::vec::Vec;
/// Dense item ids (such as node ids) ordered by a key, at most one key per item.
///
/// Unlike a lazy heap it supports exact removal and replacement, so several sets can hold
/// the same items under different orders and stay in step.
#[derive(Debug, Clone)]
pub(crate) struct KeyedSet<K> {
/// `(key, item)` pairs in key order; the item breaks ties between equal keys.
set: BTreeSet<(K, usize)>,
/// The current key of each item, indexed by item id. `None` if the item is absent.
keys: Vec<Option<K>>,
}
impl<K: Ord + Clone> KeyedSet<K> {
/// Creates an empty set.
pub(crate) const fn new() -> Self {
Self {
set: BTreeSet::new(),
keys: Vec::new(),
}
}
/// The number of items in the set.
pub(crate) fn len(&self) -> usize {
self.set.len()
}
/// Returns `true` if the set holds no item.
pub(crate) fn is_empty(&self) -> bool {
self.set.is_empty()
}
/// The current key of `item`, if it is in the set.
pub(crate) fn key(&self, item: usize) -> Option<&K> {
self.keys.get(item).and_then(Option::as_ref)
}
/// Inserts `item` with `key`, replacing its previous key if it had one.
pub(crate) fn insert(&mut self, item: usize, key: K) {
self.remove(item);
if self.keys.len() <= item {
self.keys.resize(item + 1, None);
}
self.set.insert((key.clone(), item));
self.keys[item] = Some(key);
}
/// Removes `item` and returns its key, if it was in the set.
pub(crate) fn remove(&mut self, item: usize) -> Option<K> {
let key = self.keys.get_mut(item)?.take()?;
self.set.remove(&(key.clone(), item));
Some(key)
}
/// The item with the smallest key, and the key.
pub(crate) fn first(&self) -> Option<(&K, usize)> {
self.set.first().map(|(key, item)| (key, *item))
}
}