|
1 |
| -use std::collections::HashMap; |
2 |
| - |
3 |
| -/// A set that provides removal tokens when an item is added. |
| 1 | +/// A container that provides removal tokens when an item is added. |
4 | 2 | #[derive(Debug, Clone)]
|
5 | 3 | pub(crate) struct IdSet<T> {
|
6 |
| - values: HashMap<u32, T>, |
7 |
| - // Incrementing a counter is not the best source of tokens - it can |
8 |
| - // cause poor hash behavior - but efficiency is not an immediate concern. |
9 |
| - next_id: u32, |
| 4 | + values: Vec<Entry<T>>, |
| 5 | + free: Vec<usize>, |
| 6 | +} |
| 7 | + |
| 8 | +#[derive(Debug, Clone)] |
| 9 | +struct Entry<T> { |
| 10 | + generation: u32, |
| 11 | + value: Option<T>, |
10 | 12 | }
|
11 | 13 |
|
12 | 14 | #[derive(Debug, Clone, PartialEq, Eq)]
|
13 |
| -pub(crate) struct Id(u32); |
| 15 | +pub(crate) struct Id { |
| 16 | + index: usize, |
| 17 | + generation: u32, |
| 18 | +} |
14 | 19 |
|
15 | 20 | impl<T> IdSet<T> {
|
16 | 21 | pub(crate) fn new() -> Self {
|
17 | 22 | Self {
|
18 |
| - values: HashMap::new(), |
19 |
| - next_id: 0, |
| 23 | + values: vec![], |
| 24 | + free: vec![], |
20 | 25 | }
|
21 | 26 | }
|
22 | 27 |
|
23 | 28 | pub(crate) fn insert(&mut self, value: T) -> Id {
|
24 |
| - let id = self.next_id; |
25 |
| - self.next_id += 1; |
26 |
| - self.values.insert(id, value); |
27 |
| - Id(id) |
| 29 | + let value = Some(value); |
| 30 | + if let Some(index) = self.free.pop() { |
| 31 | + let generation = self.values[index].generation + 1; |
| 32 | + self.values[index] = Entry { generation, value }; |
| 33 | + Id { index, generation } |
| 34 | + } else { |
| 35 | + let generation = 0; |
| 36 | + self.values.push(Entry { generation, value }); |
| 37 | + Id { |
| 38 | + index: self.values.len() - 1, |
| 39 | + generation, |
| 40 | + } |
| 41 | + } |
28 | 42 | }
|
29 | 43 |
|
30 | 44 | pub(crate) fn remove(&mut self, id: &Id) {
|
31 |
| - self.values.remove(&id.0); |
| 45 | + if let Some(entry) = self.values.get_mut(id.index) { |
| 46 | + if entry.generation == id.generation { |
| 47 | + entry.value = None; |
| 48 | + self.free.push(id.index); |
| 49 | + } |
| 50 | + } |
32 | 51 | }
|
33 | 52 |
|
34 | 53 | #[cfg(all(test, mongodb_internal_tracking_arc))]
|
35 | 54 | pub(crate) fn values(&self) -> impl Iterator<Item = &T> {
|
36 |
| - self.values.values() |
| 55 | + self.values.iter().filter_map(|e| e.value.as_ref()) |
37 | 56 | }
|
38 | 57 |
|
39 | 58 | pub(crate) fn extract(&mut self) -> Vec<T> {
|
40 |
| - self.values.drain().map(|(_, v)| v).collect() |
| 59 | + self.free.clear(); |
| 60 | + self.values.drain(..).filter_map(|e| e.value).collect() |
41 | 61 | }
|
42 | 62 | }
|
0 commit comments