Skip to main content

kovan_map/hopscotch/
iter.rs

1//! Walking the map: a borrowed walk that keeps the table it started on and yields a key once
2//! (it recognizes a key a displacement carried ahead of it), and the owned walk that consumes
3//! the map.
4
5extern crate alloc;
6
7use super::table::{Entry, Table, Walk, Word};
8use super::{HopscotchMap, NEIGHBORHOOD_SIZE};
9use core::hash::{BuildHasher, Hash};
10use core::marker::PhantomData;
11use core::sync::atomic::Ordering;
12use kovan::{drop_node, free_node, pin};
13
14// Construction: none of `iter`/`keys`/`values` hashes or clones a value (the walks that do
15// live in the `Iterator` impls below). `K: Eq` is captured here as the walk's key comparison
16// (how it recognizes a key it already met), so the `Iterator` impls ask only for the clones they
17// make: `K: Clone` and `V: Clone` for entries, `K: Clone` for keys, `V: Clone` for values.
18impl<K: Eq + 'static, V: 'static, S> HopscotchMap<K, V, S> {
19    /// Returns an iterator over the map entries.
20    ///
21    /// The iterator walks the table that is current when it is created, to
22    /// its end, even when a resize replaces that table meanwhile (the walk's
23    /// position means nothing in another table, whose layout differs). An
24    /// entry present from the iterator's creation to its end is yielded
25    /// exactly once: a resize neither skips nor repeats it, and a
26    /// displacement, which moves an entry to a higher slot of its
27    /// neighborhood, links it there before unlinking it from its old slot (so
28    /// the walk meets it) and the walk recognizes a key it already met there
29    /// (so it is not repeated). An insert publishes its entry's hop bit before
30    /// it links the entry, so an entry the walk finds in a slot is one a
31    /// lookup finds too. An entry inserted, removed or updated concurrently may
32    /// or may not be reflected, and no key is yielded twice. The iterator's
33    /// own loop (`fold`, and `for_each`, `count` and the other folds built on
34    /// it) reads a group of slots before it yields their entries, so a write
35    /// its closure makes is one of those concurrent writes too.
36    pub fn iter(&self) -> HopscotchIter<'_, K, V, S> {
37        let guard = pin();
38        let table = self.table.load(Ordering::Acquire, &guard).as_raw();
39        // SAFETY: loaded under `guard`, which the iterator keeps.
40        let current = unsafe { &*table };
41        let (slots, mask) = (current.buckets.len(), current.home_mask());
42        HopscotchIter {
43            table,
44            slots,
45            mask,
46            bucket_idx: 0,
47            seen: Seen::new(<K as PartialEq>::eq),
48            guard,
49            _map: PhantomData,
50        }
51    }
52
53    /// Returns an iterator over the map keys.
54    pub fn keys(&self) -> HopscotchKeys<'_, K, V, S> {
55        HopscotchKeys { iter: self.iter() }
56    }
57
58    /// Returns an iterator over the map values (clones `V`).
59    pub fn values(&self) -> HopscotchValues<'_, K, V, S> {
60        HopscotchValues { iter: self.iter() }
61    }
62}
63
64/// Iterator over HopscotchMap entries ([`HopscotchMap::iter`]).
65pub struct HopscotchIter<'a, K: 'static, V: 'static, S> {
66    /// The table the walk started on, loaded under `guard`.
67    table: *const Table<K, V>,
68    /// `table`'s slot count and home mask, read once: the walk never reloads them.
69    slots: usize,
70    mask: usize,
71    bucket_idx: usize,
72    seen: Seen<K, V>,
73    guard: kovan::Guard,
74    _map: PhantomData<&'a HopscotchMap<K, V, S>>,
75}
76
77/// Slots a walk's `fold` reads before it yields their entries, and a group whose entries `next`
78/// prefetches when it enters it: one bit each of a `u64`.
79const GROUP: usize = u64::BITS as usize;
80
81/// What a walk remembers of the slots it met: how it recognizes a key it already met.
82struct Seen<K, V> {
83    /// The entry the walk read in each of its last `NEIGHBORHOOD_SIZE` slots (slot `i` at
84    /// `i % NEIGHBORHOOD_SIZE`, null until the walk meets an entry there), loaded under the
85    /// walk's guard.
86    recent: [*const Entry<K, V>; NEIGHBORHOOD_SIZE],
87    /// For each home the walk met an entry of (home `h` at `h % NEIGHBORHOOD_SIZE`): the home's
88    /// low 32 bits over a 32-bit filter of the hashes of the home's entries the walk met, bit
89    /// `hash >> 59` of each. A walk meets a key again only as an entry of the same hash, so the
90    /// same home and the same bit: an entry whose bit is clear in its home's filter is one the
91    /// walk has not met, known without a scan.
92    homes: [u64; NEIGHBORHOOD_SIZE],
93    /// `K`'s equality, taken where `iter` is built.
94    same_key: fn(&K, &K) -> bool,
95}
96
97impl<K, V> Seen<K, V> {
98    /// Nothing met yet.
99    fn new(same_key: fn(&K, &K) -> bool) -> Self {
100        Self {
101            recent: [core::ptr::null(); NEIGHBORHOOD_SIZE],
102            homes: [0; NEIGHBORHOOD_SIZE],
103            same_key,
104        }
105    }
106
107    /// Whether the walk yields `entry`, which it read at slot `idx` (the slots it read before
108    /// are all lower) of a table whose home mask is `mask`: `false` for a key it already met.
109    /// Every walk step, `next` and `fold` alike, is this call.
110    #[inline(always)]
111    fn first_meeting(&mut self, entry: &Entry<K, V>, idx: usize, mask: usize) -> bool {
112        self.recent[idx % NEIGHBORHOOD_SIZE] = entry;
113        let home = (entry.hash as usize) & mask;
114        // The filter of `home` as the walk left it at its last entry of `home`, or an empty one
115        // when the cell names another home. Every entry of `home` lies in its neighborhood,
116        // `home..home + NEIGHBORHOOD_SIZE`, so no entry of another home of this cell lies
117        // between two entries of `home` in slot order: the cell holds `home`'s filter from the
118        // walk's first entry of `home` to its last. (A home equal to `home` in its low 32 bits
119        // only is `NEIGHBORHOOD_SIZE` homes away or more: its bits can only add a scan.)
120        let cell = &mut self.homes[home % NEIGHBORHOOD_SIZE];
121        let bit = 1u32 << (entry.hash >> 59);
122        let filter =
123            core::hint::select_unpredictable((*cell >> 32) as u32 == home as u32, *cell as u32, 0);
124        *cell = (u64::from(home as u32) << 32) | u64::from(filter | bit);
125        filter & bit == 0 || !self.met_before(home, idx, entry)
126    }
127
128    /// Whether the walk already met the key of `entry`, read at slot `idx`, in a lower slot of
129    /// the key's neighborhood (which starts at `home`). A move carries an entry to a higher slot
130    /// of its neighborhood, so the walk can meet it a second time there (or a newer entry of its
131    /// key, after an update or a re-insert). Every slot of that neighborhood below `idx` is still
132    /// in `recent`: the neighborhood spans `NEIGHBORHOOD_SIZE` slots. A cell the walk last wrote
133    /// at least `NEIGHBORHOOD_SIZE` slots back (a free slot leaves its cell as it was) holds an
134    /// entry of a lower home, whose hash differs; the walk's guard keeps it allocated.
135    #[cold]
136    #[inline(never)]
137    fn met_before(&self, home: usize, idx: usize, entry: &Entry<K, V>) -> bool {
138        let lowest = home.max(idx.saturating_sub(NEIGHBORHOOD_SIZE - 1));
139        (lowest..idx).any(|seen_idx| {
140            let seen = self.recent[seen_idx % NEIGHBORHOOD_SIZE];
141            // SAFETY: null for a slot where the walk met no entry yet, else loaded under the
142            // walk's guard, which keeps it from being freed.
143            unsafe { seen.as_ref() }.is_some_and(|seen| {
144                seen.hash == entry.hash
145                    && (core::ptr::eq(seen, entry) || (self.same_key)(&seen.key, &entry.key))
146            })
147        })
148    }
149}
150
151impl<K, V, S> HopscotchIter<'_, K, V, S> {
152    /// The next entry the walk yields: the step of every `next` of the map's walks.
153    #[inline(always)]
154    fn next_entry(&mut self) -> Option<&Entry<K, V>> {
155        // SAFETY: owned by this iterator's `guard`, which was pinned before `table` was loaded
156        // and dies with the iterator: a resize that retires the table cannot free it (or its
157        // entries) while the guard is held.
158        let table = unsafe { &*self.table };
159        while self.bucket_idx < self.slots {
160            let idx = self.bucket_idx;
161            self.bucket_idx += 1;
162            if idx.is_multiple_of(GROUP) {
163                // The entries of the group of slots the walk enters reach the cache while it
164                // walks them. Only a hint: the walk reads each slot again when it gets there.
165                // Relaxed: no entry is read through these words.
166                for bucket in &table.buckets[idx..self.slots.min(idx + GROUP)] {
167                    table.prefetch_entry(bucket.load(Ordering::Relaxed, &self.guard).ptr());
168                }
169            }
170            let entry = table
171                .get_bucket(idx)
172                .load(Ordering::Acquire, &self.guard)
173                .entry();
174            if let Some(entry) = entry
175                && self.seen.first_meeting(entry, idx, self.mask)
176            {
177                return Some(entry);
178            }
179        }
180        None
181    }
182
183    /// The rest of the walk, `f` on each entry it yields, in one loop whose position and
184    /// accumulator are locals: the loop of every `fold` of the map's walks. It reads the slots
185    /// a group of `GROUP` at a time, in order, and then yields the entries it read there: each
186    /// entry's line, prefetched when its slot is read, reaches the cache while the rest of the
187    /// group is read, and the group's free slots cost no branch. It reads each slot once, in
188    /// order, as `next` does, so what it yields keeps the guarantees of [`HopscotchMap::iter`];
189    /// it reads a slot up to `GROUP - 1` slots before it yields the slot's entry.
190    #[inline(always)]
191    fn fold_entries<B>(self, init: B, mut f: impl FnMut(B, &Entry<K, V>) -> B) -> B {
192        let Self {
193            table,
194            slots,
195            mask,
196            bucket_idx,
197            mut seen,
198            guard,
199            ..
200        } = self;
201        // SAFETY: as in `next_entry`: `guard` was pinned before `table` was loaded and lives to
202        // the end of this call.
203        let table = unsafe { &*table };
204        let mut acc = init;
205        let mut group = [core::ptr::null::<Entry<K, V>>(); GROUP];
206        let mut first = bucket_idx;
207        for buckets in table.buckets[bucket_idx..slots].chunks(GROUP) {
208            let mut occupied = 0u64;
209            for (offset, (bucket, cell)) in buckets.iter().zip(&mut group).enumerate() {
210                let entry: *const Entry<K, V> = bucket.load(Ordering::Acquire, &guard).ptr();
211                *cell = entry;
212                occupied |= u64::from(!entry.is_null()) << offset;
213                table.prefetch_entry(entry);
214            }
215            while occupied != 0 {
216                let offset = occupied.trailing_zeros() as usize;
217                occupied &= occupied - 1;
218                // SAFETY: a slot's non-null word, loaded under `guard`, which keeps its entry from
219                // being freed.
220                let entry = unsafe { &*group[offset] };
221                if seen.first_meeting(entry, first + offset, mask) {
222                    acc = f(acc, entry);
223                }
224            }
225            first += buckets.len();
226        }
227        acc
228    }
229}
230
231impl<'a, K, V, S> Iterator for HopscotchIter<'a, K, V, S>
232where
233    K: Clone,
234    V: Clone,
235{
236    type Item = (K, V);
237
238    fn next(&mut self) -> Option<Self::Item> {
239        self.next_entry()
240            .map(|entry| (entry.key.clone(), entry.value.clone()))
241    }
242
243    /// The rest of the walk in the walk's own loop (`for_each`, `count`, `sum` and the other
244    /// folds of `Iterator` come here).
245    fn fold<B, F>(self, init: B, mut f: F) -> B
246    where
247        F: FnMut(B, Self::Item) -> B,
248    {
249        self.fold_entries(init, |acc, entry| {
250            f(acc, (entry.key.clone(), entry.value.clone()))
251        })
252    }
253}
254
255/// Iterator over HopscotchMap keys (clones `K`).
256pub struct HopscotchKeys<'a, K: 'static, V: 'static, S> {
257    iter: HopscotchIter<'a, K, V, S>,
258}
259
260impl<'a, K, V, S> Iterator for HopscotchKeys<'a, K, V, S>
261where
262    K: Clone,
263{
264    type Item = K;
265
266    fn next(&mut self) -> Option<K> {
267        self.iter.next_entry().map(|entry| entry.key.clone())
268    }
269
270    fn fold<B, F>(self, init: B, mut f: F) -> B
271    where
272        F: FnMut(B, K) -> B,
273    {
274        self.iter
275            .fold_entries(init, |acc, entry| f(acc, entry.key.clone()))
276    }
277}
278
279/// Iterator over HopscotchMap values (clones `V`).
280pub struct HopscotchValues<'a, K: 'static, V: 'static, S> {
281    iter: HopscotchIter<'a, K, V, S>,
282}
283
284impl<'a, K, V, S> Iterator for HopscotchValues<'a, K, V, S>
285where
286    V: Clone,
287{
288    type Item = V;
289
290    fn next(&mut self) -> Option<V> {
291        self.iter.next_entry().map(|entry| entry.value.clone())
292    }
293
294    fn fold<B, F>(self, init: B, mut f: F) -> B
295    where
296        F: FnMut(B, V) -> B,
297    {
298        self.iter
299            .fold_entries(init, |acc, entry| f(acc, entry.value.clone()))
300    }
301}
302
303/// Owned iterator yielding `(K, V)` by value - moves out of the entries, no
304/// clone. Each drained slot is nulled so the table destructor stays a no-op.
305pub struct HopscotchIntoIter<K: 'static, V: 'static> {
306    table: *mut Table<K, V>,
307    walk: Walk<K, V>,
308    guard: kovan::Guard,
309}
310
311impl<K, V> Iterator for HopscotchIntoIter<K, V> {
312    type Item = (K, V);
313
314    fn next(&mut self) -> Option<(K, V)> {
315        let table = unsafe { &*self.table };
316        while let Some((idx, entry)) = self.walk.next(table, &self.guard) {
317            if !entry.is_null() {
318                table.get_bucket(idx).store(Word::free(), Ordering::Relaxed);
319                let k = unsafe { core::ptr::read(&(*entry).key) };
320                let v = unsafe { core::ptr::read(&(*entry).value) };
321                unsafe { free_node(entry) };
322                return Some((k, v));
323            }
324        }
325        None
326    }
327}
328
329impl<K, V> Drop for HopscotchIntoIter<K, V> {
330    fn drop(&mut self) {
331        while self.next().is_some() {}
332        // All slots nulled above; Table::drop frees only the bucket array.
333        unsafe { drop_node(self.table) };
334    }
335}
336
337impl<K, V, S> IntoIterator for HopscotchMap<K, V, S>
338where
339    K: 'static,
340    V: 'static,
341{
342    type Item = (K, V);
343    type IntoIter = HopscotchIntoIter<K, V>;
344
345    fn into_iter(self) -> HopscotchIntoIter<K, V> {
346        let mut me = core::mem::ManuallyDrop::new(self);
347        let guard = pin();
348        let table = me.table.load(Ordering::Relaxed, &guard).as_raw();
349        unsafe { core::ptr::drop_in_place(&mut me.hasher) };
350        // SAFETY: the map is consumed, so the table is this iterator's alone.
351        let walk = Walk::new(unsafe { &*table }, &guard);
352        HopscotchIntoIter { table, walk, guard }
353    }
354}
355
356// `K: Send, V: Send`: an entry an insert replaces is retired, and its destructor may run on
357// another thread.
358impl<K, V, S> core::iter::FromIterator<(K, V)> for HopscotchMap<K, V, S>
359where
360    K: Hash + Eq + Clone + Send + 'static,
361    V: Clone + Send + 'static,
362    S: BuildHasher + Default,
363{
364    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
365        let map = Self::with_hasher(S::default());
366        for (k, v) in iter {
367            map.insert(k, v);
368        }
369        map
370    }
371}
372
373// A concurrent walk yields owned clones (`K: Clone`, `V: Clone`) and recognizes a key it already
374// met (`K: Eq`, taken by `iter`), so these bounds are unavoidable here, unlike std's
375// unconstrained `IntoIterator for &HashMap`, which yields borrowed `(&K, &V)` and hashes nothing
376// at this bound-checked level either.
377impl<'a, K, V, S> IntoIterator for &'a HopscotchMap<K, V, S>
378where
379    K: Eq + Clone + 'static,
380    V: Clone + 'static,
381{
382    type Item = (K, V);
383    type IntoIter = HopscotchIter<'a, K, V, S>;
384
385    fn into_iter(self) -> Self::IntoIter {
386        self.iter()
387    }
388}