thunderation 0.2.0

Fast arena-based map with compact generational indices
Documentation
use core::iter::{ExactSizeIterator, FusedIterator};

use crate::{Arena, Key};

/// See [`Arena::drain`].
pub struct Drain<'a, K: Copy, V> {
    pub(crate) arena: &'a mut Arena<K, V>,
    pub(crate) slot: u32,
}

impl<'a, K: Copy, V> Iterator for Drain<'a, K, V> {
    type Item = (Key<K>, V);

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            // If there are no entries remaining in the arena, we should always
            // return None. Using this check instead of comparing with the
            // arena's size allows us to skip any trailing empty entries.
            if self.arena.is_empty() {
                return None;
            }

            // slot may overflow if the arena's underlying storage contains more
            // than 2^32 elements, but its internal length value was not
            // changed, as it overflowing would panic before reaching this code.
            let slot = self.slot;
            self.slot = self
                .slot
                .checked_add(1)
                .unwrap_or_else(|| panic!("Overflowed u32 trying to drain Arena"));

            // If this entry is occupied, this method will mark it as an empty.
            // Otherwise, we'll continue looping until we've drained all
            // occupied entries from the arena.
            if let Some((key, value)) = self.arena.remove_by_slot(slot) {
                return Some((key, value));
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.arena.len(), Some(self.arena.len()))
    }
}

impl<'a, K: Copy, V> FusedIterator for Drain<'a, K, V> {}
impl<'a, K: Copy, V> ExactSizeIterator for Drain<'a, K, V> {}

impl<'a, K: Copy, V> Drop for Drain<'a, K, V> {
    // Continue iterating/dropping if there are any elements left.
    fn drop(&mut self) {
        self.for_each(drop);
    }
}

#[cfg(test)]
mod test {
    use crate::Arena;

    #[cfg(not(feature = "std"))]
    use alloc::vec::Vec;

    #[test]
    fn drain() {
        let mut arena = Arena::<(), u32>::with_capacity(3);
        let one = arena.insert(1);
        let two = arena.insert(2);
        let three = arena.insert(3);

        let mut drained_pairs = Vec::new();
        {
            let mut drain = arena.drain();
            assert_eq!(drain.size_hint(), (3, Some(3)));

            let next = drain.next().unwrap();
            assert!(!drained_pairs.contains(&next));
            drained_pairs.push(next);

            assert_eq!(drain.size_hint(), (2, Some(2)));

            let next = drain.next().unwrap();
            assert!(!drained_pairs.contains(&next));
            drained_pairs.push(next);

            assert_eq!(drain.size_hint(), (1, Some(1)));

            // Do not fully drain so we can ensure everything is dropped when the
            // `Drain` is dropped.
            assert_eq!(drain.size_hint(), (1, Some(1)));
        }

        assert_eq!(arena.len(), 0);
        assert!(arena.capacity() >= 3);
        assert_eq!(drained_pairs.len(), 2);

        // We should still be able to use the arena after this.
        let one_prime = arena.insert(1);
        let two_prime = arena.insert(2);
        let three_prime = arena.insert(3);

        assert_eq!(arena.len(), 3);
        assert!(arena.capacity() >= 3);
        assert_eq!(arena.get(one_prime), Some(&1));
        assert_eq!(arena.get(two_prime), Some(&2));
        assert_eq!(arena.get(three_prime), Some(&3));
        assert_eq!(arena.get(one), None);
        assert_eq!(arena.get(two), None);
        assert_eq!(arena.get(three), None);
    }
}