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_len = self.entries.len();
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 // `key` won't be greater than `entries_len`.
833 if key >= entries_len {
834 return Err(GetDisjointMutError::IndexOutOfBounds);
835 }
836 // SAFETY: we made sure above that this key is in bounds.
837 match unsafe { &mut *entries_ptr.add(key) } {
838 Entry::Vacant(_) => return Err(GetDisjointMutError::IndexVacant),
839 Entry::Occupied(entry) => {
840 // SAFETY: `res` and `keys` both have N elements so `i` must be in bounds.
841 // We checked above that all selected `entry`s are distinct.
842 unsafe { res_ptr.add(i).write(entry) };
843 }
844 }
845 }
846 // SAFETY: the loop above only terminates successfully if it initialized
847 // all elements of this array.
848 Ok(unsafe { res.assume_init() })
849 }
850
851 /// Return a reference to the value associated with the given key without
852 /// performing bounds checking.
853 ///
854 /// For a safe alternative see [`get`](Slab::get).
855 ///
856 /// This function should be used with care.
857 ///
858 /// # Safety
859 ///
860 /// The key must be within bounds.
861 ///
862 /// # Examples
863 ///
864 /// ```
865 /// # use slab::*;
866 /// let mut slab = Slab::new();
867 /// let key = slab.insert(2);
868 ///
869 /// unsafe {
870 /// assert_eq!(slab.get_unchecked(key), &2);
871 /// }
872 /// ```
873 pub unsafe fn get_unchecked(&self, key: usize) -> &T {
874 match *self.entries.get_unchecked(key) {
875 Entry::Occupied(ref val) => val,
876 _ => unreachable!(),
877 }
878 }
879
880 /// Return a mutable reference to the value associated with the given key
881 /// without performing bounds checking.
882 ///
883 /// For a safe alternative see [`get_mut`](Slab::get_mut).
884 ///
885 /// This function should be used with care.
886 ///
887 /// # Safety
888 ///
889 /// The key must be within bounds.
890 ///
891 /// # Examples
892 ///
893 /// ```
894 /// # use slab::*;
895 /// let mut slab = Slab::new();
896 /// let key = slab.insert(2);
897 ///
898 /// unsafe {
899 /// let val = slab.get_unchecked_mut(key);
900 /// *val = 13;
901 /// }
902 ///
903 /// assert_eq!(slab[key], 13);
904 /// ```
905 pub unsafe fn get_unchecked_mut(&mut self, key: usize) -> &mut T {
906 match *self.entries.get_unchecked_mut(key) {
907 Entry::Occupied(ref mut val) => val,
908 _ => unreachable!(),
909 }
910 }
911
912 /// Return two mutable references to the values associated with the two
913 /// given keys simultaneously without performing bounds checking and safety
914 /// condition checking.
915 ///
916 /// For a safe alternative see [`get2_mut`](Slab::get2_mut).
917 ///
918 /// This function should be used with care.
919 ///
920 /// # Safety
921 ///
922 /// - Both keys must be within bounds.
923 /// - The condition `key1 != key2` must hold.
924 ///
925 /// # Examples
926 ///
927 /// ```
928 /// # use slab::*;
929 /// use std::mem;
930 ///
931 /// let mut slab = Slab::new();
932 /// let key1 = slab.insert(1);
933 /// let key2 = slab.insert(2);
934 /// let (value1, value2) = unsafe { slab.get2_unchecked_mut(key1, key2) };
935 /// mem::swap(value1, value2);
936 /// assert_eq!(slab[key1], 2);
937 /// assert_eq!(slab[key2], 1);
938 /// ```
939 pub unsafe fn get2_unchecked_mut(&mut self, key1: usize, key2: usize) -> (&mut T, &mut T) {
940 debug_assert_ne!(key1, key2);
941 let ptr = self.entries.as_mut_ptr();
942 let ptr1 = ptr.add(key1);
943 let ptr2 = ptr.add(key2);
944 match (&mut *ptr1, &mut *ptr2) {
945 (&mut Entry::Occupied(ref mut val1), &mut Entry::Occupied(ref mut val2)) => {
946 (val1, val2)
947 }
948 _ => unreachable!(),
949 }
950 }
951
952 /// Get the key for an element in the slab.
953 ///
954 /// The reference must point to an element owned by the slab.
955 /// Otherwise this function will panic.
956 /// This is a constant-time operation because the key can be calculated
957 /// from the reference with pointer arithmetic.
958 ///
959 /// # Panics
960 ///
961 /// This function will panic if the reference does not point to an element
962 /// of the slab.
963 ///
964 /// # Examples
965 ///
966 /// ```
967 /// # use slab::*;
968 ///
969 /// let mut slab = Slab::new();
970 /// let key = slab.insert(String::from("foo"));
971 /// let value = &slab[key];
972 /// assert_eq!(slab.key_of(value), key);
973 /// ```
974 ///
975 /// Values are not compared, so passing a reference to a different location
976 /// will result in a panic:
977 ///
978 /// ```should_panic
979 /// # use slab::*;
980 ///
981 /// let mut slab = Slab::new();
982 /// let key = slab.insert(0);
983 /// let bad = &0;
984 /// slab.key_of(bad); // this will panic
985 /// unreachable!();
986 /// ```
987 #[track_caller]
988 pub fn key_of(&self, present_element: &T) -> usize {
989 let element_ptr = present_element as *const T as usize;
990 let base_ptr = self.entries.as_ptr() as usize;
991 // Use wrapping subtraction in case the reference is bad
992 let byte_offset = element_ptr.wrapping_sub(base_ptr);
993 // The division rounds away any offset of T inside Entry
994 // The size of Entry<T> is never zero even if T is due to Vacant(usize)
995 let key = byte_offset / mem::size_of::<Entry<T>>();
996 // Prevent returning unspecified (but out of bounds) values
997 if key >= self.entries.len() {
998 panic!("The reference points to a value outside this slab");
999 }
1000 // The reference cannot point to a vacant entry, because then it would not be valid
1001 key
1002 }
1003
1004 /// Insert a value in the slab, returning key assigned to the value.
1005 ///
1006 /// The returned key can later be used to retrieve or remove the value using indexed
1007 /// lookup and `remove`. Additional capacity is allocated if needed. See
1008 /// [Capacity and reallocation](index.html#capacity-and-reallocation).
1009 ///
1010 /// # Panics
1011 ///
1012 /// Panics if the new storage in the vector exceeds `isize::MAX` bytes.
1013 ///
1014 /// # Examples
1015 ///
1016 /// ```
1017 /// # use slab::*;
1018 /// let mut slab = Slab::new();
1019 /// let key = slab.insert("hello");
1020 /// assert_eq!(slab[key], "hello");
1021 /// ```
1022 pub fn insert(&mut self, val: T) -> usize {
1023 let key = self.next;
1024
1025 self.insert_at(key, val);
1026
1027 key
1028 }
1029
1030 /// Returns the key of the next vacant entry.
1031 ///
1032 /// This function returns the key of the vacant entry which will be used
1033 /// for the next insertion. This is equivalent to
1034 /// `slab.vacant_entry().key()`, but it doesn't require mutable access.
1035 ///
1036 /// # Examples
1037 ///
1038 /// ```
1039 /// # use slab::*;
1040 /// let mut slab = Slab::new();
1041 /// assert_eq!(slab.vacant_key(), 0);
1042 ///
1043 /// slab.insert(0);
1044 /// assert_eq!(slab.vacant_key(), 1);
1045 ///
1046 /// slab.insert(1);
1047 /// slab.remove(0);
1048 /// assert_eq!(slab.vacant_key(), 0);
1049 /// ```
1050 pub fn vacant_key(&self) -> usize {
1051 self.next
1052 }
1053
1054 /// Return a handle to a vacant entry allowing for further manipulation.
1055 ///
1056 /// This function is useful when creating values that must contain their
1057 /// slab key. The returned `VacantEntry` reserves a slot in the slab and is
1058 /// able to query the associated key.
1059 ///
1060 /// # Examples
1061 ///
1062 /// ```
1063 /// # use slab::*;
1064 /// let mut slab = Slab::new();
1065 ///
1066 /// let hello = {
1067 /// let entry = slab.vacant_entry();
1068 /// let key = entry.key();
1069 ///
1070 /// entry.insert((key, "hello"));
1071 /// key
1072 /// };
1073 ///
1074 /// assert_eq!(hello, slab[hello].0);
1075 /// assert_eq!("hello", slab[hello].1);
1076 /// ```
1077 pub fn vacant_entry(&mut self) -> VacantEntry<'_, T> {
1078 VacantEntry {
1079 key: self.next,
1080 slab: self,
1081 }
1082 }
1083
1084 fn insert_at(&mut self, key: usize, val: T) {
1085 self.len += 1;
1086
1087 if key == self.entries.len() {
1088 self.entries.push(Entry::Occupied(val));
1089 self.next = key + 1;
1090 } else {
1091 self.next = match self.entries.get(key) {
1092 Some(&Entry::Vacant(next)) => next,
1093 _ => unreachable!(),
1094 };
1095 self.entries[key] = Entry::Occupied(val);
1096 }
1097 }
1098
1099 /// Tries to remove the value associated with the given key,
1100 /// returning the value if the key existed.
1101 ///
1102 /// The key is then released and may be associated with future stored
1103 /// values.
1104 ///
1105 /// # Examples
1106 ///
1107 /// ```
1108 /// # use slab::*;
1109 /// let mut slab = Slab::new();
1110 ///
1111 /// let hello = slab.insert("hello");
1112 ///
1113 /// assert_eq!(slab.try_remove(hello), Some("hello"));
1114 /// assert!(!slab.contains(hello));
1115 /// ```
1116 pub fn try_remove(&mut self, key: usize) -> Option<T> {
1117 if let Some(entry) = self.entries.get_mut(key) {
1118 // Swap the entry at the provided value
1119 let prev = mem::replace(entry, Entry::Vacant(self.next));
1120
1121 match prev {
1122 Entry::Occupied(val) => {
1123 self.len -= 1;
1124 self.next = key;
1125 return val.into();
1126 }
1127 _ => {
1128 // Woops, the entry is actually vacant, restore the state
1129 *entry = prev;
1130 }
1131 }
1132 }
1133 None
1134 }
1135
1136 /// Remove and return the value associated with the given key.
1137 ///
1138 /// The key is then released and may be associated with future stored
1139 /// values.
1140 ///
1141 /// # Panics
1142 ///
1143 /// Panics if `key` is not associated with a value.
1144 ///
1145 /// # Examples
1146 ///
1147 /// ```
1148 /// # use slab::*;
1149 /// let mut slab = Slab::new();
1150 ///
1151 /// let hello = slab.insert("hello");
1152 ///
1153 /// assert_eq!(slab.remove(hello), "hello");
1154 /// assert!(!slab.contains(hello));
1155 /// ```
1156 #[track_caller]
1157 pub fn remove(&mut self, key: usize) -> T {
1158 self.try_remove(key).expect("invalid key")
1159 }
1160
1161 /// Return `true` if a value is associated with the given key.
1162 ///
1163 /// # Examples
1164 ///
1165 /// ```
1166 /// # use slab::*;
1167 /// let mut slab = Slab::new();
1168 ///
1169 /// let hello = slab.insert("hello");
1170 /// assert!(slab.contains(hello));
1171 ///
1172 /// slab.remove(hello);
1173 ///
1174 /// assert!(!slab.contains(hello));
1175 /// ```
1176 pub fn contains(&self, key: usize) -> bool {
1177 matches!(self.entries.get(key), Some(&Entry::Occupied(_)))
1178 }
1179
1180 /// Retain only the elements specified by the predicate.
1181 ///
1182 /// In other words, remove all elements `e` such that `f(usize, &mut e)`
1183 /// returns false. This method operates in place and preserves the key
1184 /// associated with the retained values.
1185 ///
1186 /// # Examples
1187 ///
1188 /// ```
1189 /// # use slab::*;
1190 /// let mut slab = Slab::new();
1191 ///
1192 /// let k1 = slab.insert(0);
1193 /// let k2 = slab.insert(1);
1194 /// let k3 = slab.insert(2);
1195 ///
1196 /// slab.retain(|key, val| key == k1 || *val == 1);
1197 ///
1198 /// assert!(slab.contains(k1));
1199 /// assert!(slab.contains(k2));
1200 /// assert!(!slab.contains(k3));
1201 ///
1202 /// assert_eq!(2, slab.len());
1203 /// ```
1204 pub fn retain<F>(&mut self, mut f: F)
1205 where
1206 F: FnMut(usize, &mut T) -> bool,
1207 {
1208 for i in 0..self.entries.len() {
1209 let keep = match self.entries[i] {
1210 Entry::Occupied(ref mut v) => f(i, v),
1211 _ => true,
1212 };
1213
1214 if !keep {
1215 self.remove(i);
1216 }
1217 }
1218 }
1219
1220 /// Return a draining iterator that removes all elements from the slab and
1221 /// yields the removed items.
1222 ///
1223 /// Note: Elements are removed even if the iterator is only partially
1224 /// consumed or not consumed at all.
1225 ///
1226 /// # Examples
1227 ///
1228 /// ```
1229 /// # use slab::*;
1230 /// let mut slab = Slab::new();
1231 ///
1232 /// let _ = slab.insert(0);
1233 /// let _ = slab.insert(1);
1234 /// let _ = slab.insert(2);
1235 ///
1236 /// {
1237 /// let mut drain = slab.drain();
1238 ///
1239 /// assert_eq!(Some(0), drain.next());
1240 /// assert_eq!(Some(1), drain.next());
1241 /// assert_eq!(Some(2), drain.next());
1242 /// assert_eq!(None, drain.next());
1243 /// }
1244 ///
1245 /// assert!(slab.is_empty());
1246 /// ```
1247 pub fn drain(&mut self) -> Drain<'_, T> {
1248 let old_len = self.len;
1249 self.len = 0;
1250 self.next = 0;
1251 Drain {
1252 inner: self.entries.drain(..),
1253 len: old_len,
1254 }
1255 }
1256}
1257
1258impl<T> ops::Index<usize> for Slab<T> {
1259 type Output = T;
1260
1261 #[track_caller]
1262 fn index(&self, key: usize) -> &T {
1263 match self.entries.get(key) {
1264 Some(Entry::Occupied(v)) => v,
1265 _ => panic!("invalid key"),
1266 }
1267 }
1268}
1269
1270impl<T> ops::IndexMut<usize> for Slab<T> {
1271 #[track_caller]
1272 fn index_mut(&mut self, key: usize) -> &mut T {
1273 match self.entries.get_mut(key) {
1274 Some(&mut Entry::Occupied(ref mut v)) => v,
1275 _ => panic!("invalid key"),
1276 }
1277 }
1278}
1279
1280impl<T> IntoIterator for Slab<T> {
1281 type Item = (usize, T);
1282 type IntoIter = IntoIter<T>;
1283
1284 fn into_iter(self) -> IntoIter<T> {
1285 IntoIter {
1286 entries: self.entries.into_iter().enumerate(),
1287 len: self.len,
1288 }
1289 }
1290}
1291
1292impl<'a, T> IntoIterator for &'a Slab<T> {
1293 type Item = (usize, &'a T);
1294 type IntoIter = Iter<'a, T>;
1295
1296 fn into_iter(self) -> Iter<'a, T> {
1297 self.iter()
1298 }
1299}
1300
1301impl<'a, T> IntoIterator for &'a mut Slab<T> {
1302 type Item = (usize, &'a mut T);
1303 type IntoIter = IterMut<'a, T>;
1304
1305 fn into_iter(self) -> IterMut<'a, T> {
1306 self.iter_mut()
1307 }
1308}
1309
1310/// Create a slab from an iterator of key-value pairs.
1311///
1312/// If the iterator produces duplicate keys, the previous value is replaced with the later one.
1313/// The keys does not need to be sorted beforehand, and this function always
1314/// takes O(n) time.
1315/// Note that the returned slab will use space proportional to the largest key,
1316/// so don't use `Slab` with untrusted keys.
1317///
1318/// # Examples
1319///
1320/// ```
1321/// # use slab::*;
1322///
1323/// let vec = vec![(2,'a'), (6,'b'), (7,'c')];
1324/// let slab = vec.into_iter().collect::<Slab<char>>();
1325/// assert_eq!(slab.len(), 3);
1326/// assert!(slab.capacity() >= 8);
1327/// assert_eq!(slab[2], 'a');
1328/// ```
1329///
1330/// With duplicate and unsorted keys:
1331///
1332/// ```
1333/// # use slab::*;
1334///
1335/// let vec = vec![(20,'a'), (10,'b'), (11,'c'), (10,'d')];
1336/// let slab = vec.into_iter().collect::<Slab<char>>();
1337/// assert_eq!(slab.len(), 3);
1338/// assert_eq!(slab[10], 'd');
1339/// ```
1340impl<T> FromIterator<(usize, T)> for Slab<T> {
1341 fn from_iter<I>(iterable: I) -> Self
1342 where
1343 I: IntoIterator<Item = (usize, T)>,
1344 {
1345 let iterator = iterable.into_iter();
1346 let mut builder = builder::Builder::with_capacity(iterator.size_hint().0);
1347
1348 for (key, value) in iterator {
1349 builder.pair(key, value)
1350 }
1351 builder.build()
1352 }
1353}
1354
1355impl<T> fmt::Debug for Slab<T>
1356where
1357 T: fmt::Debug,
1358{
1359 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1360 if fmt.alternate() {
1361 fmt.debug_map().entries(self.iter()).finish()
1362 } else {
1363 fmt.debug_struct("Slab")
1364 .field("len", &self.len)
1365 .field("cap", &self.capacity())
1366 .finish()
1367 }
1368 }
1369}
1370
1371impl<T> fmt::Debug for IntoIter<T>
1372where
1373 T: fmt::Debug,
1374{
1375 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1376 fmt.debug_struct("IntoIter")
1377 .field("remaining", &self.len)
1378 .finish()
1379 }
1380}
1381
1382impl<T> fmt::Debug for Iter<'_, T>
1383where
1384 T: fmt::Debug,
1385{
1386 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1387 fmt.debug_struct("Iter")
1388 .field("remaining", &self.len)
1389 .finish()
1390 }
1391}
1392
1393impl<T> fmt::Debug for IterMut<'_, T>
1394where
1395 T: fmt::Debug,
1396{
1397 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1398 fmt.debug_struct("IterMut")
1399 .field("remaining", &self.len)
1400 .finish()
1401 }
1402}
1403
1404impl<T> fmt::Debug for Drain<'_, T> {
1405 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1406 fmt.debug_struct("Drain").finish()
1407 }
1408}
1409
1410// ===== VacantEntry =====
1411
1412impl<'a, T> VacantEntry<'a, T> {
1413 /// Insert a value in the entry, returning a mutable reference to the value.
1414 ///
1415 /// To get the key associated with the value, use `key` prior to calling
1416 /// `insert`.
1417 ///
1418 /// # Examples
1419 ///
1420 /// ```
1421 /// # use slab::*;
1422 /// let mut slab = Slab::new();
1423 ///
1424 /// let hello = {
1425 /// let entry = slab.vacant_entry();
1426 /// let key = entry.key();
1427 ///
1428 /// entry.insert((key, "hello"));
1429 /// key
1430 /// };
1431 ///
1432 /// assert_eq!(hello, slab[hello].0);
1433 /// assert_eq!("hello", slab[hello].1);
1434 /// ```
1435 pub fn insert(self, val: T) -> &'a mut T {
1436 self.slab.insert_at(self.key, val);
1437
1438 match self.slab.entries.get_mut(self.key) {
1439 Some(&mut Entry::Occupied(ref mut v)) => v,
1440 _ => unreachable!(),
1441 }
1442 }
1443
1444 /// Return the key associated with this entry.
1445 ///
1446 /// A value stored in this entry will be associated with this key.
1447 ///
1448 /// # Examples
1449 ///
1450 /// ```
1451 /// # use slab::*;
1452 /// let mut slab = Slab::new();
1453 ///
1454 /// let hello = {
1455 /// let entry = slab.vacant_entry();
1456 /// let key = entry.key();
1457 ///
1458 /// entry.insert((key, "hello"));
1459 /// key
1460 /// };
1461 ///
1462 /// assert_eq!(hello, slab[hello].0);
1463 /// assert_eq!("hello", slab[hello].1);
1464 /// ```
1465 pub fn key(&self) -> usize {
1466 self.key
1467 }
1468}
1469
1470// ===== IntoIter =====
1471
1472impl<T> Iterator for IntoIter<T> {
1473 type Item = (usize, T);
1474
1475 fn next(&mut self) -> Option<Self::Item> {
1476 for (key, entry) in &mut self.entries {
1477 if let Entry::Occupied(v) = entry {
1478 self.len -= 1;
1479 return Some((key, v));
1480 }
1481 }
1482
1483 debug_assert_eq!(self.len, 0);
1484 None
1485 }
1486
1487 fn size_hint(&self) -> (usize, Option<usize>) {
1488 (self.len, Some(self.len))
1489 }
1490}
1491
1492impl<T> DoubleEndedIterator for IntoIter<T> {
1493 fn next_back(&mut self) -> Option<Self::Item> {
1494 while let Some((key, entry)) = self.entries.next_back() {
1495 if let Entry::Occupied(v) = entry {
1496 self.len -= 1;
1497 return Some((key, v));
1498 }
1499 }
1500
1501 debug_assert_eq!(self.len, 0);
1502 None
1503 }
1504}
1505
1506impl<T> ExactSizeIterator for IntoIter<T> {
1507 fn len(&self) -> usize {
1508 self.len
1509 }
1510}
1511
1512impl<T> FusedIterator for IntoIter<T> {}
1513
1514// ===== Iter =====
1515
1516impl<'a, T> Iterator for Iter<'a, T> {
1517 type Item = (usize, &'a T);
1518
1519 fn next(&mut self) -> Option<Self::Item> {
1520 for (key, entry) in &mut self.entries {
1521 if let Entry::Occupied(ref v) = *entry {
1522 self.len -= 1;
1523 return Some((key, v));
1524 }
1525 }
1526
1527 debug_assert_eq!(self.len, 0);
1528 None
1529 }
1530
1531 fn size_hint(&self) -> (usize, Option<usize>) {
1532 (self.len, Some(self.len))
1533 }
1534}
1535
1536impl<T> DoubleEndedIterator for Iter<'_, T> {
1537 fn next_back(&mut self) -> Option<Self::Item> {
1538 while let Some((key, entry)) = self.entries.next_back() {
1539 if let Entry::Occupied(ref v) = *entry {
1540 self.len -= 1;
1541 return Some((key, v));
1542 }
1543 }
1544
1545 debug_assert_eq!(self.len, 0);
1546 None
1547 }
1548}
1549
1550impl<T> ExactSizeIterator for Iter<'_, T> {
1551 fn len(&self) -> usize {
1552 self.len
1553 }
1554}
1555
1556impl<T> FusedIterator for Iter<'_, T> {}
1557
1558// ===== IterMut =====
1559
1560impl<'a, T> Iterator for IterMut<'a, T> {
1561 type Item = (usize, &'a mut T);
1562
1563 fn next(&mut self) -> Option<Self::Item> {
1564 for (key, entry) in &mut self.entries {
1565 if let Entry::Occupied(ref mut v) = *entry {
1566 self.len -= 1;
1567 return Some((key, v));
1568 }
1569 }
1570
1571 debug_assert_eq!(self.len, 0);
1572 None
1573 }
1574
1575 fn size_hint(&self) -> (usize, Option<usize>) {
1576 (self.len, Some(self.len))
1577 }
1578}
1579
1580impl<T> DoubleEndedIterator for IterMut<'_, T> {
1581 fn next_back(&mut self) -> Option<Self::Item> {
1582 while let Some((key, entry)) = self.entries.next_back() {
1583 if let Entry::Occupied(ref mut v) = *entry {
1584 self.len -= 1;
1585 return Some((key, v));
1586 }
1587 }
1588
1589 debug_assert_eq!(self.len, 0);
1590 None
1591 }
1592}
1593
1594impl<T> ExactSizeIterator for IterMut<'_, T> {
1595 fn len(&self) -> usize {
1596 self.len
1597 }
1598}
1599
1600impl<T> FusedIterator for IterMut<'_, T> {}
1601
1602// ===== Drain =====
1603
1604impl<T> Iterator for Drain<'_, T> {
1605 type Item = T;
1606
1607 fn next(&mut self) -> Option<Self::Item> {
1608 for entry in &mut self.inner {
1609 if let Entry::Occupied(v) = entry {
1610 self.len -= 1;
1611 return Some(v);
1612 }
1613 }
1614
1615 debug_assert_eq!(self.len, 0);
1616 None
1617 }
1618
1619 fn size_hint(&self) -> (usize, Option<usize>) {
1620 (self.len, Some(self.len))
1621 }
1622}
1623
1624impl<T> DoubleEndedIterator for Drain<'_, T> {
1625 fn next_back(&mut self) -> Option<Self::Item> {
1626 while let Some(entry) = self.inner.next_back() {
1627 if let Entry::Occupied(v) = entry {
1628 self.len -= 1;
1629 return Some(v);
1630 }
1631 }
1632
1633 debug_assert_eq!(self.len, 0);
1634 None
1635 }
1636}
1637
1638impl<T> ExactSizeIterator for Drain<'_, T> {
1639 fn len(&self) -> usize {
1640 self.len
1641 }
1642}
1643
1644impl<T> FusedIterator for Drain<'_, T> {}