xref: /linux/rust/kernel/alloc/kvec.rs (revision ec7714e4947909190ffb3041a03311a975350fe0)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 //! Implementation of [`Vec`].
4 
5 use super::{
6     allocator::{KVmalloc, Kmalloc, Vmalloc},
7     layout::ArrayLayout,
8     AllocError, Allocator, Box, Flags,
9 };
10 use core::{
11     fmt,
12     marker::PhantomData,
13     mem::{ManuallyDrop, MaybeUninit},
14     ops::Deref,
15     ops::DerefMut,
16     ops::Index,
17     ops::IndexMut,
18     ptr,
19     ptr::NonNull,
20     slice,
21     slice::SliceIndex,
22 };
23 
24 mod errors;
25 pub use self::errors::{InsertError, PushError, RemoveError};
26 
27 /// Create a [`KVec`] containing the arguments.
28 ///
29 /// New memory is allocated with `GFP_KERNEL`.
30 ///
31 /// # Examples
32 ///
33 /// ```
34 /// let mut v = kernel::kvec![];
35 /// v.push(1, GFP_KERNEL)?;
36 /// assert_eq!(v, [1]);
37 ///
38 /// let mut v = kernel::kvec![1; 3]?;
39 /// v.push(4, GFP_KERNEL)?;
40 /// assert_eq!(v, [1, 1, 1, 4]);
41 ///
42 /// let mut v = kernel::kvec![1, 2, 3]?;
43 /// v.push(4, GFP_KERNEL)?;
44 /// assert_eq!(v, [1, 2, 3, 4]);
45 ///
46 /// # Ok::<(), Error>(())
47 /// ```
48 #[macro_export]
49 macro_rules! kvec {
50     () => (
51         $crate::alloc::KVec::new()
52     );
53     ($elem:expr; $n:expr) => (
54         $crate::alloc::KVec::from_elem($elem, $n, GFP_KERNEL)
55     );
56     ($($x:expr),+ $(,)?) => (
57         match $crate::alloc::KBox::new_uninit(GFP_KERNEL) {
58             Ok(b) => Ok($crate::alloc::KVec::from($crate::alloc::KBox::write(b, [$($x),+]))),
59             Err(e) => Err(e),
60         }
61     );
62 }
63 
64 /// The kernel's [`Vec`] type.
65 ///
66 /// A contiguous growable array type with contents allocated with the kernel's allocators (e.g.
67 /// [`Kmalloc`], [`Vmalloc`] or [`KVmalloc`]), written `Vec<T, A>`.
68 ///
69 /// For non-zero-sized values, a [`Vec`] will use the given allocator `A` for its allocation. For
70 /// the most common allocators the type aliases [`KVec`], [`VVec`] and [`KVVec`] exist.
71 ///
72 /// For zero-sized types the [`Vec`]'s pointer must be `dangling_mut::<T>`; no memory is allocated.
73 ///
74 /// Generally, [`Vec`] consists of a pointer that represents the vector's backing buffer, the
75 /// capacity of the vector (the number of elements that currently fit into the vector), its length
76 /// (the number of elements that are currently stored in the vector) and the `Allocator` type used
77 /// to allocate (and free) the backing buffer.
78 ///
79 /// A [`Vec`] can be deconstructed into and (re-)constructed from its previously named raw parts
80 /// and manually modified.
81 ///
82 /// [`Vec`]'s backing buffer gets, if required, automatically increased (re-allocated) when elements
83 /// are added to the vector.
84 ///
85 /// # Invariants
86 ///
87 /// - `self.ptr` is always properly aligned and either points to memory allocated with `A` or, for
88 ///   zero-sized types, is a dangling, well aligned pointer.
89 ///
90 /// - `self.len` always represents the exact number of elements stored in the vector.
91 ///
92 /// - `self.layout` represents the absolute number of elements that can be stored within the vector
93 ///   without re-allocation. For ZSTs `self.layout`'s capacity is zero. However, it is legal for the
94 ///   backing buffer to be larger than `layout`.
95 ///
96 /// - `self.len()` is always less than or equal to `self.capacity()`.
97 ///
98 /// - The `Allocator` type `A` of the vector is the exact same `Allocator` type the backing buffer
99 ///   was allocated with (and must be freed with).
100 pub struct Vec<T, A: Allocator> {
101     ptr: NonNull<T>,
102     /// Represents the actual buffer size as `cap` times `size_of::<T>` bytes.
103     ///
104     /// Note: This isn't quite the same as `Self::capacity`, which in contrast returns the number of
105     /// elements we can still store without reallocating.
106     layout: ArrayLayout<T>,
107     len: usize,
108     _p: PhantomData<A>,
109 }
110 
111 /// Type alias for [`Vec`] with a [`Kmalloc`] allocator.
112 ///
113 /// # Examples
114 ///
115 /// ```
116 /// let mut v = KVec::new();
117 /// v.push(1, GFP_KERNEL)?;
118 /// assert_eq!(&v, &[1]);
119 ///
120 /// # Ok::<(), Error>(())
121 /// ```
122 pub type KVec<T> = Vec<T, Kmalloc>;
123 
124 /// Type alias for [`Vec`] with a [`Vmalloc`] allocator.
125 ///
126 /// # Examples
127 ///
128 /// ```
129 /// let mut v = VVec::new();
130 /// v.push(1, GFP_KERNEL)?;
131 /// assert_eq!(&v, &[1]);
132 ///
133 /// # Ok::<(), Error>(())
134 /// ```
135 pub type VVec<T> = Vec<T, Vmalloc>;
136 
137 /// Type alias for [`Vec`] with a [`KVmalloc`] allocator.
138 ///
139 /// # Examples
140 ///
141 /// ```
142 /// let mut v = KVVec::new();
143 /// v.push(1, GFP_KERNEL)?;
144 /// assert_eq!(&v, &[1]);
145 ///
146 /// # Ok::<(), Error>(())
147 /// ```
148 pub type KVVec<T> = Vec<T, KVmalloc>;
149 
150 // SAFETY: `Vec` is `Send` if `T` is `Send` because `Vec` owns its elements.
151 unsafe impl<T, A> Send for Vec<T, A>
152 where
153     T: Send,
154     A: Allocator,
155 {
156 }
157 
158 // SAFETY: `Vec` is `Sync` if `T` is `Sync` because `Vec` owns its elements.
159 unsafe impl<T, A> Sync for Vec<T, A>
160 where
161     T: Sync,
162     A: Allocator,
163 {
164 }
165 
166 impl<T, A> Vec<T, A>
167 where
168     A: Allocator,
169 {
170     #[inline]
is_zst() -> bool171     const fn is_zst() -> bool {
172         core::mem::size_of::<T>() == 0
173     }
174 
175     /// Returns the number of elements that can be stored within the vector without allocating
176     /// additional memory.
capacity(&self) -> usize177     pub fn capacity(&self) -> usize {
178         if const { Self::is_zst() } {
179             usize::MAX
180         } else {
181             self.layout.len()
182         }
183     }
184 
185     /// Returns the number of elements stored within the vector.
186     #[inline]
len(&self) -> usize187     pub fn len(&self) -> usize {
188         self.len
189     }
190 
191     /// Increments `self.len` by `additional`.
192     ///
193     /// # Safety
194     ///
195     /// - `additional` must be less than or equal to `self.capacity - self.len`.
196     /// - All elements within the interval [`self.len`,`self.len + additional`) must be initialized.
197     #[inline]
inc_len(&mut self, additional: usize)198     pub unsafe fn inc_len(&mut self, additional: usize) {
199         // Guaranteed by the type invariant to never underflow.
200         debug_assert!(additional <= self.capacity() - self.len());
201         // INVARIANT: By the safety requirements of this method this represents the exact number of
202         // elements stored within `self`.
203         self.len += additional;
204     }
205 
206     /// Decreases `self.len` by `count`.
207     ///
208     /// Returns a mutable slice to the elements forgotten by the vector. It is the caller's
209     /// responsibility to drop these elements if necessary.
210     ///
211     /// # Safety
212     ///
213     /// - `count` must be less than or equal to `self.len`.
dec_len(&mut self, count: usize) -> &mut [T]214     unsafe fn dec_len(&mut self, count: usize) -> &mut [T] {
215         debug_assert!(count <= self.len());
216         // INVARIANT: We relinquish ownership of the elements within the range `[self.len - count,
217         // self.len)`, hence the updated value of `set.len` represents the exact number of elements
218         // stored within `self`.
219         self.len -= count;
220         // SAFETY: The memory after `self.len()` is guaranteed to contain `count` initialized
221         // elements of type `T`.
222         unsafe { slice::from_raw_parts_mut(self.as_mut_ptr().add(self.len), count) }
223     }
224 
225     /// Returns a slice of the entire vector.
226     #[inline]
as_slice(&self) -> &[T]227     pub fn as_slice(&self) -> &[T] {
228         self
229     }
230 
231     /// Returns a mutable slice of the entire vector.
232     #[inline]
as_mut_slice(&mut self) -> &mut [T]233     pub fn as_mut_slice(&mut self) -> &mut [T] {
234         self
235     }
236 
237     /// Returns a mutable raw pointer to the vector's backing buffer, or, if `T` is a ZST, a
238     /// dangling raw pointer.
239     #[inline]
as_mut_ptr(&mut self) -> *mut T240     pub fn as_mut_ptr(&mut self) -> *mut T {
241         self.ptr.as_ptr()
242     }
243 
244     /// Returns a raw pointer to the vector's backing buffer, or, if `T` is a ZST, a dangling raw
245     /// pointer.
246     #[inline]
as_ptr(&self) -> *const T247     pub fn as_ptr(&self) -> *const T {
248         self.ptr.as_ptr()
249     }
250 
251     /// Returns `true` if the vector contains no elements, `false` otherwise.
252     ///
253     /// # Examples
254     ///
255     /// ```
256     /// let mut v = KVec::new();
257     /// assert!(v.is_empty());
258     ///
259     /// v.push(1, GFP_KERNEL);
260     /// assert!(!v.is_empty());
261     /// ```
262     #[inline]
is_empty(&self) -> bool263     pub fn is_empty(&self) -> bool {
264         self.len() == 0
265     }
266 
267     /// Creates a new, empty `Vec<T, A>`.
268     ///
269     /// This method does not allocate by itself.
270     #[inline]
new() -> Self271     pub const fn new() -> Self {
272         // INVARIANT: Since this is a new, empty `Vec` with no backing memory yet,
273         // - `ptr` is a properly aligned dangling pointer for type `T`,
274         // - `layout` is an empty `ArrayLayout` (zero capacity)
275         // - `len` is zero, since no elements can be or have been stored,
276         // - `A` is always valid.
277         Self {
278             ptr: NonNull::dangling(),
279             layout: ArrayLayout::empty(),
280             len: 0,
281             _p: PhantomData::<A>,
282         }
283     }
284 
285     /// Returns a slice of `MaybeUninit<T>` for the remaining spare capacity of the vector.
spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>]286     pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
287         // SAFETY:
288         // - `self.len` is smaller than `self.capacity` by the type invariant and hence, the
289         //   resulting pointer is guaranteed to be part of the same allocated object.
290         // - `self.len` can not overflow `isize`.
291         let ptr = unsafe { self.as_mut_ptr().add(self.len) } as *mut MaybeUninit<T>;
292 
293         // SAFETY: The memory between `self.len` and `self.capacity` is guaranteed to be allocated
294         // and valid, but uninitialized.
295         unsafe { slice::from_raw_parts_mut(ptr, self.capacity() - self.len) }
296     }
297 
298     /// Appends an element to the back of the [`Vec`] instance.
299     ///
300     /// # Examples
301     ///
302     /// ```
303     /// let mut v = KVec::new();
304     /// v.push(1, GFP_KERNEL)?;
305     /// assert_eq!(&v, &[1]);
306     ///
307     /// v.push(2, GFP_KERNEL)?;
308     /// assert_eq!(&v, &[1, 2]);
309     /// # Ok::<(), Error>(())
310     /// ```
push(&mut self, v: T, flags: Flags) -> Result<(), AllocError>311     pub fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> {
312         self.reserve(1, flags)?;
313         // SAFETY: The call to `reserve` was successful, so the capacity is at least one greater
314         // than the length.
315         unsafe { self.push_within_capacity_unchecked(v) };
316         Ok(())
317     }
318 
319     /// Appends an element to the back of the [`Vec`] instance without reallocating.
320     ///
321     /// Fails if the vector does not have capacity for the new element.
322     ///
323     /// # Examples
324     ///
325     /// ```
326     /// let mut v = KVec::with_capacity(10, GFP_KERNEL)?;
327     /// for i in 0..10 {
328     ///     v.push_within_capacity(i)?;
329     /// }
330     ///
331     /// assert!(v.push_within_capacity(10).is_err());
332     /// # Ok::<(), Error>(())
333     /// ```
push_within_capacity(&mut self, v: T) -> Result<(), PushError<T>>334     pub fn push_within_capacity(&mut self, v: T) -> Result<(), PushError<T>> {
335         if self.len() < self.capacity() {
336             // SAFETY: The length is less than the capacity.
337             unsafe { self.push_within_capacity_unchecked(v) };
338             Ok(())
339         } else {
340             Err(PushError(v))
341         }
342     }
343 
344     /// Appends an element to the back of the [`Vec`] instance without reallocating.
345     ///
346     /// # Safety
347     ///
348     /// The length must be less than the capacity.
push_within_capacity_unchecked(&mut self, v: T)349     unsafe fn push_within_capacity_unchecked(&mut self, v: T) {
350         let spare = self.spare_capacity_mut();
351 
352         // SAFETY: By the safety requirements, `spare` is non-empty.
353         unsafe { spare.get_unchecked_mut(0) }.write(v);
354 
355         // SAFETY: We just initialised the first spare entry, so it is safe to increase the length
356         // by 1. We also know that the new length is <= capacity because the caller guarantees that
357         // the length is less than the capacity at the beginning of this function.
358         unsafe { self.inc_len(1) };
359     }
360 
361     /// Inserts an element at the given index in the [`Vec`] instance.
362     ///
363     /// Fails if the vector does not have capacity for the new element. Panics if the index is out
364     /// of bounds.
365     ///
366     /// # Examples
367     ///
368     /// ```
369     /// use kernel::alloc::kvec::InsertError;
370     ///
371     /// let mut v = KVec::with_capacity(5, GFP_KERNEL)?;
372     /// for i in 0..5 {
373     ///     v.insert_within_capacity(0, i)?;
374     /// }
375     ///
376     /// assert!(matches!(v.insert_within_capacity(0, 5), Err(InsertError::OutOfCapacity(_))));
377     /// assert!(matches!(v.insert_within_capacity(1000, 5), Err(InsertError::IndexOutOfBounds(_))));
378     /// assert_eq!(v, [4, 3, 2, 1, 0]);
379     /// # Ok::<(), Error>(())
380     /// ```
insert_within_capacity( &mut self, index: usize, element: T, ) -> Result<(), InsertError<T>>381     pub fn insert_within_capacity(
382         &mut self,
383         index: usize,
384         element: T,
385     ) -> Result<(), InsertError<T>> {
386         let len = self.len();
387         if index > len {
388             return Err(InsertError::IndexOutOfBounds(element));
389         }
390 
391         if len >= self.capacity() {
392             return Err(InsertError::OutOfCapacity(element));
393         }
394 
395         // SAFETY: This is in bounds since `index <= len < capacity`.
396         let p = unsafe { self.as_mut_ptr().add(index) };
397         // INVARIANT: This breaks the Vec invariants by making `index` contain an invalid element,
398         // but we restore the invariants below.
399         // SAFETY: Both the src and dst ranges end no later than one element after the length.
400         // Since the length is less than the capacity, both ranges are in bounds of the allocation.
401         unsafe { ptr::copy(p, p.add(1), len - index) };
402         // INVARIANT: This restores the Vec invariants.
403         // SAFETY: The pointer is in-bounds of the allocation.
404         unsafe { ptr::write(p, element) };
405         // SAFETY: Index `len` contains a valid element due to the above copy and write.
406         unsafe { self.inc_len(1) };
407         Ok(())
408     }
409 
410     /// Removes the last element from a vector and returns it, or `None` if it is empty.
411     ///
412     /// # Examples
413     ///
414     /// ```
415     /// let mut v = KVec::new();
416     /// v.push(1, GFP_KERNEL)?;
417     /// v.push(2, GFP_KERNEL)?;
418     /// assert_eq!(&v, &[1, 2]);
419     ///
420     /// assert_eq!(v.pop(), Some(2));
421     /// assert_eq!(v.pop(), Some(1));
422     /// assert_eq!(v.pop(), None);
423     /// # Ok::<(), Error>(())
424     /// ```
pop(&mut self) -> Option<T>425     pub fn pop(&mut self) -> Option<T> {
426         if self.is_empty() {
427             return None;
428         }
429 
430         let removed: *mut T = {
431             // SAFETY: We just checked that the length is at least one.
432             let slice = unsafe { self.dec_len(1) };
433             // SAFETY: The argument to `dec_len` was 1 so this returns a slice of length 1.
434             unsafe { slice.get_unchecked_mut(0) }
435         };
436 
437         // SAFETY: The guarantees of `dec_len` allow us to take ownership of this value.
438         Some(unsafe { removed.read() })
439     }
440 
441     /// Removes the element at the given index.
442     ///
443     /// # Examples
444     ///
445     /// ```
446     /// let mut v = kernel::kvec![1, 2, 3]?;
447     /// assert_eq!(v.remove(1)?, 2);
448     /// assert_eq!(v, [1, 3]);
449     /// # Ok::<(), Error>(())
450     /// ```
remove(&mut self, i: usize) -> Result<T, RemoveError>451     pub fn remove(&mut self, i: usize) -> Result<T, RemoveError> {
452         let value = {
453             let value_ref = self.get(i).ok_or(RemoveError)?;
454             // INVARIANT: This breaks the invariants by invalidating the value at index `i`, but we
455             // restore the invariants below.
456             // SAFETY: The value at index `i` is valid, because otherwise we would have already
457             // failed with `RemoveError`.
458             unsafe { ptr::read(value_ref) }
459         };
460 
461         // SAFETY: We checked that `i` is in-bounds.
462         let p = unsafe { self.as_mut_ptr().add(i) };
463 
464         // INVARIANT: After this call, the invalid value is at the last slot, so the Vec invariants
465         // are restored after the below call to `dec_len(1)`.
466         // SAFETY: `p.add(1).add(self.len - i - 1)` is `i+1+len-i-1 == len` elements after the
467         // beginning of the vector, so this is in-bounds of the vector's allocation.
468         unsafe { ptr::copy(p.add(1), p, self.len - i - 1) };
469 
470         // SAFETY: Since the check at the beginning of this call did not fail with `RemoveError`,
471         // the length is at least one.
472         unsafe { self.dec_len(1) };
473 
474         Ok(value)
475     }
476 
477     /// Creates a new [`Vec`] instance with at least the given capacity.
478     ///
479     /// # Examples
480     ///
481     /// ```
482     /// let v = KVec::<u32>::with_capacity(20, GFP_KERNEL)?;
483     ///
484     /// assert!(v.capacity() >= 20);
485     /// # Ok::<(), Error>(())
486     /// ```
with_capacity(capacity: usize, flags: Flags) -> Result<Self, AllocError>487     pub fn with_capacity(capacity: usize, flags: Flags) -> Result<Self, AllocError> {
488         let mut v = Vec::new();
489 
490         v.reserve(capacity, flags)?;
491 
492         Ok(v)
493     }
494 
495     /// Creates a `Vec<T, A>` from a pointer, a length and a capacity using the allocator `A`.
496     ///
497     /// # Examples
498     ///
499     /// ```
500     /// let mut v = kernel::kvec![1, 2, 3]?;
501     /// v.reserve(1, GFP_KERNEL)?;
502     ///
503     /// let (mut ptr, mut len, cap) = v.into_raw_parts();
504     ///
505     /// // SAFETY: We've just reserved memory for another element.
506     /// unsafe { ptr.add(len).write(4) };
507     /// len += 1;
508     ///
509     /// // SAFETY: We only wrote an additional element at the end of the `KVec`'s buffer and
510     /// // correspondingly increased the length of the `KVec` by one. Otherwise, we construct it
511     /// // from the exact same raw parts.
512     /// let v = unsafe { KVec::from_raw_parts(ptr, len, cap) };
513     ///
514     /// assert_eq!(v, [1, 2, 3, 4]);
515     ///
516     /// # Ok::<(), Error>(())
517     /// ```
518     ///
519     /// # Safety
520     ///
521     /// If `T` is a ZST:
522     ///
523     /// - `ptr` must be a dangling, well aligned pointer.
524     ///
525     /// Otherwise:
526     ///
527     /// - `ptr` must have been allocated with the allocator `A`.
528     /// - `ptr` must satisfy or exceed the alignment requirements of `T`.
529     /// - `ptr` must point to memory with a size of at least `size_of::<T>() * capacity` bytes.
530     /// - The allocated size in bytes must not be larger than `isize::MAX`.
531     /// - `length` must be less than or equal to `capacity`.
532     /// - The first `length` elements must be initialized values of type `T`.
533     ///
534     /// It is also valid to create an empty `Vec` passing a dangling pointer for `ptr` and zero for
535     /// `cap` and `len`.
from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self536     pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self {
537         let layout = if Self::is_zst() {
538             ArrayLayout::empty()
539         } else {
540             // SAFETY: By the safety requirements of this function, `capacity * size_of::<T>()` is
541             // smaller than `isize::MAX`.
542             unsafe { ArrayLayout::new_unchecked(capacity) }
543         };
544 
545         // INVARIANT: For ZSTs, we store an empty `ArrayLayout`, all other type invariants are
546         // covered by the safety requirements of this function.
547         Self {
548             // SAFETY: By the safety requirements, `ptr` is either dangling or pointing to a valid
549             // memory allocation, allocated with `A`.
550             ptr: unsafe { NonNull::new_unchecked(ptr) },
551             layout,
552             len: length,
553             _p: PhantomData::<A>,
554         }
555     }
556 
557     /// Consumes the `Vec<T, A>` and returns its raw components `pointer`, `length` and `capacity`.
558     ///
559     /// This will not run the destructor of the contained elements and for non-ZSTs the allocation
560     /// will stay alive indefinitely. Use [`Vec::from_raw_parts`] to recover the [`Vec`], drop the
561     /// elements and free the allocation, if any.
into_raw_parts(self) -> (*mut T, usize, usize)562     pub fn into_raw_parts(self) -> (*mut T, usize, usize) {
563         let mut me = ManuallyDrop::new(self);
564         let len = me.len();
565         let capacity = me.capacity();
566         let ptr = me.as_mut_ptr();
567         (ptr, len, capacity)
568     }
569 
570     /// Clears the vector, removing all values.
571     ///
572     /// Note that this method has no effect on the allocated capacity
573     /// of the vector.
574     ///
575     /// # Examples
576     ///
577     /// ```
578     /// let mut v = kernel::kvec![1, 2, 3]?;
579     ///
580     /// v.clear();
581     ///
582     /// assert!(v.is_empty());
583     /// # Ok::<(), Error>(())
584     /// ```
585     #[inline]
clear(&mut self)586     pub fn clear(&mut self) {
587         self.truncate(0);
588     }
589 
590     /// Ensures that the capacity exceeds the length by at least `additional` elements.
591     ///
592     /// # Examples
593     ///
594     /// ```
595     /// let mut v = KVec::new();
596     /// v.push(1, GFP_KERNEL)?;
597     ///
598     /// v.reserve(10, GFP_KERNEL)?;
599     /// let cap = v.capacity();
600     /// assert!(cap >= 10);
601     ///
602     /// v.reserve(10, GFP_KERNEL)?;
603     /// let new_cap = v.capacity();
604     /// assert_eq!(new_cap, cap);
605     ///
606     /// # Ok::<(), Error>(())
607     /// ```
reserve(&mut self, additional: usize, flags: Flags) -> Result<(), AllocError>608     pub fn reserve(&mut self, additional: usize, flags: Flags) -> Result<(), AllocError> {
609         let len = self.len();
610         let cap = self.capacity();
611 
612         if cap - len >= additional {
613             return Ok(());
614         }
615 
616         if Self::is_zst() {
617             // The capacity is already `usize::MAX` for ZSTs, we can't go higher.
618             return Err(AllocError);
619         }
620 
621         // We know that `cap <= isize::MAX` because of the type invariants of `Self`. So the
622         // multiplication by two won't overflow.
623         let new_cap = core::cmp::max(cap * 2, len.checked_add(additional).ok_or(AllocError)?);
624         let layout = ArrayLayout::new(new_cap).map_err(|_| AllocError)?;
625 
626         // SAFETY:
627         // - `ptr` is valid because it's either `None` or comes from a previous call to
628         //   `A::realloc`.
629         // - `self.layout` matches the `ArrayLayout` of the preceding allocation.
630         let ptr = unsafe {
631             A::realloc(
632                 Some(self.ptr.cast()),
633                 layout.into(),
634                 self.layout.into(),
635                 flags,
636             )?
637         };
638 
639         // INVARIANT:
640         // - `layout` is some `ArrayLayout::<T>`,
641         // - `ptr` has been created by `A::realloc` from `layout`.
642         self.ptr = ptr.cast();
643         self.layout = layout;
644 
645         Ok(())
646     }
647 
648     /// Shortens the vector, setting the length to `len` and drops the removed values.
649     /// If `len` is greater than or equal to the current length, this does nothing.
650     ///
651     /// This has no effect on the capacity and will not allocate.
652     ///
653     /// # Examples
654     ///
655     /// ```
656     /// let mut v = kernel::kvec![1, 2, 3]?;
657     /// v.truncate(1);
658     /// assert_eq!(v.len(), 1);
659     /// assert_eq!(&v, &[1]);
660     ///
661     /// # Ok::<(), Error>(())
662     /// ```
truncate(&mut self, len: usize)663     pub fn truncate(&mut self, len: usize) {
664         if let Some(count) = self.len().checked_sub(len) {
665             // SAFETY: `count` is `self.len() - len` so it is guaranteed to be less than or
666             // equal to `self.len()`.
667             let ptr: *mut [T] = unsafe { self.dec_len(count) };
668 
669             // SAFETY: the contract of `dec_len` guarantees that the elements in `ptr` are
670             // valid elements whose ownership has been transferred to the caller.
671             unsafe { ptr::drop_in_place(ptr) };
672         }
673     }
674 
675     /// Takes ownership of all items in this vector without consuming the allocation.
676     ///
677     /// # Examples
678     ///
679     /// ```
680     /// let mut v = kernel::kvec![0, 1, 2, 3]?;
681     ///
682     /// for (i, j) in v.drain_all().enumerate() {
683     ///     assert_eq!(i, j);
684     /// }
685     ///
686     /// assert!(v.capacity() >= 4);
687     /// # Ok::<(), Error>(())
688     /// ```
drain_all(&mut self) -> DrainAll<'_, T>689     pub fn drain_all(&mut self) -> DrainAll<'_, T> {
690         // SAFETY: This does not underflow the length.
691         let elems = unsafe { self.dec_len(self.len()) };
692         // INVARIANT: The first `len` elements of the spare capacity are valid values, and as we
693         // just set the length to zero, we may transfer ownership to the `DrainAll` object.
694         DrainAll {
695             elements: elems.iter_mut(),
696         }
697     }
698 
699     /// Removes all elements that don't match the provided closure.
700     ///
701     /// # Examples
702     ///
703     /// ```
704     /// let mut v = kernel::kvec![1, 2, 3, 4]?;
705     /// v.retain(|i| *i % 2 == 0);
706     /// assert_eq!(v, [2, 4]);
707     /// # Ok::<(), Error>(())
708     /// ```
retain(&mut self, mut f: impl FnMut(&mut T) -> bool)709     pub fn retain(&mut self, mut f: impl FnMut(&mut T) -> bool) {
710         let mut num_kept = 0;
711         let mut next_to_check = 0;
712         while let Some(to_check) = self.get_mut(next_to_check) {
713             if f(to_check) {
714                 self.swap(num_kept, next_to_check);
715                 num_kept += 1;
716             }
717             next_to_check += 1;
718         }
719         self.truncate(num_kept);
720     }
721 }
722 
723 impl<T: Clone, A: Allocator> Vec<T, A> {
724     /// Extend the vector by `n` clones of `value`.
extend_with(&mut self, n: usize, value: T, flags: Flags) -> Result<(), AllocError>725     pub fn extend_with(&mut self, n: usize, value: T, flags: Flags) -> Result<(), AllocError> {
726         if n == 0 {
727             return Ok(());
728         }
729 
730         self.reserve(n, flags)?;
731 
732         let spare = self.spare_capacity_mut();
733 
734         for item in spare.iter_mut().take(n - 1) {
735             item.write(value.clone());
736         }
737 
738         // We can write the last element directly without cloning needlessly.
739         spare[n - 1].write(value);
740 
741         // SAFETY:
742         // - `self.len() + n < self.capacity()` due to the call to reserve above,
743         // - the loop and the line above initialized the next `n` elements.
744         unsafe { self.inc_len(n) };
745 
746         Ok(())
747     }
748 
749     /// Pushes clones of the elements of slice into the [`Vec`] instance.
750     ///
751     /// # Examples
752     ///
753     /// ```
754     /// let mut v = KVec::new();
755     /// v.push(1, GFP_KERNEL)?;
756     ///
757     /// v.extend_from_slice(&[20, 30, 40], GFP_KERNEL)?;
758     /// assert_eq!(&v, &[1, 20, 30, 40]);
759     ///
760     /// v.extend_from_slice(&[50, 60], GFP_KERNEL)?;
761     /// assert_eq!(&v, &[1, 20, 30, 40, 50, 60]);
762     /// # Ok::<(), Error>(())
763     /// ```
extend_from_slice(&mut self, other: &[T], flags: Flags) -> Result<(), AllocError>764     pub fn extend_from_slice(&mut self, other: &[T], flags: Flags) -> Result<(), AllocError> {
765         self.reserve(other.len(), flags)?;
766         for (slot, item) in core::iter::zip(self.spare_capacity_mut(), other) {
767             slot.write(item.clone());
768         }
769 
770         // SAFETY:
771         // - `other.len()` spare entries have just been initialized, so it is safe to increase
772         //   the length by the same number.
773         // - `self.len() + other.len() <= self.capacity()` is guaranteed by the preceding `reserve`
774         //   call.
775         unsafe { self.inc_len(other.len()) };
776         Ok(())
777     }
778 
779     /// Create a new `Vec<T, A>` and extend it by `n` clones of `value`.
from_elem(value: T, n: usize, flags: Flags) -> Result<Self, AllocError>780     pub fn from_elem(value: T, n: usize, flags: Flags) -> Result<Self, AllocError> {
781         let mut v = Self::with_capacity(n, flags)?;
782 
783         v.extend_with(n, value, flags)?;
784 
785         Ok(v)
786     }
787 
788     /// Resizes the [`Vec`] so that `len` is equal to `new_len`.
789     ///
790     /// If `new_len` is smaller than `len`, the `Vec` is [`Vec::truncate`]d.
791     /// If `new_len` is larger, each new slot is filled with clones of `value`.
792     ///
793     /// # Examples
794     ///
795     /// ```
796     /// let mut v = kernel::kvec![1, 2, 3]?;
797     /// v.resize(1, 42, GFP_KERNEL)?;
798     /// assert_eq!(&v, &[1]);
799     ///
800     /// v.resize(3, 42, GFP_KERNEL)?;
801     /// assert_eq!(&v, &[1, 42, 42]);
802     ///
803     /// # Ok::<(), Error>(())
804     /// ```
resize(&mut self, new_len: usize, value: T, flags: Flags) -> Result<(), AllocError>805     pub fn resize(&mut self, new_len: usize, value: T, flags: Flags) -> Result<(), AllocError> {
806         match new_len.checked_sub(self.len()) {
807             Some(n) => self.extend_with(n, value, flags),
808             None => {
809                 self.truncate(new_len);
810                 Ok(())
811             }
812         }
813     }
814 }
815 
816 impl<T, A> Drop for Vec<T, A>
817 where
818     A: Allocator,
819 {
drop(&mut self)820     fn drop(&mut self) {
821         // SAFETY: `self.as_mut_ptr` is guaranteed to be valid by the type invariant.
822         unsafe {
823             ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut(
824                 self.as_mut_ptr(),
825                 self.len,
826             ))
827         };
828 
829         // SAFETY:
830         // - `self.ptr` was previously allocated with `A`.
831         // - `self.layout` matches the `ArrayLayout` of the preceding allocation.
832         unsafe { A::free(self.ptr.cast(), self.layout.into()) };
833     }
834 }
835 
836 impl<T, A, const N: usize> From<Box<[T; N], A>> for Vec<T, A>
837 where
838     A: Allocator,
839 {
from(b: Box<[T; N], A>) -> Vec<T, A>840     fn from(b: Box<[T; N], A>) -> Vec<T, A> {
841         let len = b.len();
842         let ptr = Box::into_raw(b);
843 
844         // SAFETY:
845         // - `b` has been allocated with `A`,
846         // - `ptr` fulfills the alignment requirements for `T`,
847         // - `ptr` points to memory with at least a size of `size_of::<T>() * len`,
848         // - all elements within `b` are initialized values of `T`,
849         // - `len` does not exceed `isize::MAX`.
850         unsafe { Vec::from_raw_parts(ptr as _, len, len) }
851     }
852 }
853 
854 impl<T> Default for KVec<T> {
855     #[inline]
default() -> Self856     fn default() -> Self {
857         Self::new()
858     }
859 }
860 
861 impl<T: fmt::Debug, A: Allocator> fmt::Debug for Vec<T, A> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result862     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
863         fmt::Debug::fmt(&**self, f)
864     }
865 }
866 
867 impl<T, A> Deref for Vec<T, A>
868 where
869     A: Allocator,
870 {
871     type Target = [T];
872 
873     #[inline]
deref(&self) -> &[T]874     fn deref(&self) -> &[T] {
875         // SAFETY: The memory behind `self.as_ptr()` is guaranteed to contain `self.len`
876         // initialized elements of type `T`.
877         unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
878     }
879 }
880 
881 impl<T, A> DerefMut for Vec<T, A>
882 where
883     A: Allocator,
884 {
885     #[inline]
deref_mut(&mut self) -> &mut [T]886     fn deref_mut(&mut self) -> &mut [T] {
887         // SAFETY: The memory behind `self.as_ptr()` is guaranteed to contain `self.len`
888         // initialized elements of type `T`.
889         unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
890     }
891 }
892 
893 impl<T: Eq, A> Eq for Vec<T, A> where A: Allocator {}
894 
895 impl<T, I: SliceIndex<[T]>, A> Index<I> for Vec<T, A>
896 where
897     A: Allocator,
898 {
899     type Output = I::Output;
900 
901     #[inline]
index(&self, index: I) -> &Self::Output902     fn index(&self, index: I) -> &Self::Output {
903         Index::index(&**self, index)
904     }
905 }
906 
907 impl<T, I: SliceIndex<[T]>, A> IndexMut<I> for Vec<T, A>
908 where
909     A: Allocator,
910 {
911     #[inline]
index_mut(&mut self, index: I) -> &mut Self::Output912     fn index_mut(&mut self, index: I) -> &mut Self::Output {
913         IndexMut::index_mut(&mut **self, index)
914     }
915 }
916 
917 macro_rules! impl_slice_eq {
918     ($([$($vars:tt)*] $lhs:ty, $rhs:ty,)*) => {
919         $(
920             impl<T, U, $($vars)*> PartialEq<$rhs> for $lhs
921             where
922                 T: PartialEq<U>,
923             {
924                 #[inline]
925                 fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] }
926             }
927         )*
928     }
929 }
930 
931 impl_slice_eq! {
932     [A1: Allocator, A2: Allocator] Vec<T, A1>, Vec<U, A2>,
933     [A: Allocator] Vec<T, A>, &[U],
934     [A: Allocator] Vec<T, A>, &mut [U],
935     [A: Allocator] &[T], Vec<U, A>,
936     [A: Allocator] &mut [T], Vec<U, A>,
937     [A: Allocator] Vec<T, A>, [U],
938     [A: Allocator] [T], Vec<U, A>,
939     [A: Allocator, const N: usize] Vec<T, A>, [U; N],
940     [A: Allocator, const N: usize] Vec<T, A>, &[U; N],
941 }
942 
943 impl<'a, T, A> IntoIterator for &'a Vec<T, A>
944 where
945     A: Allocator,
946 {
947     type Item = &'a T;
948     type IntoIter = slice::Iter<'a, T>;
949 
into_iter(self) -> Self::IntoIter950     fn into_iter(self) -> Self::IntoIter {
951         self.iter()
952     }
953 }
954 
955 impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec<T, A>
956 where
957     A: Allocator,
958 {
959     type Item = &'a mut T;
960     type IntoIter = slice::IterMut<'a, T>;
961 
into_iter(self) -> Self::IntoIter962     fn into_iter(self) -> Self::IntoIter {
963         self.iter_mut()
964     }
965 }
966 
967 /// An [`Iterator`] implementation for [`Vec`] that moves elements out of a vector.
968 ///
969 /// This structure is created by the [`Vec::into_iter`] method on [`Vec`] (provided by the
970 /// [`IntoIterator`] trait).
971 ///
972 /// # Examples
973 ///
974 /// ```
975 /// let v = kernel::kvec![0, 1, 2]?;
976 /// let iter = v.into_iter();
977 ///
978 /// # Ok::<(), Error>(())
979 /// ```
980 pub struct IntoIter<T, A: Allocator> {
981     ptr: *mut T,
982     buf: NonNull<T>,
983     len: usize,
984     layout: ArrayLayout<T>,
985     _p: PhantomData<A>,
986 }
987 
988 impl<T, A> IntoIter<T, A>
989 where
990     A: Allocator,
991 {
into_raw_parts(self) -> (*mut T, NonNull<T>, usize, usize)992     fn into_raw_parts(self) -> (*mut T, NonNull<T>, usize, usize) {
993         let me = ManuallyDrop::new(self);
994         let ptr = me.ptr;
995         let buf = me.buf;
996         let len = me.len;
997         let cap = me.layout.len();
998         (ptr, buf, len, cap)
999     }
1000 
1001     /// Same as `Iterator::collect` but specialized for `Vec`'s `IntoIter`.
1002     ///
1003     /// # Examples
1004     ///
1005     /// ```
1006     /// let v = kernel::kvec![1, 2, 3]?;
1007     /// let mut it = v.into_iter();
1008     ///
1009     /// assert_eq!(it.next(), Some(1));
1010     ///
1011     /// let v = it.collect(GFP_KERNEL);
1012     /// assert_eq!(v, [2, 3]);
1013     ///
1014     /// # Ok::<(), Error>(())
1015     /// ```
1016     ///
1017     /// # Implementation details
1018     ///
1019     /// Currently, we can't implement `FromIterator`. There are a couple of issues with this trait
1020     /// in the kernel, namely:
1021     ///
1022     /// - Rust's specialization feature is unstable. This prevents us to optimize for the special
1023     ///   case where `I::IntoIter` equals `Vec`'s `IntoIter` type.
1024     /// - We also can't use `I::IntoIter`'s type ID either to work around this, since `FromIterator`
1025     ///   doesn't require this type to be `'static`.
1026     /// - `FromIterator::from_iter` does return `Self` instead of `Result<Self, AllocError>`, hence
1027     ///   we can't properly handle allocation failures.
1028     /// - Neither `Iterator::collect` nor `FromIterator::from_iter` can handle additional allocation
1029     ///   flags.
1030     ///
1031     /// Instead, provide `IntoIter::collect`, such that we can at least convert a `IntoIter` into a
1032     /// `Vec` again.
1033     ///
1034     /// Note that `IntoIter::collect` doesn't require `Flags`, since it re-uses the existing backing
1035     /// buffer. However, this backing buffer may be shrunk to the actual count of elements.
collect(self, flags: Flags) -> Vec<T, A>1036     pub fn collect(self, flags: Flags) -> Vec<T, A> {
1037         let old_layout = self.layout;
1038         let (mut ptr, buf, len, mut cap) = self.into_raw_parts();
1039         let has_advanced = ptr != buf.as_ptr();
1040 
1041         if has_advanced {
1042             // Copy the contents we have advanced to at the beginning of the buffer.
1043             //
1044             // SAFETY:
1045             // - `ptr` is valid for reads of `len * size_of::<T>()` bytes,
1046             // - `buf.as_ptr()` is valid for writes of `len * size_of::<T>()` bytes,
1047             // - `ptr` and `buf.as_ptr()` are not be subject to aliasing restrictions relative to
1048             //   each other,
1049             // - both `ptr` and `buf.ptr()` are properly aligned.
1050             unsafe { ptr::copy(ptr, buf.as_ptr(), len) };
1051             ptr = buf.as_ptr();
1052 
1053             // SAFETY: `len` is guaranteed to be smaller than `self.layout.len()` by the type
1054             // invariant.
1055             let layout = unsafe { ArrayLayout::<T>::new_unchecked(len) };
1056 
1057             // SAFETY: `buf` points to the start of the backing buffer and `len` is guaranteed by
1058             // the type invariant to be smaller than `cap`. Depending on `realloc` this operation
1059             // may shrink the buffer or leave it as it is.
1060             ptr = match unsafe {
1061                 A::realloc(Some(buf.cast()), layout.into(), old_layout.into(), flags)
1062             } {
1063                 // If we fail to shrink, which likely can't even happen, continue with the existing
1064                 // buffer.
1065                 Err(_) => ptr,
1066                 Ok(ptr) => {
1067                     cap = len;
1068                     ptr.as_ptr().cast()
1069                 }
1070             };
1071         }
1072 
1073         // SAFETY: If the iterator has been advanced, the advanced elements have been copied to
1074         // the beginning of the buffer and `len` has been adjusted accordingly.
1075         //
1076         // - `ptr` is guaranteed to point to the start of the backing buffer.
1077         // - `cap` is either the original capacity or, after shrinking the buffer, equal to `len`.
1078         // - `alloc` is guaranteed to be unchanged since `into_iter` has been called on the original
1079         //   `Vec`.
1080         unsafe { Vec::from_raw_parts(ptr, len, cap) }
1081     }
1082 }
1083 
1084 impl<T, A> Iterator for IntoIter<T, A>
1085 where
1086     A: Allocator,
1087 {
1088     type Item = T;
1089 
1090     /// # Examples
1091     ///
1092     /// ```
1093     /// let v = kernel::kvec![1, 2, 3]?;
1094     /// let mut it = v.into_iter();
1095     ///
1096     /// assert_eq!(it.next(), Some(1));
1097     /// assert_eq!(it.next(), Some(2));
1098     /// assert_eq!(it.next(), Some(3));
1099     /// assert_eq!(it.next(), None);
1100     ///
1101     /// # Ok::<(), Error>(())
1102     /// ```
next(&mut self) -> Option<T>1103     fn next(&mut self) -> Option<T> {
1104         if self.len == 0 {
1105             return None;
1106         }
1107 
1108         let current = self.ptr;
1109 
1110         // SAFETY: We can't overflow; decreasing `self.len` by one every time we advance `self.ptr`
1111         // by one guarantees that.
1112         unsafe { self.ptr = self.ptr.add(1) };
1113 
1114         self.len -= 1;
1115 
1116         // SAFETY: `current` is guaranteed to point at a valid element within the buffer.
1117         Some(unsafe { current.read() })
1118     }
1119 
1120     /// # Examples
1121     ///
1122     /// ```
1123     /// let v: KVec<u32> = kernel::kvec![1, 2, 3]?;
1124     /// let mut iter = v.into_iter();
1125     /// let size = iter.size_hint().0;
1126     ///
1127     /// iter.next();
1128     /// assert_eq!(iter.size_hint().0, size - 1);
1129     ///
1130     /// iter.next();
1131     /// assert_eq!(iter.size_hint().0, size - 2);
1132     ///
1133     /// iter.next();
1134     /// assert_eq!(iter.size_hint().0, size - 3);
1135     ///
1136     /// # Ok::<(), Error>(())
1137     /// ```
size_hint(&self) -> (usize, Option<usize>)1138     fn size_hint(&self) -> (usize, Option<usize>) {
1139         (self.len, Some(self.len))
1140     }
1141 }
1142 
1143 impl<T, A> Drop for IntoIter<T, A>
1144 where
1145     A: Allocator,
1146 {
drop(&mut self)1147     fn drop(&mut self) {
1148         // SAFETY: `self.ptr` is guaranteed to be valid by the type invariant.
1149         unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.ptr, self.len)) };
1150 
1151         // SAFETY:
1152         // - `self.buf` was previously allocated with `A`.
1153         // - `self.layout` matches the `ArrayLayout` of the preceding allocation.
1154         unsafe { A::free(self.buf.cast(), self.layout.into()) };
1155     }
1156 }
1157 
1158 impl<T, A> IntoIterator for Vec<T, A>
1159 where
1160     A: Allocator,
1161 {
1162     type Item = T;
1163     type IntoIter = IntoIter<T, A>;
1164 
1165     /// Consumes the `Vec<T, A>` and creates an `Iterator`, which moves each value out of the
1166     /// vector (from start to end).
1167     ///
1168     /// # Examples
1169     ///
1170     /// ```
1171     /// let v = kernel::kvec![1, 2]?;
1172     /// let mut v_iter = v.into_iter();
1173     ///
1174     /// let first_element: Option<u32> = v_iter.next();
1175     ///
1176     /// assert_eq!(first_element, Some(1));
1177     /// assert_eq!(v_iter.next(), Some(2));
1178     /// assert_eq!(v_iter.next(), None);
1179     ///
1180     /// # Ok::<(), Error>(())
1181     /// ```
1182     ///
1183     /// ```
1184     /// let v = kernel::kvec![];
1185     /// let mut v_iter = v.into_iter();
1186     ///
1187     /// let first_element: Option<u32> = v_iter.next();
1188     ///
1189     /// assert_eq!(first_element, None);
1190     ///
1191     /// # Ok::<(), Error>(())
1192     /// ```
1193     #[inline]
into_iter(self) -> Self::IntoIter1194     fn into_iter(self) -> Self::IntoIter {
1195         let buf = self.ptr;
1196         let layout = self.layout;
1197         let (ptr, len, _) = self.into_raw_parts();
1198 
1199         IntoIter {
1200             ptr,
1201             buf,
1202             len,
1203             layout,
1204             _p: PhantomData::<A>,
1205         }
1206     }
1207 }
1208 
1209 /// An iterator that owns all items in a vector, but does not own its allocation.
1210 ///
1211 /// # Invariants
1212 ///
1213 /// Every `&mut T` returned by the iterator references a `T` that the iterator may take ownership
1214 /// of.
1215 pub struct DrainAll<'vec, T> {
1216     elements: slice::IterMut<'vec, T>,
1217 }
1218 
1219 impl<'vec, T> Iterator for DrainAll<'vec, T> {
1220     type Item = T;
1221 
next(&mut self) -> Option<T>1222     fn next(&mut self) -> Option<T> {
1223         let elem: *mut T = self.elements.next()?;
1224         // SAFETY: By the type invariants, we may take ownership of this value.
1225         Some(unsafe { elem.read() })
1226     }
1227 
size_hint(&self) -> (usize, Option<usize>)1228     fn size_hint(&self) -> (usize, Option<usize>) {
1229         self.elements.size_hint()
1230     }
1231 }
1232 
1233 impl<'vec, T> Drop for DrainAll<'vec, T> {
drop(&mut self)1234     fn drop(&mut self) {
1235         if core::mem::needs_drop::<T>() {
1236             let iter = core::mem::take(&mut self.elements);
1237             let ptr: *mut [T] = iter.into_slice();
1238             // SAFETY: By the type invariants, we own these values so we may destroy them.
1239             unsafe { ptr::drop_in_place(ptr) };
1240         }
1241     }
1242 }
1243 
1244 #[macros::kunit_tests(rust_kvec_kunit)]
1245 mod tests {
1246     use super::*;
1247     use crate::prelude::*;
1248 
1249     #[test]
test_kvec_retain()1250     fn test_kvec_retain() {
1251         /// Verify correctness for one specific function.
1252         #[expect(clippy::needless_range_loop)]
1253         fn verify(c: &[bool]) {
1254             let mut vec1: KVec<usize> = KVec::with_capacity(c.len(), GFP_KERNEL).unwrap();
1255             let mut vec2: KVec<usize> = KVec::with_capacity(c.len(), GFP_KERNEL).unwrap();
1256 
1257             for i in 0..c.len() {
1258                 vec1.push_within_capacity(i).unwrap();
1259                 if c[i] {
1260                     vec2.push_within_capacity(i).unwrap();
1261                 }
1262             }
1263 
1264             vec1.retain(|i| c[*i]);
1265 
1266             assert_eq!(vec1, vec2);
1267         }
1268 
1269         /// Add one to a binary integer represented as a boolean array.
1270         fn add(value: &mut [bool]) {
1271             let mut carry = true;
1272             for v in value {
1273                 let new_v = carry != *v;
1274                 carry = carry && *v;
1275                 *v = new_v;
1276             }
1277         }
1278 
1279         // This boolean array represents a function from index to boolean. We check that `retain`
1280         // behaves correctly for all possible boolean arrays of every possible length less than
1281         // ten.
1282         let mut func = KVec::with_capacity(10, GFP_KERNEL).unwrap();
1283         for len in 0..10 {
1284             for _ in 0u32..1u32 << len {
1285                 verify(&func);
1286                 add(&mut func);
1287             }
1288             func.push_within_capacity(false).unwrap();
1289         }
1290     }
1291 }
1292