kernel/alloc/
kvec.rs

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