Coverage Report

Created: 2025-11-16 06:34

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