slab/
lib.rs

1#![no_std]
2#![warn(
3    missing_debug_implementations,
4    missing_docs,
5    rust_2018_idioms,
6    unreachable_pub
7)]
8#![doc(test(
9    no_crate_inject,
10    attr(deny(warnings, rust_2018_idioms), allow(dead_code, unused_variables))
11))]
12#![allow(clippy::incompatible_msrv)] // false positive: https://github.com/rust-lang/rust-clippy/issues/12280
13
14//! Pre-allocated storage for a uniform data type.
15//!
16//! `Slab` provides pre-allocated storage for a single data type. If many values
17//! of a single type are being allocated, it can be more efficient to
18//! pre-allocate the necessary storage. Since the size of the type is uniform,
19//! memory fragmentation can be avoided. Storing, clearing, and lookup
20//! operations become very cheap.
21//!
22//! While `Slab` may look like other Rust collections, it is not intended to be
23//! used as a general purpose collection. The primary difference between `Slab`
24//! and `Vec` is that `Slab` returns the key when storing the value.
25//!
26//! It is important to note that keys may be reused. In other words, once a
27//! value associated with a given key is removed from a slab, that key may be
28//! returned from future calls to `insert`.
29//!
30//! # Performance notes
31//!
32//! Methods that remove values and return them, such as [`Slab::remove`] and
33//! [`Slab::try_remove`], might copy the removed values to the stack even if
34//! their return values are unused. For types that don't have drop glue, the
35//! compiler can usually elide these copies.
36//!
37//! # Examples
38//!
39//! Basic storing and retrieval.
40//!
41//! ```
42//! # use slab::*;
43//! let mut slab = Slab::new();
44//!
45//! let hello = slab.insert("hello");
46//! let world = slab.insert("world");
47//!
48//! assert_eq!(slab[hello], "hello");
49//! assert_eq!(slab[world], "world");
50//!
51//! slab[world] = "earth";
52//! assert_eq!(slab[world], "earth");
53//! ```
54//!
55//! Sometimes it is useful to be able to associate the key with the value being
56//! inserted in the slab. This can be done with the `vacant_entry` API as such:
57//!
58//! ```
59//! # use slab::*;
60//! let mut slab = Slab::new();
61//!
62//! let hello = {
63//!     let entry = slab.vacant_entry();
64//!     let key = entry.key();
65//!
66//!     entry.insert((key, "hello"));
67//!     key
68//! };
69//!
70//! assert_eq!(hello, slab[hello].0);
71//! assert_eq!("hello", slab[hello].1);
72//! ```
73//!
74//! It is generally a good idea to specify the desired capacity of a slab at
75//! creation time. Note that `Slab` will grow the internal capacity when
76//! attempting to insert a new value once the existing capacity has been reached.
77//! To avoid this, add a check.
78//!
79//! ```
80//! # use slab::*;
81//! let mut slab = Slab::with_capacity(1024);
82//!
83//! // ... use the slab
84//!
85//! if slab.len() == slab.capacity() {
86//!     panic!("slab full");
87//! }
88//!
89//! slab.insert("the slab is not at capacity yet");
90//! ```
91//!
92//! # Capacity and reallocation
93//!
94//! The capacity of a slab is the amount of space allocated for any future
95//! values that will be inserted in the slab. This is not to be confused with
96//! the *length* of the slab, which specifies the number of actual values
97//! currently being inserted. If a slab's length is equal to its capacity, the
98//! next value inserted into the slab will require growing the slab by
99//! reallocating.
100//!
101//! For example, a slab with capacity 10 and length 0 would be an empty slab
102//! with space for 10 more stored values. Storing 10 or fewer elements into the
103//! slab will not change its capacity or cause reallocation to occur. However,
104//! if the slab length is increased to 11 (due to another `insert`), it will
105//! have to reallocate, which can be slow. For this reason, it is recommended to
106//! use [`Slab::with_capacity`] whenever possible to specify how many values the
107//! slab is expected to store.
108//!
109//! # Implementation
110//!
111//! `Slab` is backed by a `Vec` of slots. Each slot is either occupied or
112//! vacant. `Slab` maintains a stack of vacant slots using a linked list. To
113//! find a vacant slot, the stack is popped. When a slot is released, it is
114//! pushed onto the stack.
115//!
116//! If there are no more available slots in the stack, then `Vec::reserve(1)` is
117//! called and a new slot is created.
118//!
119//! [`Slab::with_capacity`]: struct.Slab.html#with_capacity
120
121#[cfg(not(feature = "std"))]
122extern crate alloc;
123#[cfg(feature = "std")]
124extern crate std;
125#[cfg(feature = "std")]
126extern crate std as alloc;
127
128#[cfg(feature = "serde")]
129mod serde;
130
131mod builder;
132
133use alloc::vec::{self, Vec};
134use core::iter::{self, FromIterator, FusedIterator};
135use core::mem::MaybeUninit;
136use core::{fmt, mem, ops, slice};
137
138/// Pre-allocated storage for a uniform data type
139///
140/// See the [module documentation] for more details.
141///
142/// [module documentation]: index.html
143pub struct Slab<T> {
144    // Chunk of memory
145    entries: Vec<Entry<T>>,
146
147    // Number of Filled elements currently in the slab
148    len: usize,
149
150    // Offset of the next available slot in the slab. Set to the slab's
151    // capacity when the slab is full.
152    next: usize,
153}
154
155impl<T> Clone for Slab<T>
156where
157    T: Clone,
158{
159    fn clone(&self) -> Self {
160        Self {
161            entries: self.entries.clone(),
162            len: self.len,
163            next: self.next,
164        }
165    }
166
167    fn clone_from(&mut self, source: &Self) {
168        self.entries.clone_from(&source.entries);
169        self.len = source.len;
170        self.next = source.next;
171    }
172}
173
174impl<T> Default for Slab<T> {
175    fn default() -> Self {
176        Slab::new()
177    }
178}
179
180#[derive(Debug, Clone, PartialEq, Eq)]
181/// The error type returned by [`Slab::get_disjoint_mut`].
182pub enum GetDisjointMutError {
183    /// An index provided was not associated with a value.
184    IndexVacant,
185
186    /// An index provided was out-of-bounds for the slab.
187    IndexOutOfBounds,
188
189    /// Two indices provided were overlapping.
190    OverlappingIndices,
191}
192
193impl fmt::Display for GetDisjointMutError {
194    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195        let msg = match self {
196            GetDisjointMutError::IndexVacant => "an index is vacant",
197            GetDisjointMutError::IndexOutOfBounds => "an index is out of bounds",
198            GetDisjointMutError::OverlappingIndices => "there were overlapping indices",
199        };
200        fmt::Display::fmt(msg, f)
201    }
202}
203
204#[cfg(feature = "std")]
205impl std::error::Error for GetDisjointMutError {}
206
207/// A handle to a vacant entry in a `Slab`.
208///
209/// `VacantEntry` allows constructing values with the key that they will be
210/// assigned to.
211///
212/// # Examples
213///
214/// ```
215/// # use slab::*;
216/// let mut slab = Slab::new();
217///
218/// let hello = {
219///     let entry = slab.vacant_entry();
220///     let key = entry.key();
221///
222///     entry.insert((key, "hello"));
223///     key
224/// };
225///
226/// assert_eq!(hello, slab[hello].0);
227/// assert_eq!("hello", slab[hello].1);
228/// ```
229#[derive(Debug)]
230pub struct VacantEntry<'a, T> {
231    slab: &'a mut Slab<T>,
232    key: usize,
233}
234
235/// A consuming iterator over the values stored in a `Slab`
236pub struct IntoIter<T> {
237    entries: iter::Enumerate<vec::IntoIter<Entry<T>>>,
238    len: usize,
239}
240
241/// An iterator over the values stored in the `Slab`
242pub struct Iter<'a, T> {
243    entries: iter::Enumerate<slice::Iter<'a, Entry<T>>>,
244    len: usize,
245}
246
247impl<T> Clone for Iter<'_, T> {
248    fn clone(&self) -> Self {
249        Self {
250            entries: self.entries.clone(),
251            len: self.len,
252        }
253    }
254}
255
256/// A mutable iterator over the values stored in the `Slab`
257pub struct IterMut<'a, T> {
258    entries: iter::Enumerate<slice::IterMut<'a, Entry<T>>>,
259    len: usize,
260}
261
262/// A draining iterator for `Slab`
263pub struct Drain<'a, T> {
264    inner: vec::Drain<'a, Entry<T>>,
265    len: usize,
266}
267
268#[derive(Clone)]
269enum Entry<T> {
270    Vacant(usize),
271    Occupied(T),
272}
273
274impl<T> Slab<T> {
275    /// Construct a new, empty `Slab`.
276    ///
277    /// The function does not allocate and the returned slab will have no
278    /// capacity until `insert` is called or capacity is explicitly reserved.
279    ///
280    /// # Examples
281    ///
282    /// ```
283    /// # use slab::*;
284    /// let slab: Slab<i32> = Slab::new();
285    /// ```
286    pub const fn new() -> Self {
287        Self {
288            entries: Vec::new(),
289            next: 0,
290            len: 0,
291        }
292    }
293
294    /// Construct a new, empty `Slab` with the specified capacity.
295    ///
296    /// The returned slab will be able to store exactly `capacity` without
297    /// reallocating. If `capacity` is 0, the slab will not allocate.
298    ///
299    /// It is important to note that this function does not specify the *length*
300    /// of the returned slab, but only the capacity. For an explanation of the
301    /// difference between length and capacity, see [Capacity and
302    /// reallocation](index.html#capacity-and-reallocation).
303    ///
304    /// # Examples
305    ///
306    /// ```
307    /// # use slab::*;
308    /// let mut slab = Slab::with_capacity(10);
309    ///
310    /// // The slab contains no values, even though it has capacity for more
311    /// assert_eq!(slab.len(), 0);
312    ///
313    /// // These are all done without reallocating...
314    /// for i in 0..10 {
315    ///     slab.insert(i);
316    /// }
317    ///
318    /// // ...but this may make the slab reallocate
319    /// slab.insert(11);
320    /// ```
321    pub fn with_capacity(capacity: usize) -> Slab<T> {
322        Slab {
323            entries: Vec::with_capacity(capacity),
324            next: 0,
325            len: 0,
326        }
327    }
328
329    /// Return the number of values the slab can store without reallocating.
330    ///
331    /// # Examples
332    ///
333    /// ```
334    /// # use slab::*;
335    /// let slab: Slab<i32> = Slab::with_capacity(10);
336    /// assert_eq!(slab.capacity(), 10);
337    /// ```
338    pub fn capacity(&self) -> usize {
339        self.entries.capacity()
340    }
341
342    /// Reserve capacity for at least `additional` more values to be stored
343    /// without allocating.
344    ///
345    /// `reserve` does nothing if the slab already has sufficient capacity for
346    /// `additional` more values. If more capacity is required, a new segment of
347    /// memory will be allocated and all existing values will be copied into it.
348    /// As such, if the slab is already very large, a call to `reserve` can end
349    /// up being expensive.
350    ///
351    /// The slab may reserve more than `additional` extra space in order to
352    /// avoid frequent reallocations. Use `reserve_exact` instead to guarantee
353    /// that only the requested space is allocated.
354    ///
355    /// # Panics
356    ///
357    /// Panics if the new capacity exceeds `isize::MAX` bytes.
358    ///
359    /// # Examples
360    ///
361    /// ```
362    /// # use slab::*;
363    /// let mut slab = Slab::new();
364    /// slab.insert("hello");
365    /// slab.reserve(10);
366    /// assert!(slab.capacity() >= 11);
367    /// ```
368    pub fn reserve(&mut self, additional: usize) {
369        if self.capacity() - self.len >= additional {
370            return;
371        }
372        let need_add = additional - (self.entries.len() - self.len);
373        self.entries.reserve(need_add);
374    }
375
376    /// Reserve the minimum capacity required to store exactly `additional`
377    /// more values.
378    ///
379    /// `reserve_exact` does nothing if the slab already has sufficient capacity
380    /// for `additional` more values. If more capacity is required, a new segment
381    /// of memory will be allocated and all existing values will be copied into
382    /// it.  As such, if the slab is already very large, a call to `reserve` can
383    /// end up being expensive.
384    ///
385    /// Note that the allocator may give the slab more space than it requests.
386    /// Therefore capacity can not be relied upon to be precisely minimal.
387    /// Prefer `reserve` if future insertions are expected.
388    ///
389    /// # Panics
390    ///
391    /// Panics if the new capacity exceeds `isize::MAX` bytes.
392    ///
393    /// # Examples
394    ///
395    /// ```
396    /// # use slab::*;
397    /// let mut slab = Slab::new();
398    /// slab.insert("hello");
399    /// slab.reserve_exact(10);
400    /// assert!(slab.capacity() >= 11);
401    /// ```
402    pub fn reserve_exact(&mut self, additional: usize) {
403        if self.capacity() - self.len >= additional {
404            return;
405        }
406        let need_add = additional - (self.entries.len() - self.len);
407        self.entries.reserve_exact(need_add);
408    }
409
410    /// Shrink the capacity of the slab as much as possible without invalidating keys.
411    ///
412    /// Because values cannot be moved to a different index, the slab cannot
413    /// shrink past any stored values.
414    /// It will drop down as close as possible to the length but the allocator may
415    /// still inform the underlying vector that there is space for a few more elements.
416    ///
417    /// This function can take O(n) time even when the capacity cannot be reduced
418    /// or the allocation is shrunk in place. Repeated calls run in O(1) though.
419    ///
420    /// # Examples
421    ///
422    /// ```
423    /// # use slab::*;
424    /// let mut slab = Slab::with_capacity(10);
425    ///
426    /// for i in 0..3 {
427    ///     slab.insert(i);
428    /// }
429    ///
430    /// slab.shrink_to_fit();
431    /// assert!(slab.capacity() >= 3 && slab.capacity() < 10);
432    /// ```
433    ///
434    /// The slab cannot shrink past the last present value even if previous
435    /// values are removed:
436    ///
437    /// ```
438    /// # use slab::*;
439    /// let mut slab = Slab::with_capacity(10);
440    ///
441    /// for i in 0..4 {
442    ///     slab.insert(i);
443    /// }
444    ///
445    /// slab.remove(0);
446    /// slab.remove(3);
447    ///
448    /// slab.shrink_to_fit();
449    /// assert!(slab.capacity() >= 3 && slab.capacity() < 10);
450    /// ```
451    pub fn shrink_to_fit(&mut self) {
452        // Remove all vacant entries after the last occupied one, so that
453        // the capacity can be reduced to what is actually needed.
454        // If the slab is empty the vector can simply be cleared, but that
455        // optimization would not affect time complexity when T: Drop.
456        let len_before = self.entries.len();
457        while let Some(&Entry::Vacant(_)) = self.entries.last() {
458            self.entries.pop();
459        }
460
461        // Removing entries breaks the list of vacant entries,
462        // so it must be repaired
463        if self.entries.len() != len_before {
464            // Some vacant entries were removed, so the list now likely¹
465            // either contains references to the removed entries, or has an
466            // invalid end marker. Fix this by recreating the list.
467            self.recreate_vacant_list();
468            // ¹: If the removed entries formed the tail of the list, with the
469            // most recently popped entry being the head of them, (so that its
470            // index is now the end marker) the list is still valid.
471            // Checking for that unlikely scenario of this infrequently called
472            // is not worth the code complexity.
473        }
474
475        self.entries.shrink_to_fit();
476    }
477
478    /// Iterate through all entries to recreate and repair the vacant list.
479    /// self.len must be correct and is not modified.
480    fn recreate_vacant_list(&mut self) {
481        self.next = self.entries.len();
482        // We can stop once we've found all vacant entries
483        let mut remaining_vacant = self.entries.len() - self.len;
484        if remaining_vacant == 0 {
485            return;
486        }
487
488        // Iterate in reverse order so that lower keys are at the start of
489        // the vacant list. This way future shrinks are more likely to be
490        // able to remove vacant entries.
491        for (i, entry) in self.entries.iter_mut().enumerate().rev() {
492            if let Entry::Vacant(ref mut next) = *entry {
493                *next = self.next;
494                self.next = i;
495                remaining_vacant -= 1;
496                if remaining_vacant == 0 {
497                    break;
498                }
499            }
500        }
501    }
502
503    /// Reduce the capacity as much as possible, changing the key for elements when necessary.
504    ///
505    /// To allow updating references to the elements which must be moved to a new key,
506    /// this function takes a closure which is called before moving each element.
507    /// The second and third parameters to the closure are the current key and
508    /// new key respectively.
509    /// In case changing the key for one element turns out not to be possible,
510    /// the move can be cancelled by returning `false` from the closure.
511    /// In that case no further attempts at relocating elements is made.
512    /// If the closure unwinds, the slab will be left in a consistent state,
513    /// but the value that the closure panicked on might be removed.
514    ///
515    /// # Examples
516    ///
517    /// ```
518    /// # use slab::*;
519    ///
520    /// let mut slab = Slab::with_capacity(10);
521    /// let a = slab.insert('a');
522    /// slab.insert('b');
523    /// slab.insert('c');
524    /// slab.remove(a);
525    /// slab.compact(|&mut value, from, to| {
526    ///     assert_eq!((value, from, to), ('c', 2, 0));
527    ///     true
528    /// });
529    /// assert!(slab.capacity() >= 2 && slab.capacity() < 10);
530    /// ```
531    ///
532    /// The value is not moved when the closure returns `Err`:
533    ///
534    /// ```
535    /// # use slab::*;
536    ///
537    /// let mut slab = Slab::with_capacity(100);
538    /// let a = slab.insert('a');
539    /// let b = slab.insert('b');
540    /// slab.remove(a);
541    /// slab.compact(|&mut value, from, to| false);
542    /// assert_eq!(slab.iter().next(), Some((b, &'b')));
543    /// ```
544    pub fn compact<F>(&mut self, mut rekey: F)
545    where
546        F: FnMut(&mut T, usize, usize) -> bool,
547    {
548        // If the closure unwinds, we need to restore a valid list of vacant entries
549        struct CleanupGuard<'a, T> {
550            slab: &'a mut Slab<T>,
551            decrement: bool,
552        }
553        impl<T> Drop for CleanupGuard<'_, T> {
554            fn drop(&mut self) {
555                if self.decrement {
556                    // Value was popped and not pushed back on
557                    self.slab.len -= 1;
558                }
559                self.slab.recreate_vacant_list();
560            }
561        }
562        let mut guard = CleanupGuard {
563            slab: self,
564            decrement: true,
565        };
566
567        let mut occupied_until = 0;
568        // While there are vacant entries
569        while guard.slab.entries.len() > guard.slab.len {
570            // Find a value that needs to be moved,
571            // by popping entries until we find an occupied one.
572            // (entries cannot be empty because 0 is not greater than anything)
573            if let Some(Entry::Occupied(mut value)) = guard.slab.entries.pop() {
574                // Found one, now find a vacant entry to move it to
575                while let Some(&Entry::Occupied(_)) = guard.slab.entries.get(occupied_until) {
576                    occupied_until += 1;
577                }
578                // Let the caller try to update references to the key
579                if !rekey(&mut value, guard.slab.entries.len(), occupied_until) {
580                    // Changing the key failed, so push the entry back on at its old index.
581                    guard.slab.entries.push(Entry::Occupied(value));
582                    guard.decrement = false;
583                    guard.slab.entries.shrink_to_fit();
584                    return;
585                    // Guard drop handles cleanup
586                }
587                // Put the value in its new spot
588                guard.slab.entries[occupied_until] = Entry::Occupied(value);
589                // ... and mark it as occupied (this is optional)
590                occupied_until += 1;
591            }
592        }
593        guard.slab.next = guard.slab.len;
594        guard.slab.entries.shrink_to_fit();
595        // Normal cleanup is not necessary
596        mem::forget(guard);
597    }
598
599    /// Clear the slab of all values.
600    ///
601    /// # Examples
602    ///
603    /// ```
604    /// # use slab::*;
605    /// let mut slab = Slab::new();
606    ///
607    /// for i in 0..3 {
608    ///     slab.insert(i);
609    /// }
610    ///
611    /// slab.clear();
612    /// assert!(slab.is_empty());
613    /// ```
614    pub fn clear(&mut self) {
615        self.entries.clear();
616        self.len = 0;
617        self.next = 0;
618    }
619
620    /// Return the number of stored values.
621    ///
622    /// # Examples
623    ///
624    /// ```
625    /// # use slab::*;
626    /// let mut slab = Slab::new();
627    ///
628    /// for i in 0..3 {
629    ///     slab.insert(i);
630    /// }
631    ///
632    /// assert_eq!(3, slab.len());
633    /// ```
634    pub fn len(&self) -> usize {
635        self.len
636    }
637
638    /// Return `true` if there are no values stored in the slab.
639    ///
640    /// # Examples
641    ///
642    /// ```
643    /// # use slab::*;
644    /// let mut slab = Slab::new();
645    /// assert!(slab.is_empty());
646    ///
647    /// slab.insert(1);
648    /// assert!(!slab.is_empty());
649    /// ```
650    pub fn is_empty(&self) -> bool {
651        self.len == 0
652    }
653
654    /// Return an iterator over the slab.
655    ///
656    /// This function should generally be **avoided** as it is not efficient.
657    /// Iterators must iterate over every slot in the slab even if it is
658    /// vacant. As such, a slab with a capacity of 1 million but only one
659    /// stored value must still iterate the million slots.
660    ///
661    /// # Examples
662    ///
663    /// ```
664    /// # use slab::*;
665    /// let mut slab = Slab::new();
666    ///
667    /// for i in 0..3 {
668    ///     slab.insert(i);
669    /// }
670    ///
671    /// let mut iterator = slab.iter();
672    ///
673    /// assert_eq!(iterator.next(), Some((0, &0)));
674    /// assert_eq!(iterator.next(), Some((1, &1)));
675    /// assert_eq!(iterator.next(), Some((2, &2)));
676    /// assert_eq!(iterator.next(), None);
677    /// ```
678    pub fn iter(&self) -> Iter<'_, T> {
679        Iter {
680            entries: self.entries.iter().enumerate(),
681            len: self.len,
682        }
683    }
684
685    /// Return an iterator that allows modifying each value.
686    ///
687    /// This function should generally be **avoided** as it is not efficient.
688    /// Iterators must iterate over every slot in the slab even if it is
689    /// vacant. As such, a slab with a capacity of 1 million but only one
690    /// stored value must still iterate the million slots.
691    ///
692    /// # Examples
693    ///
694    /// ```
695    /// # use slab::*;
696    /// let mut slab = Slab::new();
697    ///
698    /// let key1 = slab.insert(0);
699    /// let key2 = slab.insert(1);
700    ///
701    /// for (key, val) in slab.iter_mut() {
702    ///     if key == key1 {
703    ///         *val += 2;
704    ///     }
705    /// }
706    ///
707    /// assert_eq!(slab[key1], 2);
708    /// assert_eq!(slab[key2], 1);
709    /// ```
710    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
711        IterMut {
712            entries: self.entries.iter_mut().enumerate(),
713            len: self.len,
714        }
715    }
716
717    /// Return a reference to the value associated with the given key.
718    ///
719    /// If the given key is not associated with a value, then `None` is
720    /// returned.
721    ///
722    /// # Examples
723    ///
724    /// ```
725    /// # use slab::*;
726    /// let mut slab = Slab::new();
727    /// let key = slab.insert("hello");
728    ///
729    /// assert_eq!(slab.get(key), Some(&"hello"));
730    /// assert_eq!(slab.get(123), None);
731    /// ```
732    pub fn get(&self, key: usize) -> Option<&T> {
733        match self.entries.get(key) {
734            Some(Entry::Occupied(val)) => Some(val),
735            _ => None,
736        }
737    }
738
739    /// Return a mutable reference to the value associated with the given key.
740    ///
741    /// If the given key is not associated with a value, then `None` is
742    /// returned.
743    ///
744    /// # Examples
745    ///
746    /// ```
747    /// # use slab::*;
748    /// let mut slab = Slab::new();
749    /// let key = slab.insert("hello");
750    ///
751    /// *slab.get_mut(key).unwrap() = "world";
752    ///
753    /// assert_eq!(slab[key], "world");
754    /// assert_eq!(slab.get_mut(123), None);
755    /// ```
756    pub fn get_mut(&mut self, key: usize) -> Option<&mut T> {
757        match self.entries.get_mut(key) {
758            Some(&mut Entry::Occupied(ref mut val)) => Some(val),
759            _ => None,
760        }
761    }
762
763    /// Return two mutable references to the values associated with the two
764    /// given keys simultaneously.
765    ///
766    /// If any one of the given keys is not associated with a value, then `None`
767    /// is returned.
768    ///
769    /// This function can be used to get two mutable references out of one slab,
770    /// so that you can manipulate both of them at the same time, eg. swap them.
771    ///
772    /// # Panics
773    ///
774    /// This function will panic if `key1` and `key2` are the same.
775    ///
776    /// # Examples
777    ///
778    /// ```
779    /// # use slab::*;
780    /// use std::mem;
781    ///
782    /// let mut slab = Slab::new();
783    /// let key1 = slab.insert(1);
784    /// let key2 = slab.insert(2);
785    /// let (value1, value2) = slab.get2_mut(key1, key2).unwrap();
786    /// mem::swap(value1, value2);
787    /// assert_eq!(slab[key1], 2);
788    /// assert_eq!(slab[key2], 1);
789    /// ```
790    pub fn get2_mut(&mut self, key1: usize, key2: usize) -> Option<(&mut T, &mut T)> {
791        assert!(key1 != key2);
792
793        let (entry1, entry2);
794
795        if key1 > key2 {
796            let (slice1, slice2) = self.entries.split_at_mut(key1);
797            entry1 = slice2.get_mut(0);
798            entry2 = slice1.get_mut(key2);
799        } else {
800            let (slice1, slice2) = self.entries.split_at_mut(key2);
801            entry1 = slice1.get_mut(key1);
802            entry2 = slice2.get_mut(0);
803        }
804
805        match (entry1, entry2) {
806            (
807                Some(&mut Entry::Occupied(ref mut val1)),
808                Some(&mut Entry::Occupied(ref mut val2)),
809            ) => Some((val1, val2)),
810            _ => None,
811        }
812    }
813
814    /// Returns mutable references to many indices at once.
815    ///
816    /// Returns [`GetDisjointMutError`] if the indices are out of bounds,
817    /// overlapping, or vacant.
818    pub fn get_disjoint_mut<const N: usize>(
819        &mut self,
820        keys: [usize; N],
821    ) -> Result<[&mut T; N], GetDisjointMutError> {
822        // NB: The optimizer should inline the loops into a sequence
823        // of instructions without additional branching.
824        for (i, &key) in keys.iter().enumerate() {
825            for &prev_key in &keys[..i] {
826                if key == prev_key {
827                    return Err(GetDisjointMutError::OverlappingIndices);
828                }
829            }
830        }
831
832        let entries_ptr = self.entries.as_mut_ptr();
833        let entries_len = self.entries.len();
834
835        let mut res = MaybeUninit::<[&mut T; N]>::uninit();
836        let res_ptr = res.as_mut_ptr() as *mut &mut T;
837
838        for (i, &key) in keys.iter().enumerate() {
839            // `key` won't be greater than `entries_len`.
840            if key >= entries_len {
841                return Err(GetDisjointMutError::IndexOutOfBounds);
842            }
843            // SAFETY: we made sure above that this key is in bounds.
844            match unsafe { &mut *entries_ptr.add(key) } {
845                Entry::Vacant(_) => return Err(GetDisjointMutError::IndexVacant),
846                Entry::Occupied(entry) => {
847                    // SAFETY: `res` and `keys` both have N elements so `i` must be in bounds.
848                    // We checked above that all selected `entry`s are distinct.
849                    unsafe { res_ptr.add(i).write(entry) };
850                }
851            }
852        }
853        // SAFETY: the loop above only terminates successfully if it initialized
854        // all elements of this array.
855        Ok(unsafe { res.assume_init() })
856    }
857
858    /// Return a reference to the value associated with the given key without
859    /// performing bounds checking.
860    ///
861    /// For a safe alternative see [`get`](Slab::get).
862    ///
863    /// This function should be used with care.
864    ///
865    /// # Safety
866    ///
867    /// The key must be within bounds.
868    ///
869    /// # Examples
870    ///
871    /// ```
872    /// # use slab::*;
873    /// let mut slab = Slab::new();
874    /// let key = slab.insert(2);
875    ///
876    /// unsafe {
877    ///     assert_eq!(slab.get_unchecked(key), &2);
878    /// }
879    /// ```
880    pub unsafe fn get_unchecked(&self, key: usize) -> &T {
881        match *self.entries.get_unchecked(key) {
882            Entry::Occupied(ref val) => val,
883            _ => unreachable!(),
884        }
885    }
886
887    /// Return a mutable reference to the value associated with the given key
888    /// without performing bounds checking.
889    ///
890    /// For a safe alternative see [`get_mut`](Slab::get_mut).
891    ///
892    /// This function should be used with care.
893    ///
894    /// # Safety
895    ///
896    /// The key must be within bounds.
897    ///
898    /// # Examples
899    ///
900    /// ```
901    /// # use slab::*;
902    /// let mut slab = Slab::new();
903    /// let key = slab.insert(2);
904    ///
905    /// unsafe {
906    ///     let val = slab.get_unchecked_mut(key);
907    ///     *val = 13;
908    /// }
909    ///
910    /// assert_eq!(slab[key], 13);
911    /// ```
912    pub unsafe fn get_unchecked_mut(&mut self, key: usize) -> &mut T {
913        match *self.entries.get_unchecked_mut(key) {
914            Entry::Occupied(ref mut val) => val,
915            _ => unreachable!(),
916        }
917    }
918
919    /// Return two mutable references to the values associated with the two
920    /// given keys simultaneously without performing bounds checking and safety
921    /// condition checking.
922    ///
923    /// For a safe alternative see [`get2_mut`](Slab::get2_mut).
924    ///
925    /// This function should be used with care.
926    ///
927    /// # Safety
928    ///
929    /// - Both keys must be within bounds.
930    /// - The condition `key1 != key2` must hold.
931    ///
932    /// # Examples
933    ///
934    /// ```
935    /// # use slab::*;
936    /// use std::mem;
937    ///
938    /// let mut slab = Slab::new();
939    /// let key1 = slab.insert(1);
940    /// let key2 = slab.insert(2);
941    /// let (value1, value2) = unsafe { slab.get2_unchecked_mut(key1, key2) };
942    /// mem::swap(value1, value2);
943    /// assert_eq!(slab[key1], 2);
944    /// assert_eq!(slab[key2], 1);
945    /// ```
946    pub unsafe fn get2_unchecked_mut(&mut self, key1: usize, key2: usize) -> (&mut T, &mut T) {
947        debug_assert_ne!(key1, key2);
948        let ptr = self.entries.as_mut_ptr();
949        let ptr1 = ptr.add(key1);
950        let ptr2 = ptr.add(key2);
951        match (&mut *ptr1, &mut *ptr2) {
952            (&mut Entry::Occupied(ref mut val1), &mut Entry::Occupied(ref mut val2)) => {
953                (val1, val2)
954            }
955            _ => unreachable!(),
956        }
957    }
958
959    /// Get the key for an element in the slab.
960    ///
961    /// The reference must point to an element owned by the slab.
962    /// Otherwise this function will panic.
963    /// This is a constant-time operation because the key can be calculated
964    /// from the reference with pointer arithmetic.
965    ///
966    /// # Panics
967    ///
968    /// This function will panic if the reference does not point to an element
969    /// of the slab.
970    ///
971    /// # Examples
972    ///
973    /// ```
974    /// # use slab::*;
975    ///
976    /// let mut slab = Slab::new();
977    /// let key = slab.insert(String::from("foo"));
978    /// let value = &slab[key];
979    /// assert_eq!(slab.key_of(value), key);
980    /// ```
981    ///
982    /// Values are not compared, so passing a reference to a different location
983    /// will result in a panic:
984    ///
985    /// ```should_panic
986    /// # use slab::*;
987    ///
988    /// let mut slab = Slab::new();
989    /// let key = slab.insert(0);
990    /// let bad = &0;
991    /// slab.key_of(bad); // this will panic
992    /// unreachable!();
993    /// ```
994    #[track_caller]
995    pub fn key_of(&self, present_element: &T) -> usize {
996        let element_ptr = present_element as *const T as usize;
997        let base_ptr = self.entries.as_ptr() as usize;
998        // Use wrapping subtraction in case the reference is bad
999        let byte_offset = element_ptr.wrapping_sub(base_ptr);
1000        // The division rounds away any offset of T inside Entry
1001        // The size of Entry<T> is never zero even if T is due to Vacant(usize)
1002        let key = byte_offset / mem::size_of::<Entry<T>>();
1003        // Prevent returning unspecified (but out of bounds) values
1004        if key >= self.entries.len() {
1005            panic!("The reference points to a value outside this slab");
1006        }
1007        // The reference cannot point to a vacant entry, because then it would not be valid
1008        key
1009    }
1010
1011    /// Insert a value in the slab, returning key assigned to the value.
1012    ///
1013    /// The returned key can later be used to retrieve or remove the value using indexed
1014    /// lookup and `remove`. Additional capacity is allocated if needed. See
1015    /// [Capacity and reallocation](index.html#capacity-and-reallocation).
1016    ///
1017    /// # Panics
1018    ///
1019    /// Panics if the new storage in the vector exceeds `isize::MAX` bytes.
1020    ///
1021    /// # Examples
1022    ///
1023    /// ```
1024    /// # use slab::*;
1025    /// let mut slab = Slab::new();
1026    /// let key = slab.insert("hello");
1027    /// assert_eq!(slab[key], "hello");
1028    /// ```
1029    pub fn insert(&mut self, val: T) -> usize {
1030        let key = self.next;
1031
1032        self.insert_at(key, val);
1033
1034        key
1035    }
1036
1037    /// Returns the key of the next vacant entry.
1038    ///
1039    /// This function returns the key of the vacant entry which  will be used
1040    /// for the next insertion. This is equivalent to
1041    /// `slab.vacant_entry().key()`, but it doesn't require mutable access.
1042    ///
1043    /// # Examples
1044    ///
1045    /// ```
1046    /// # use slab::*;
1047    /// let mut slab = Slab::new();
1048    /// assert_eq!(slab.vacant_key(), 0);
1049    ///
1050    /// slab.insert(0);
1051    /// assert_eq!(slab.vacant_key(), 1);
1052    ///
1053    /// slab.insert(1);
1054    /// slab.remove(0);
1055    /// assert_eq!(slab.vacant_key(), 0);
1056    /// ```
1057    pub fn vacant_key(&self) -> usize {
1058        self.next
1059    }
1060
1061    /// Return a handle to a vacant entry allowing for further manipulation.
1062    ///
1063    /// This function is useful when creating values that must contain their
1064    /// slab key. The returned `VacantEntry` reserves a slot in the slab and is
1065    /// able to query the associated key.
1066    ///
1067    /// # Examples
1068    ///
1069    /// ```
1070    /// # use slab::*;
1071    /// let mut slab = Slab::new();
1072    ///
1073    /// let hello = {
1074    ///     let entry = slab.vacant_entry();
1075    ///     let key = entry.key();
1076    ///
1077    ///     entry.insert((key, "hello"));
1078    ///     key
1079    /// };
1080    ///
1081    /// assert_eq!(hello, slab[hello].0);
1082    /// assert_eq!("hello", slab[hello].1);
1083    /// ```
1084    pub fn vacant_entry(&mut self) -> VacantEntry<'_, T> {
1085        VacantEntry {
1086            key: self.next,
1087            slab: self,
1088        }
1089    }
1090
1091    fn insert_at(&mut self, key: usize, val: T) {
1092        self.len += 1;
1093
1094        if key == self.entries.len() {
1095            self.entries.push(Entry::Occupied(val));
1096            self.next = key + 1;
1097        } else {
1098            self.next = match self.entries.get(key) {
1099                Some(&Entry::Vacant(next)) => next,
1100                _ => unreachable!(),
1101            };
1102            self.entries[key] = Entry::Occupied(val);
1103        }
1104    }
1105
1106    /// Tries to remove the value associated with the given key,
1107    /// returning the value if the key existed.
1108    ///
1109    /// The key is then released and may be associated with future stored
1110    /// values.
1111    ///
1112    /// # Examples
1113    ///
1114    /// ```
1115    /// # use slab::*;
1116    /// let mut slab = Slab::new();
1117    ///
1118    /// let hello = slab.insert("hello");
1119    ///
1120    /// assert_eq!(slab.try_remove(hello), Some("hello"));
1121    /// assert!(!slab.contains(hello));
1122    /// ```
1123    pub fn try_remove(&mut self, key: usize) -> Option<T> {
1124        if let Some(entry) = self.entries.get_mut(key) {
1125            if let Entry::Occupied(_) = entry {
1126                // Here we use `std::mem::replace` to move the entry's value to
1127                // the stack and set the entry as vacant in one shot. By doing
1128                // this only when the entry is occupied, the compiler should be
1129                // able to elide copying the bytes to the stack if the value
1130                // turns out to be unused.
1131
1132                let val = match core::mem::replace(entry, Entry::Vacant(self.next)) {
1133                    Entry::Occupied(val) => val, // confirmed occupied above
1134                    _ => unreachable!(),
1135                };
1136
1137                self.len -= 1;
1138                self.next = key;
1139                return val.into();
1140            }
1141        }
1142        None
1143    }
1144
1145    /// Remove and return the value associated with the given key.
1146    ///
1147    /// The key is then released and may be associated with future stored
1148    /// values.
1149    ///
1150    /// # Panics
1151    ///
1152    /// Panics if `key` is not associated with a value.
1153    ///
1154    /// # Examples
1155    ///
1156    /// ```
1157    /// # use slab::*;
1158    /// let mut slab = Slab::new();
1159    ///
1160    /// let hello = slab.insert("hello");
1161    ///
1162    /// assert_eq!(slab.remove(hello), "hello");
1163    /// assert!(!slab.contains(hello));
1164    /// ```
1165    #[track_caller]
1166    pub fn remove(&mut self, key: usize) -> T {
1167        self.try_remove(key).expect("invalid key")
1168    }
1169
1170    /// Return `true` if a value is associated with the given key.
1171    ///
1172    /// # Examples
1173    ///
1174    /// ```
1175    /// # use slab::*;
1176    /// let mut slab = Slab::new();
1177    ///
1178    /// let hello = slab.insert("hello");
1179    /// assert!(slab.contains(hello));
1180    ///
1181    /// slab.remove(hello);
1182    ///
1183    /// assert!(!slab.contains(hello));
1184    /// ```
1185    pub fn contains(&self, key: usize) -> bool {
1186        matches!(self.entries.get(key), Some(&Entry::Occupied(_)))
1187    }
1188
1189    /// Retain only the elements specified by the predicate.
1190    ///
1191    /// In other words, remove all elements `e` such that `f(usize, &mut e)`
1192    /// returns false. This method operates in place and preserves the key
1193    /// associated with the retained values.
1194    ///
1195    /// # Examples
1196    ///
1197    /// ```
1198    /// # use slab::*;
1199    /// let mut slab = Slab::new();
1200    ///
1201    /// let k1 = slab.insert(0);
1202    /// let k2 = slab.insert(1);
1203    /// let k3 = slab.insert(2);
1204    ///
1205    /// slab.retain(|key, val| key == k1 || *val == 1);
1206    ///
1207    /// assert!(slab.contains(k1));
1208    /// assert!(slab.contains(k2));
1209    /// assert!(!slab.contains(k3));
1210    ///
1211    /// assert_eq!(2, slab.len());
1212    /// ```
1213    pub fn retain<F>(&mut self, mut f: F)
1214    where
1215        F: FnMut(usize, &mut T) -> bool,
1216    {
1217        for i in 0..self.entries.len() {
1218            let keep = match self.entries[i] {
1219                Entry::Occupied(ref mut v) => f(i, v),
1220                _ => true,
1221            };
1222
1223            if !keep {
1224                self.remove(i);
1225            }
1226        }
1227    }
1228
1229    /// Return a draining iterator that removes all elements from the slab and
1230    /// yields the removed items.
1231    ///
1232    /// Note: Elements are removed even if the iterator is only partially
1233    /// consumed or not consumed at all.
1234    ///
1235    /// # Examples
1236    ///
1237    /// ```
1238    /// # use slab::*;
1239    /// let mut slab = Slab::new();
1240    ///
1241    /// let _ = slab.insert(0);
1242    /// let _ = slab.insert(1);
1243    /// let _ = slab.insert(2);
1244    ///
1245    /// {
1246    ///     let mut drain = slab.drain();
1247    ///
1248    ///     assert_eq!(Some(0), drain.next());
1249    ///     assert_eq!(Some(1), drain.next());
1250    ///     assert_eq!(Some(2), drain.next());
1251    ///     assert_eq!(None, drain.next());
1252    /// }
1253    ///
1254    /// assert!(slab.is_empty());
1255    /// ```
1256    pub fn drain(&mut self) -> Drain<'_, T> {
1257        let old_len = self.len;
1258        self.len = 0;
1259        self.next = 0;
1260        Drain {
1261            inner: self.entries.drain(..),
1262            len: old_len,
1263        }
1264    }
1265}
1266
1267impl<T> ops::Index<usize> for Slab<T> {
1268    type Output = T;
1269
1270    #[track_caller]
1271    fn index(&self, key: usize) -> &T {
1272        match self.entries.get(key) {
1273            Some(Entry::Occupied(v)) => v,
1274            _ => panic!("invalid key"),
1275        }
1276    }
1277}
1278
1279impl<T> ops::IndexMut<usize> for Slab<T> {
1280    #[track_caller]
1281    fn index_mut(&mut self, key: usize) -> &mut T {
1282        match self.entries.get_mut(key) {
1283            Some(&mut Entry::Occupied(ref mut v)) => v,
1284            _ => panic!("invalid key"),
1285        }
1286    }
1287}
1288
1289impl<T> IntoIterator for Slab<T> {
1290    type Item = (usize, T);
1291    type IntoIter = IntoIter<T>;
1292
1293    fn into_iter(self) -> IntoIter<T> {
1294        IntoIter {
1295            entries: self.entries.into_iter().enumerate(),
1296            len: self.len,
1297        }
1298    }
1299}
1300
1301impl<'a, T> IntoIterator for &'a Slab<T> {
1302    type Item = (usize, &'a T);
1303    type IntoIter = Iter<'a, T>;
1304
1305    fn into_iter(self) -> Iter<'a, T> {
1306        self.iter()
1307    }
1308}
1309
1310impl<'a, T> IntoIterator for &'a mut Slab<T> {
1311    type Item = (usize, &'a mut T);
1312    type IntoIter = IterMut<'a, T>;
1313
1314    fn into_iter(self) -> IterMut<'a, T> {
1315        self.iter_mut()
1316    }
1317}
1318
1319/// Create a slab from an iterator of key-value pairs.
1320///
1321/// If the iterator produces duplicate keys, the previous value is replaced with the later one.
1322/// The keys does not need to be sorted beforehand, and this function always
1323/// takes O(n) time.
1324/// Note that the returned slab will use space proportional to the largest key,
1325/// so don't use `Slab` with untrusted keys.
1326///
1327/// # Examples
1328///
1329/// ```
1330/// # use slab::*;
1331///
1332/// let vec = vec![(2,'a'), (6,'b'), (7,'c')];
1333/// let slab = vec.into_iter().collect::<Slab<char>>();
1334/// assert_eq!(slab.len(), 3);
1335/// assert!(slab.capacity() >= 8);
1336/// assert_eq!(slab[2], 'a');
1337/// ```
1338///
1339/// With duplicate and unsorted keys:
1340///
1341/// ```
1342/// # use slab::*;
1343///
1344/// let vec = vec![(20,'a'), (10,'b'), (11,'c'), (10,'d')];
1345/// let slab = vec.into_iter().collect::<Slab<char>>();
1346/// assert_eq!(slab.len(), 3);
1347/// assert_eq!(slab[10], 'd');
1348/// ```
1349impl<T> FromIterator<(usize, T)> for Slab<T> {
1350    fn from_iter<I>(iterable: I) -> Self
1351    where
1352        I: IntoIterator<Item = (usize, T)>,
1353    {
1354        let iterator = iterable.into_iter();
1355        let mut builder = builder::Builder::with_capacity(iterator.size_hint().0);
1356
1357        for (key, value) in iterator {
1358            builder.pair(key, value);
1359        }
1360        builder.build()
1361    }
1362}
1363
1364impl<T> fmt::Debug for Slab<T>
1365where
1366    T: fmt::Debug,
1367{
1368    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1369        if fmt.alternate() {
1370            fmt.debug_map().entries(self.iter()).finish()
1371        } else {
1372            fmt.debug_struct("Slab")
1373                .field("len", &self.len)
1374                .field("cap", &self.capacity())
1375                .finish()
1376        }
1377    }
1378}
1379
1380impl<T> fmt::Debug for IntoIter<T>
1381where
1382    T: fmt::Debug,
1383{
1384    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1385        fmt.debug_struct("IntoIter")
1386            .field("remaining", &self.len)
1387            .finish()
1388    }
1389}
1390
1391impl<T> fmt::Debug for Iter<'_, T>
1392where
1393    T: fmt::Debug,
1394{
1395    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1396        fmt.debug_struct("Iter")
1397            .field("remaining", &self.len)
1398            .finish()
1399    }
1400}
1401
1402impl<T> fmt::Debug for IterMut<'_, T>
1403where
1404    T: fmt::Debug,
1405{
1406    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1407        fmt.debug_struct("IterMut")
1408            .field("remaining", &self.len)
1409            .finish()
1410    }
1411}
1412
1413impl<T> fmt::Debug for Drain<'_, T> {
1414    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1415        fmt.debug_struct("Drain").finish()
1416    }
1417}
1418
1419// ===== VacantEntry =====
1420
1421impl<'a, T> VacantEntry<'a, T> {
1422    /// Insert a value in the entry, returning a mutable reference to the value.
1423    ///
1424    /// To get the key associated with the value, use `key` prior to calling
1425    /// `insert`.
1426    ///
1427    /// # Examples
1428    ///
1429    /// ```
1430    /// # use slab::*;
1431    /// let mut slab = Slab::new();
1432    ///
1433    /// let hello = {
1434    ///     let entry = slab.vacant_entry();
1435    ///     let key = entry.key();
1436    ///
1437    ///     entry.insert((key, "hello"));
1438    ///     key
1439    /// };
1440    ///
1441    /// assert_eq!(hello, slab[hello].0);
1442    /// assert_eq!("hello", slab[hello].1);
1443    /// ```
1444    pub fn insert(self, val: T) -> &'a mut T {
1445        self.slab.insert_at(self.key, val);
1446
1447        match self.slab.entries.get_mut(self.key) {
1448            Some(&mut Entry::Occupied(ref mut v)) => v,
1449            _ => unreachable!(),
1450        }
1451    }
1452
1453    /// Return the key associated with this entry.
1454    ///
1455    /// A value stored in this entry will be associated with this key.
1456    ///
1457    /// # Examples
1458    ///
1459    /// ```
1460    /// # use slab::*;
1461    /// let mut slab = Slab::new();
1462    ///
1463    /// let hello = {
1464    ///     let entry = slab.vacant_entry();
1465    ///     let key = entry.key();
1466    ///
1467    ///     entry.insert((key, "hello"));
1468    ///     key
1469    /// };
1470    ///
1471    /// assert_eq!(hello, slab[hello].0);
1472    /// assert_eq!("hello", slab[hello].1);
1473    /// ```
1474    pub fn key(&self) -> usize {
1475        self.key
1476    }
1477}
1478
1479// ===== IntoIter =====
1480
1481impl<T> Iterator for IntoIter<T> {
1482    type Item = (usize, T);
1483
1484    fn next(&mut self) -> Option<Self::Item> {
1485        for (key, entry) in &mut self.entries {
1486            if let Entry::Occupied(v) = entry {
1487                self.len -= 1;
1488                return Some((key, v));
1489            }
1490        }
1491
1492        debug_assert_eq!(self.len, 0);
1493        None
1494    }
1495
1496    fn size_hint(&self) -> (usize, Option<usize>) {
1497        (self.len, Some(self.len))
1498    }
1499}
1500
1501impl<T> DoubleEndedIterator for IntoIter<T> {
1502    fn next_back(&mut self) -> Option<Self::Item> {
1503        while let Some((key, entry)) = self.entries.next_back() {
1504            if let Entry::Occupied(v) = entry {
1505                self.len -= 1;
1506                return Some((key, v));
1507            }
1508        }
1509
1510        debug_assert_eq!(self.len, 0);
1511        None
1512    }
1513}
1514
1515impl<T> ExactSizeIterator for IntoIter<T> {
1516    fn len(&self) -> usize {
1517        self.len
1518    }
1519}
1520
1521impl<T> FusedIterator for IntoIter<T> {}
1522
1523// ===== Iter =====
1524
1525impl<'a, T> Iterator for Iter<'a, T> {
1526    type Item = (usize, &'a T);
1527
1528    fn next(&mut self) -> Option<Self::Item> {
1529        for (key, entry) in &mut self.entries {
1530            if let Entry::Occupied(ref v) = *entry {
1531                self.len -= 1;
1532                return Some((key, v));
1533            }
1534        }
1535
1536        debug_assert_eq!(self.len, 0);
1537        None
1538    }
1539
1540    fn size_hint(&self) -> (usize, Option<usize>) {
1541        (self.len, Some(self.len))
1542    }
1543}
1544
1545impl<T> DoubleEndedIterator for Iter<'_, T> {
1546    fn next_back(&mut self) -> Option<Self::Item> {
1547        while let Some((key, entry)) = self.entries.next_back() {
1548            if let Entry::Occupied(ref v) = *entry {
1549                self.len -= 1;
1550                return Some((key, v));
1551            }
1552        }
1553
1554        debug_assert_eq!(self.len, 0);
1555        None
1556    }
1557}
1558
1559impl<T> ExactSizeIterator for Iter<'_, T> {
1560    fn len(&self) -> usize {
1561        self.len
1562    }
1563}
1564
1565impl<T> FusedIterator for Iter<'_, T> {}
1566
1567// ===== IterMut =====
1568
1569impl<'a, T> Iterator for IterMut<'a, T> {
1570    type Item = (usize, &'a mut T);
1571
1572    fn next(&mut self) -> Option<Self::Item> {
1573        for (key, entry) in &mut self.entries {
1574            if let Entry::Occupied(ref mut v) = *entry {
1575                self.len -= 1;
1576                return Some((key, v));
1577            }
1578        }
1579
1580        debug_assert_eq!(self.len, 0);
1581        None
1582    }
1583
1584    fn size_hint(&self) -> (usize, Option<usize>) {
1585        (self.len, Some(self.len))
1586    }
1587}
1588
1589impl<T> DoubleEndedIterator for IterMut<'_, T> {
1590    fn next_back(&mut self) -> Option<Self::Item> {
1591        while let Some((key, entry)) = self.entries.next_back() {
1592            if let Entry::Occupied(ref mut v) = *entry {
1593                self.len -= 1;
1594                return Some((key, v));
1595            }
1596        }
1597
1598        debug_assert_eq!(self.len, 0);
1599        None
1600    }
1601}
1602
1603impl<T> ExactSizeIterator for IterMut<'_, T> {
1604    fn len(&self) -> usize {
1605        self.len
1606    }
1607}
1608
1609impl<T> FusedIterator for IterMut<'_, T> {}
1610
1611// ===== Drain =====
1612
1613impl<T> Iterator for Drain<'_, T> {
1614    type Item = T;
1615
1616    fn next(&mut self) -> Option<Self::Item> {
1617        for entry in &mut self.inner {
1618            if let Entry::Occupied(v) = entry {
1619                self.len -= 1;
1620                return Some(v);
1621            }
1622        }
1623
1624        debug_assert_eq!(self.len, 0);
1625        None
1626    }
1627
1628    fn size_hint(&self) -> (usize, Option<usize>) {
1629        (self.len, Some(self.len))
1630    }
1631}
1632
1633impl<T> DoubleEndedIterator for Drain<'_, T> {
1634    fn next_back(&mut self) -> Option<Self::Item> {
1635        while let Some(entry) = self.inner.next_back() {
1636            if let Entry::Occupied(v) = entry {
1637                self.len -= 1;
1638                return Some(v);
1639            }
1640        }
1641
1642        debug_assert_eq!(self.len, 0);
1643        None
1644    }
1645}
1646
1647impl<T> ExactSizeIterator for Drain<'_, T> {
1648    fn len(&self) -> usize {
1649        self.len
1650    }
1651}
1652
1653impl<T> FusedIterator for Drain<'_, T> {}