Skip to main content

kernel/alloc/
kvec.rs

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