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