kernel/alloc/
kvec.rs

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