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