/rust/registry/src/index.crates.io-6f17d22bba15001f/slab-0.4.7/src/lib.rs
Line | Count | Source (jump to first uncovered line) |
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 | 0 | fn default() -> Self { |
145 | 0 | Slab::new() |
146 | 0 | } |
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 | 0 | fn clone(&self) -> Self { |
191 | 0 | Self { |
192 | 0 | entries: self.entries.clone(), |
193 | 0 | len: self.len, |
194 | 0 | } |
195 | 0 | } |
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 | 0 | pub const fn new() -> Self { |
232 | 0 | Self { |
233 | 0 | entries: Vec::new(), |
234 | 0 | next: 0, |
235 | 0 | len: 0, |
236 | 0 | } |
237 | 0 | } |
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 | 0 | pub fn with_capacity(capacity: usize) -> Slab<T> { |
281 | 0 | Slab { |
282 | 0 | entries: Vec::with_capacity(capacity), |
283 | 0 | next: 0, |
284 | 0 | len: 0, |
285 | 0 | } |
286 | 0 | } |
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 | 0 | pub fn capacity(&self) -> usize { |
298 | 0 | self.entries.capacity() |
299 | 0 | } |
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 | 0 | pub fn reserve(&mut self, additional: usize) { |
328 | 0 | if self.capacity() - self.len >= additional { |
329 | 0 | return; |
330 | 0 | } |
331 | 0 | let need_add = additional - (self.entries.len() - self.len); |
332 | 0 | self.entries.reserve(need_add); |
333 | 0 | } |
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 | 0 | pub fn reserve_exact(&mut self, additional: usize) { |
362 | 0 | if self.capacity() - self.len >= additional { |
363 | 0 | return; |
364 | 0 | } |
365 | 0 | let need_add = additional - (self.entries.len() - self.len); |
366 | 0 | self.entries.reserve_exact(need_add); |
367 | 0 | } |
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 | 0 | pub fn shrink_to_fit(&mut self) { |
411 | 0 | // Remove all vacant entries after the last occupied one, so that |
412 | 0 | // the capacity can be reduced to what is actually needed. |
413 | 0 | // If the slab is empty the vector can simply be cleared, but that |
414 | 0 | // optimization would not affect time complexity when T: Drop. |
415 | 0 | let len_before = self.entries.len(); |
416 | 0 | while let Some(&Entry::Vacant(_)) = self.entries.last() { |
417 | 0 | self.entries.pop(); |
418 | 0 | } |
419 | | |
420 | | // Removing entries breaks the list of vacant entries, |
421 | | // so it must be repaired |
422 | 0 | if self.entries.len() != len_before { |
423 | 0 | // Some vacant entries were removed, so the list now likely¹ |
424 | 0 | // either contains references to the removed entries, or has an |
425 | 0 | // invalid end marker. Fix this by recreating the list. |
426 | 0 | self.recreate_vacant_list(); |
427 | 0 | // ¹: If the removed entries formed the tail of the list, with the |
428 | 0 | // most recently popped entry being the head of them, (so that its |
429 | 0 | // index is now the end marker) the list is still valid. |
430 | 0 | // Checking for that unlikely scenario of this infrequently called |
431 | 0 | // is not worth the code complexity. |
432 | 0 | } |
433 | | |
434 | 0 | self.entries.shrink_to_fit(); |
435 | 0 | } |
436 | | |
437 | | /// Iterate through all entries to recreate and repair the vacant list. |
438 | | /// self.len must be correct and is not modified. |
439 | 0 | fn recreate_vacant_list(&mut self) { |
440 | 0 | self.next = self.entries.len(); |
441 | 0 | // We can stop once we've found all vacant entries |
442 | 0 | 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 | 0 | for (i, entry) in self.entries.iter_mut().enumerate().rev() { |
447 | 0 | if remaining_vacant == 0 { |
448 | 0 | break; |
449 | 0 | } |
450 | 0 | if let Entry::Vacant(ref mut next) = *entry { |
451 | 0 | *next = self.next; |
452 | 0 | self.next = i; |
453 | 0 | remaining_vacant -= 1; |
454 | 0 | } |
455 | | } |
456 | 0 | } |
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 | 0 | pub fn compact<F>(&mut self, mut rekey: F) |
500 | 0 | where |
501 | 0 | F: FnMut(&mut T, usize, usize) -> bool, |
502 | 0 | { |
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 | 0 | fn drop(&mut self) { |
510 | 0 | if self.decrement { |
511 | 0 | // Value was popped and not pushed back on |
512 | 0 | self.slab.len -= 1; |
513 | 0 | } |
514 | 0 | self.slab.recreate_vacant_list(); |
515 | 0 | } |
516 | | } |
517 | 0 | let mut guard = CleanupGuard { |
518 | 0 | slab: self, |
519 | 0 | decrement: true, |
520 | 0 | }; |
521 | 0 |
|
522 | 0 | let mut occupied_until = 0; |
523 | | // While there are vacant entries |
524 | 0 | 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 | 0 | if let Some(Entry::Occupied(mut value)) = guard.slab.entries.pop() { |
529 | | // Found one, now find a vacant entry to move it to |
530 | 0 | while let Some(&Entry::Occupied(_)) = guard.slab.entries.get(occupied_until) { |
531 | 0 | occupied_until += 1; |
532 | 0 | } |
533 | | // Let the caller try to update references to the key |
534 | 0 | 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 | 0 | guard.slab.entries.push(Entry::Occupied(value)); |
537 | 0 | guard.decrement = false; |
538 | 0 | guard.slab.entries.shrink_to_fit(); |
539 | 0 | return; |
540 | | // Guard drop handles cleanup |
541 | 0 | } |
542 | 0 | // Put the value in its new spot |
543 | 0 | guard.slab.entries[occupied_until] = Entry::Occupied(value); |
544 | 0 | // ... and mark it as occupied (this is optional) |
545 | 0 | occupied_until += 1; |
546 | 0 | } |
547 | | } |
548 | 0 | guard.slab.next = guard.slab.len; |
549 | 0 | guard.slab.entries.shrink_to_fit(); |
550 | 0 | // Normal cleanup is not necessary |
551 | 0 | mem::forget(guard); |
552 | 0 | } |
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 | 0 | pub fn clear(&mut self) { |
570 | 0 | self.entries.clear(); |
571 | 0 | self.len = 0; |
572 | 0 | self.next = 0; |
573 | 0 | } |
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 | } |
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 | 0 | pub fn is_empty(&self) -> bool { |
606 | 0 | self.len == 0 |
607 | 0 | } |
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 | 0 | pub fn iter(&self) -> Iter<'_, T> { |
634 | 0 | Iter { |
635 | 0 | entries: self.entries.iter().enumerate(), |
636 | 0 | len: self.len, |
637 | 0 | } |
638 | 0 | } |
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<core::option::Option<core::task::wake::Waker>>>::iter_mut Unexecuted instantiation: <slab::Slab<_>>::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 | 0 | pub fn get_mut(&mut self, key: usize) -> Option<&mut T> { |
712 | 0 | match self.entries.get_mut(key) { |
713 | 0 | Some(&mut Entry::Occupied(ref mut val)) => Some(val), |
714 | 0 | _ => None, |
715 | | } |
716 | 0 | } |
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 | 0 | pub fn get2_mut(&mut self, key1: usize, key2: usize) -> Option<(&mut T, &mut T)> { |
742 | 0 | assert!(key1 != key2); |
743 | | |
744 | | let (entry1, entry2); |
745 | | |
746 | 0 | if key1 > key2 { |
747 | 0 | let (slice1, slice2) = self.entries.split_at_mut(key1); |
748 | 0 | entry1 = slice2.get_mut(0); |
749 | 0 | entry2 = slice1.get_mut(key2); |
750 | 0 | } else { |
751 | 0 | let (slice1, slice2) = self.entries.split_at_mut(key2); |
752 | 0 | entry1 = slice1.get_mut(key1); |
753 | 0 | entry2 = slice2.get_mut(0); |
754 | 0 | } |
755 | | |
756 | 0 | match (entry1, entry2) { |
757 | | ( |
758 | 0 | Some(&mut Entry::Occupied(ref mut val1)), |
759 | 0 | Some(&mut Entry::Occupied(ref mut val2)), |
760 | 0 | ) => Some((val1, val2)), |
761 | 0 | _ => None, |
762 | | } |
763 | 0 | } |
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 | 0 | pub unsafe fn get_unchecked(&self, key: usize) -> &T { |
788 | 0 | match *self.entries.get_unchecked(key) { |
789 | 0 | Entry::Occupied(ref val) => val, |
790 | 0 | _ => unreachable!(), |
791 | | } |
792 | 0 | } |
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 | 0 | pub unsafe fn get_unchecked_mut(&mut self, key: usize) -> &mut T { |
820 | 0 | match *self.entries.get_unchecked_mut(key) { |
821 | 0 | Entry::Occupied(ref mut val) => val, |
822 | 0 | _ => unreachable!(), |
823 | | } |
824 | 0 | } |
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 | 0 | pub unsafe fn get2_unchecked_mut(&mut self, key1: usize, key2: usize) -> (&mut T, &mut T) { |
854 | 0 | debug_assert_ne!(key1, key2); |
855 | 0 | let ptr = self.entries.as_mut_ptr(); |
856 | 0 | let ptr1 = ptr.add(key1); |
857 | 0 | let ptr2 = ptr.add(key2); |
858 | 0 | match (&mut *ptr1, &mut *ptr2) { |
859 | 0 | (&mut Entry::Occupied(ref mut val1), &mut Entry::Occupied(ref mut val2)) => { |
860 | 0 | (val1, val2) |
861 | | } |
862 | 0 | _ => unreachable!(), |
863 | | } |
864 | 0 | } |
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 | 0 | pub fn key_of(&self, present_element: &T) -> usize { |
903 | 0 | let element_ptr = present_element as *const T as usize; |
904 | 0 | let base_ptr = self.entries.as_ptr() as usize; |
905 | 0 | // Use wrapping subtraction in case the reference is bad |
906 | 0 | let byte_offset = element_ptr.wrapping_sub(base_ptr); |
907 | 0 | // The division rounds away any offset of T inside Entry |
908 | 0 | // The size of Entry<T> is never zero even if T is due to Vacant(usize) |
909 | 0 | let key = byte_offset / mem::size_of::<Entry<T>>(); |
910 | 0 | // Prevent returning unspecified (but out of bounds) values |
911 | 0 | if key >= self.entries.len() { |
912 | 0 | panic!("The reference points to a value outside this slab"); |
913 | 0 | } |
914 | 0 | // The reference cannot point to a vacant entry, because then it would not be valid |
915 | 0 | key |
916 | 0 | } |
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 | 0 |
|
939 | 0 | self.insert_at(key, val); |
940 | 0 |
|
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 | 0 | pub fn vacant_key(&self) -> usize { |
965 | 0 | self.next |
966 | 0 | } |
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 | 0 | pub fn vacant_entry(&mut self) -> VacantEntry<'_, T> { |
992 | 0 | VacantEntry { |
993 | 0 | key: self.next, |
994 | 0 | slab: self, |
995 | 0 | } |
996 | 0 | } |
997 | | |
998 | 0 | fn insert_at(&mut self, key: usize, val: T) { |
999 | 0 | self.len += 1; |
1000 | 0 |
|
1001 | 0 | if key == self.entries.len() { |
1002 | 0 | self.entries.push(Entry::Occupied(val)); |
1003 | 0 | self.next = key + 1; |
1004 | 0 | } 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 | 0 | } |
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 | 0 | pub fn try_remove(&mut self, key: usize) -> Option<T> { |
1031 | 0 | if let Some(entry) = self.entries.get_mut(key) { |
1032 | | // Swap the entry at the provided value |
1033 | 0 | let prev = mem::replace(entry, Entry::Vacant(self.next)); |
1034 | 0 |
|
1035 | 0 | match prev { |
1036 | 0 | Entry::Occupied(val) => { |
1037 | 0 | self.len -= 1; |
1038 | 0 | self.next = key; |
1039 | 0 | 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 | 0 | } |
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 | 0 | pub fn remove(&mut self, key: usize) -> T { |
1072 | 0 | self.try_remove(key).expect("invalid key") |
1073 | 0 | } |
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 | 0 | pub fn contains(&self, key: usize) -> bool { |
1091 | 0 | match self.entries.get(key) { |
1092 | 0 | Some(&Entry::Occupied(_)) => true, |
1093 | 0 | _ => false, |
1094 | | } |
1095 | 0 | } |
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 | 0 | pub fn retain<F>(&mut self, mut f: F) |
1122 | 0 | where |
1123 | 0 | F: FnMut(usize, &mut T) -> bool, |
1124 | 0 | { |
1125 | 0 | for i in 0..self.entries.len() { |
1126 | 0 | let keep = match self.entries[i] { |
1127 | 0 | Entry::Occupied(ref mut v) => f(i, v), |
1128 | 0 | _ => true, |
1129 | | }; |
1130 | | |
1131 | 0 | if !keep { |
1132 | 0 | self.remove(i); |
1133 | 0 | } |
1134 | | } |
1135 | 0 | } |
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 | 0 | pub fn drain(&mut self) -> Drain<'_, T> { |
1165 | 0 | let old_len = self.len; |
1166 | 0 | self.len = 0; |
1167 | 0 | self.next = 0; |
1168 | 0 | Drain { |
1169 | 0 | inner: self.entries.drain(..), |
1170 | 0 | len: old_len, |
1171 | 0 | } |
1172 | 0 | } |
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 | 0 | fn index(&self, key: usize) -> &T { |
1180 | 0 | match self.entries.get(key) { |
1181 | 0 | Some(&Entry::Occupied(ref v)) => v, |
1182 | 0 | _ => panic!("invalid key"), |
1183 | | } |
1184 | 0 | } |
1185 | | } |
1186 | | |
1187 | | impl<T> ops::IndexMut<usize> for Slab<T> { |
1188 | | #[cfg_attr(not(slab_no_track_caller), track_caller)] |
1189 | 0 | fn index_mut(&mut self, key: usize) -> &mut T { |
1190 | 0 | match self.entries.get_mut(key) { |
1191 | 0 | Some(&mut Entry::Occupied(ref mut v)) => v, |
1192 | 0 | _ => panic!("invalid key"), |
1193 | | } |
1194 | 0 | } |
1195 | | } |
1196 | | |
1197 | | impl<T> IntoIterator for Slab<T> { |
1198 | | type Item = (usize, T); |
1199 | | type IntoIter = IntoIter<T>; |
1200 | | |
1201 | 0 | fn into_iter(self) -> IntoIter<T> { |
1202 | 0 | IntoIter { |
1203 | 0 | entries: self.entries.into_iter().enumerate(), |
1204 | 0 | len: self.len, |
1205 | 0 | } |
1206 | 0 | } |
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 | 0 | fn into_iter(self) -> Iter<'a, T> { |
1214 | 0 | self.iter() |
1215 | 0 | } |
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 | } Unexecuted instantiation: <&mut slab::Slab<core::option::Option<core::task::wake::Waker>> as core::iter::traits::collect::IntoIterator>::into_iter Unexecuted instantiation: <&mut slab::Slab<_> as core::iter::traits::collect::IntoIterator>::into_iter |
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 | 0 | fn from_iter<I>(iterable: I) -> Self |
1259 | 0 | where |
1260 | 0 | I: IntoIterator<Item = (usize, T)>, |
1261 | 0 | { |
1262 | 0 | let iterator = iterable.into_iter(); |
1263 | 0 | let mut slab = Self::with_capacity(iterator.size_hint().0); |
1264 | 0 |
|
1265 | 0 | let mut vacant_list_broken = false; |
1266 | 0 | let mut first_vacant_index = None; |
1267 | 0 | for (key, value) in iterator { |
1268 | 0 | if key < slab.entries.len() { |
1269 | | // iterator is not sorted, might need to recreate vacant list |
1270 | 0 | if let Entry::Vacant(_) = slab.entries[key] { |
1271 | 0 | vacant_list_broken = true; |
1272 | 0 | slab.len += 1; |
1273 | 0 | } |
1274 | | // if an element with this key already exists, replace it. |
1275 | | // This is consistent with HashMap and BtreeMap |
1276 | 0 | slab.entries[key] = Entry::Occupied(value); |
1277 | | } else { |
1278 | 0 | if first_vacant_index.is_none() && slab.entries.len() < key { |
1279 | 0 | first_vacant_index = Some(slab.entries.len()); |
1280 | 0 | } |
1281 | | // insert holes as necessary |
1282 | 0 | while slab.entries.len() < key { |
1283 | 0 | // add the entry to the start of the vacant list |
1284 | 0 | let next = slab.next; |
1285 | 0 | slab.next = slab.entries.len(); |
1286 | 0 | slab.entries.push(Entry::Vacant(next)); |
1287 | 0 | } |
1288 | 0 | slab.entries.push(Entry::Occupied(value)); |
1289 | 0 | slab.len += 1; |
1290 | | } |
1291 | | } |
1292 | 0 | if slab.len == slab.entries.len() { |
1293 | 0 | // no vacant entries, so next might not have been updated |
1294 | 0 | slab.next = slab.entries.len(); |
1295 | 0 | } else if vacant_list_broken { |
1296 | 0 | slab.recreate_vacant_list(); |
1297 | 0 | } else if let Some(first_vacant_index) = first_vacant_index { |
1298 | 0 | let next = slab.entries.len(); |
1299 | 0 | match &mut slab.entries[first_vacant_index] { |
1300 | 0 | Entry::Vacant(n) => *n = next, |
1301 | 0 | _ => unreachable!(), |
1302 | | } |
1303 | | } else { |
1304 | 0 | unreachable!() |
1305 | | } |
1306 | | |
1307 | 0 | slab |
1308 | 0 | } |
1309 | | } |
1310 | | |
1311 | | impl<T> fmt::Debug for Slab<T> |
1312 | | where |
1313 | | T: fmt::Debug, |
1314 | | { |
1315 | 0 | fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
1316 | 0 | if fmt.alternate() { |
1317 | 0 | fmt.debug_map().entries(self.iter()).finish() |
1318 | | } else { |
1319 | 0 | fmt.debug_struct("Slab") |
1320 | 0 | .field("len", &self.len) |
1321 | 0 | .field("cap", &self.capacity()) |
1322 | 0 | .finish() |
1323 | | } |
1324 | 0 | } |
1325 | | } |
1326 | | |
1327 | | impl<T> fmt::Debug for IntoIter<T> |
1328 | | where |
1329 | | T: fmt::Debug, |
1330 | | { |
1331 | 0 | fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
1332 | 0 | fmt.debug_struct("IntoIter") |
1333 | 0 | .field("remaining", &self.len) |
1334 | 0 | .finish() |
1335 | 0 | } |
1336 | | } |
1337 | | |
1338 | | impl<T> fmt::Debug for Iter<'_, T> |
1339 | | where |
1340 | | T: fmt::Debug, |
1341 | | { |
1342 | 0 | fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
1343 | 0 | fmt.debug_struct("Iter") |
1344 | 0 | .field("remaining", &self.len) |
1345 | 0 | .finish() |
1346 | 0 | } |
1347 | | } |
1348 | | |
1349 | | impl<T> fmt::Debug for IterMut<'_, T> |
1350 | | where |
1351 | | T: fmt::Debug, |
1352 | | { |
1353 | 0 | fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
1354 | 0 | fmt.debug_struct("IterMut") |
1355 | 0 | .field("remaining", &self.len) |
1356 | 0 | .finish() |
1357 | 0 | } |
1358 | | } |
1359 | | |
1360 | | impl<T> fmt::Debug for Drain<'_, T> { |
1361 | 0 | fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
1362 | 0 | fmt.debug_struct("Drain").finish() |
1363 | 0 | } |
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 | 0 | pub fn insert(self, val: T) -> &'a mut T { |
1392 | 0 | self.slab.insert_at(self.key, val); |
1393 | 0 |
|
1394 | 0 | match self.slab.entries.get_mut(self.key) { |
1395 | 0 | Some(&mut Entry::Occupied(ref mut v)) => v, |
1396 | 0 | _ => unreachable!(), |
1397 | | } |
1398 | 0 | } |
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 | 0 | pub fn key(&self) -> usize { |
1422 | 0 | self.key |
1423 | 0 | } |
1424 | | } |
1425 | | |
1426 | | // ===== IntoIter ===== |
1427 | | |
1428 | | impl<T> Iterator for IntoIter<T> { |
1429 | | type Item = (usize, T); |
1430 | | |
1431 | 0 | fn next(&mut self) -> Option<Self::Item> { |
1432 | 0 | for (key, entry) in &mut self.entries { |
1433 | 0 | if let Entry::Occupied(v) = entry { |
1434 | 0 | self.len -= 1; |
1435 | 0 | return Some((key, v)); |
1436 | 0 | } |
1437 | | } |
1438 | | |
1439 | 0 | debug_assert_eq!(self.len, 0); |
1440 | 0 | None |
1441 | 0 | } |
1442 | | |
1443 | 0 | fn size_hint(&self) -> (usize, Option<usize>) { |
1444 | 0 | (self.len, Some(self.len)) |
1445 | 0 | } |
1446 | | } |
1447 | | |
1448 | | impl<T> DoubleEndedIterator for IntoIter<T> { |
1449 | 0 | fn next_back(&mut self) -> Option<Self::Item> { |
1450 | 0 | while let Some((key, entry)) = self.entries.next_back() { |
1451 | 0 | if let Entry::Occupied(v) = entry { |
1452 | 0 | self.len -= 1; |
1453 | 0 | return Some((key, v)); |
1454 | 0 | } |
1455 | | } |
1456 | | |
1457 | 0 | debug_assert_eq!(self.len, 0); |
1458 | 0 | None |
1459 | 0 | } |
1460 | | } |
1461 | | |
1462 | | impl<T> ExactSizeIterator for IntoIter<T> { |
1463 | 0 | fn len(&self) -> usize { |
1464 | 0 | self.len |
1465 | 0 | } |
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 | 0 | fn next(&mut self) -> Option<Self::Item> { |
1476 | 0 | for (key, entry) in &mut self.entries { |
1477 | 0 | if let Entry::Occupied(ref v) = *entry { |
1478 | 0 | self.len -= 1; |
1479 | 0 | return Some((key, v)); |
1480 | 0 | } |
1481 | | } |
1482 | | |
1483 | 0 | debug_assert_eq!(self.len, 0); |
1484 | 0 | None |
1485 | 0 | } |
1486 | | |
1487 | 0 | fn size_hint(&self) -> (usize, Option<usize>) { |
1488 | 0 | (self.len, Some(self.len)) |
1489 | 0 | } |
1490 | | } |
1491 | | |
1492 | | impl<T> DoubleEndedIterator for Iter<'_, T> { |
1493 | 0 | fn next_back(&mut self) -> Option<Self::Item> { |
1494 | 0 | while let Some((key, entry)) = self.entries.next_back() { |
1495 | 0 | if let Entry::Occupied(ref v) = *entry { |
1496 | 0 | self.len -= 1; |
1497 | 0 | return Some((key, v)); |
1498 | 0 | } |
1499 | | } |
1500 | | |
1501 | 0 | debug_assert_eq!(self.len, 0); |
1502 | 0 | None |
1503 | 0 | } |
1504 | | } |
1505 | | |
1506 | | impl<T> ExactSizeIterator for Iter<'_, T> { |
1507 | 0 | fn len(&self) -> usize { |
1508 | 0 | self.len |
1509 | 0 | } |
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<core::option::Option<core::task::wake::Waker>> as core::iter::traits::iterator::Iterator>::next Unexecuted instantiation: <slab::IterMut<_> 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 | 0 | fn next_back(&mut self) -> Option<Self::Item> { |
1538 | 0 | while let Some((key, entry)) = self.entries.next_back() { |
1539 | 0 | if let Entry::Occupied(ref mut v) = *entry { |
1540 | 0 | self.len -= 1; |
1541 | 0 | return Some((key, v)); |
1542 | 0 | } |
1543 | | } |
1544 | | |
1545 | 0 | debug_assert_eq!(self.len, 0); |
1546 | 0 | None |
1547 | 0 | } |
1548 | | } |
1549 | | |
1550 | | impl<T> ExactSizeIterator for IterMut<'_, T> { |
1551 | 0 | fn len(&self) -> usize { |
1552 | 0 | self.len |
1553 | 0 | } |
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 | 0 | fn next(&mut self) -> Option<Self::Item> { |
1564 | 0 | for entry in &mut self.inner { |
1565 | 0 | if let Entry::Occupied(v) = entry { |
1566 | 0 | self.len -= 1; |
1567 | 0 | return Some(v); |
1568 | 0 | } |
1569 | | } |
1570 | | |
1571 | 0 | debug_assert_eq!(self.len, 0); |
1572 | 0 | None |
1573 | 0 | } |
1574 | | |
1575 | 0 | fn size_hint(&self) -> (usize, Option<usize>) { |
1576 | 0 | (self.len, Some(self.len)) |
1577 | 0 | } |
1578 | | } |
1579 | | |
1580 | | impl<T> DoubleEndedIterator for Drain<'_, T> { |
1581 | 0 | fn next_back(&mut self) -> Option<Self::Item> { |
1582 | 0 | while let Some(entry) = self.inner.next_back() { |
1583 | 0 | if let Entry::Occupied(v) = entry { |
1584 | 0 | self.len -= 1; |
1585 | 0 | return Some(v); |
1586 | 0 | } |
1587 | | } |
1588 | | |
1589 | 0 | debug_assert_eq!(self.len, 0); |
1590 | 0 | None |
1591 | 0 | } |
1592 | | } |
1593 | | |
1594 | | impl<T> ExactSizeIterator for Drain<'_, T> { |
1595 | 0 | fn len(&self) -> usize { |
1596 | 0 | self.len |
1597 | 0 | } |
1598 | | } |
1599 | | |
1600 | | impl<T> FusedIterator for Drain<'_, T> {} |