// SPDX-License-Identifier: GPL-2.012//! Implementation of [`Vec`].34use super::{5allocator::{KVmalloc, Kmalloc, Vmalloc, VmallocPageIter},6layout::ArrayLayout,7AllocError, Allocator, Box, Flags, NumaNode,8};9use crate::{10fmt,11page::AsPageIter,12};13use core::{14borrow::{Borrow, BorrowMut},15marker::PhantomData,16mem::{ManuallyDrop, MaybeUninit},17ops::Deref,18ops::DerefMut,19ops::Index,20ops::IndexMut,21ptr,22ptr::NonNull,23slice,24slice::SliceIndex,25};2627mod errors;28pub use self::errors::{InsertError, PushError, RemoveError};2930/// Create a [`KVec`] containing the arguments.31///32/// New memory is allocated with `GFP_KERNEL`.33///34/// # Examples35///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),+ $(,)?) => (60match $crate::alloc::KBox::new_uninit(GFP_KERNEL) {61Ok(b) => Ok($crate::alloc::KVec::from($crate::alloc::KBox::write(b, [$($x),+]))),62Err(e) => Err(e),63}64);65}6667/// 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. For73/// 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, the78/// capacity of the vector (the number of elements that currently fit into the vector), its length79/// (the number of elements that are currently stored in the vector) and the `Allocator` type used80/// to allocate (and free) the backing buffer.81///82/// A [`Vec`] can be deconstructed into and (re-)constructed from its previously named raw parts83/// and manually modified.84///85/// [`Vec`]'s backing buffer gets, if required, automatically increased (re-allocated) when elements86/// are added to the vector.87///88/// # Invariants89///90/// - `self.ptr` is always properly aligned and either points to memory allocated with `A` or, for91/// 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 vector96/// without re-allocation. For ZSTs `self.layout`'s capacity is zero. However, it is legal for the97/// 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 buffer102/// was allocated with (and must be freed with).103pub struct Vec<T, A: Allocator> {104ptr: 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 of108/// elements we can still store without reallocating.109layout: ArrayLayout<T>,110len: usize,111_p: PhantomData<A>,112}113114/// Type alias for [`Vec`] with a [`Kmalloc`] allocator.115///116/// # Examples117///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>;126127/// Type alias for [`Vec`] with a [`Vmalloc`] allocator.128///129/// # Examples130///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>;139140/// Type alias for [`Vec`] with a [`KVmalloc`] allocator.141///142/// # Examples143///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>;152153// SAFETY: `Vec` is `Send` if `T` is `Send` because `Vec` owns its elements.154unsafe impl<T, A> Send for Vec<T, A>155where156T: Send,157A: Allocator,158{159}160161// SAFETY: `Vec` is `Sync` if `T` is `Sync` because `Vec` owns its elements.162unsafe impl<T, A> Sync for Vec<T, A>163where164T: Sync,165A: Allocator,166{167}168169impl<T, A> Vec<T, A>170where171A: Allocator,172{173#[inline]174const fn is_zst() -> bool {175core::mem::size_of::<T>() == 0176}177178/// Returns the number of elements that can be stored within the vector without allocating179/// additional memory.180pub const fn capacity(&self) -> usize {181if const { Self::is_zst() } {182usize::MAX183} else {184self.layout.len()185}186}187188/// Returns the number of elements stored within the vector.189#[inline]190pub const fn len(&self) -> usize {191self.len192}193194/// Increments `self.len` by `additional`.195///196/// # Safety197///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]201pub const unsafe fn inc_len(&mut self, additional: usize) {202// Guaranteed by the type invariant to never underflow.203debug_assert!(additional <= self.capacity() - self.len());204// INVARIANT: By the safety requirements of this method this represents the exact number of205// elements stored within `self`.206self.len += additional;207}208209/// Decreases `self.len` by `count`.210///211/// Returns a mutable slice to the elements forgotten by the vector. It is the caller's212/// responsibility to drop these elements if necessary.213///214/// # Safety215///216/// - `count` must be less than or equal to `self.len`.217unsafe fn dec_len(&mut self, count: usize) -> &mut [T] {218debug_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 elements221// stored within `self`.222self.len -= count;223// SAFETY: The memory after `self.len()` is guaranteed to contain `count` initialized224// elements of type `T`.225unsafe { slice::from_raw_parts_mut(self.as_mut_ptr().add(self.len), count) }226}227228/// Returns a slice of the entire vector.229///230/// # Examples231///232/// ```233/// let mut v = KVec::new();234/// v.push(1, GFP_KERNEL)?;235/// v.push(2, GFP_KERNEL)?;236/// assert_eq!(v.as_slice(), &[1, 2]);237/// # Ok::<(), Error>(())238/// ```239#[inline]240pub fn as_slice(&self) -> &[T] {241self242}243244/// Returns a mutable slice of the entire vector.245#[inline]246pub fn as_mut_slice(&mut self) -> &mut [T] {247self248}249250/// Returns a mutable raw pointer to the vector's backing buffer, or, if `T` is a ZST, a251/// dangling raw pointer.252#[inline]253pub fn as_mut_ptr(&mut self) -> *mut T {254self.ptr.as_ptr()255}256257/// Returns a raw pointer to the vector's backing buffer, or, if `T` is a ZST, a dangling raw258/// pointer.259#[inline]260pub const fn as_ptr(&self) -> *const T {261self.ptr.as_ptr()262}263264/// Returns `true` if the vector contains no elements, `false` otherwise.265///266/// # Examples267///268/// ```269/// let mut v = KVec::new();270/// assert!(v.is_empty());271///272/// v.push(1, GFP_KERNEL);273/// assert!(!v.is_empty());274/// ```275#[inline]276pub const fn is_empty(&self) -> bool {277self.len() == 0278}279280/// Creates a new, empty `Vec<T, A>`.281///282/// This method does not allocate by itself.283#[inline]284pub const fn new() -> Self {285// INVARIANT: Since this is a new, empty `Vec` with no backing memory yet,286// - `ptr` is a properly aligned dangling pointer for type `T`,287// - `layout` is an empty `ArrayLayout` (zero capacity)288// - `len` is zero, since no elements can be or have been stored,289// - `A` is always valid.290Self {291ptr: NonNull::dangling(),292layout: ArrayLayout::empty(),293len: 0,294_p: PhantomData::<A>,295}296}297298/// Returns a slice of `MaybeUninit<T>` for the remaining spare capacity of the vector.299pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {300// SAFETY:301// - `self.len` is smaller than `self.capacity` by the type invariant and hence, the302// resulting pointer is guaranteed to be part of the same allocated object.303// - `self.len` can not overflow `isize`.304let ptr = unsafe { self.as_mut_ptr().add(self.len) }.cast::<MaybeUninit<T>>();305306// SAFETY: The memory between `self.len` and `self.capacity` is guaranteed to be allocated307// and valid, but uninitialized.308unsafe { slice::from_raw_parts_mut(ptr, self.capacity() - self.len) }309}310311/// Appends an element to the back of the [`Vec`] instance.312///313/// # Examples314///315/// ```316/// let mut v = KVec::new();317/// v.push(1, GFP_KERNEL)?;318/// assert_eq!(&v, &[1]);319///320/// v.push(2, GFP_KERNEL)?;321/// assert_eq!(&v, &[1, 2]);322/// # Ok::<(), Error>(())323/// ```324pub fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> {325self.reserve(1, flags)?;326// SAFETY: The call to `reserve` was successful, so the capacity is at least one greater327// than the length.328unsafe { self.push_within_capacity_unchecked(v) };329Ok(())330}331332/// Appends an element to the back of the [`Vec`] instance without reallocating.333///334/// Fails if the vector does not have capacity for the new element.335///336/// # Examples337///338/// ```339/// let mut v = KVec::with_capacity(10, GFP_KERNEL)?;340/// for i in 0..10 {341/// v.push_within_capacity(i)?;342/// }343///344/// assert!(v.push_within_capacity(10).is_err());345/// # Ok::<(), Error>(())346/// ```347pub fn push_within_capacity(&mut self, v: T) -> Result<(), PushError<T>> {348if self.len() < self.capacity() {349// SAFETY: The length is less than the capacity.350unsafe { self.push_within_capacity_unchecked(v) };351Ok(())352} else {353Err(PushError(v))354}355}356357/// Appends an element to the back of the [`Vec`] instance without reallocating.358///359/// # Safety360///361/// The length must be less than the capacity.362unsafe fn push_within_capacity_unchecked(&mut self, v: T) {363let spare = self.spare_capacity_mut();364365// SAFETY: By the safety requirements, `spare` is non-empty.366unsafe { spare.get_unchecked_mut(0) }.write(v);367368// SAFETY: We just initialised the first spare entry, so it is safe to increase the length369// by 1. We also know that the new length is <= capacity because the caller guarantees that370// the length is less than the capacity at the beginning of this function.371unsafe { self.inc_len(1) };372}373374/// Inserts an element at the given index in the [`Vec`] instance.375///376/// Fails if the vector does not have capacity for the new element. Panics if the index is out377/// of bounds.378///379/// # Examples380///381/// ```382/// use kernel::alloc::kvec::InsertError;383///384/// let mut v = KVec::with_capacity(5, GFP_KERNEL)?;385/// for i in 0..5 {386/// v.insert_within_capacity(0, i)?;387/// }388///389/// assert!(matches!(v.insert_within_capacity(0, 5), Err(InsertError::OutOfCapacity(_))));390/// assert!(matches!(v.insert_within_capacity(1000, 5), Err(InsertError::IndexOutOfBounds(_))));391/// assert_eq!(v, [4, 3, 2, 1, 0]);392/// # Ok::<(), Error>(())393/// ```394pub fn insert_within_capacity(395&mut self,396index: usize,397element: T,398) -> Result<(), InsertError<T>> {399let len = self.len();400if index > len {401return Err(InsertError::IndexOutOfBounds(element));402}403404if len >= self.capacity() {405return Err(InsertError::OutOfCapacity(element));406}407408// SAFETY: This is in bounds since `index <= len < capacity`.409let p = unsafe { self.as_mut_ptr().add(index) };410// INVARIANT: This breaks the Vec invariants by making `index` contain an invalid element,411// but we restore the invariants below.412// SAFETY: Both the src and dst ranges end no later than one element after the length.413// Since the length is less than the capacity, both ranges are in bounds of the allocation.414unsafe { ptr::copy(p, p.add(1), len - index) };415// INVARIANT: This restores the Vec invariants.416// SAFETY: The pointer is in-bounds of the allocation.417unsafe { ptr::write(p, element) };418// SAFETY: Index `len` contains a valid element due to the above copy and write.419unsafe { self.inc_len(1) };420Ok(())421}422423/// Removes the last element from a vector and returns it, or `None` if it is empty.424///425/// # Examples426///427/// ```428/// let mut v = KVec::new();429/// v.push(1, GFP_KERNEL)?;430/// v.push(2, GFP_KERNEL)?;431/// assert_eq!(&v, &[1, 2]);432///433/// assert_eq!(v.pop(), Some(2));434/// assert_eq!(v.pop(), Some(1));435/// assert_eq!(v.pop(), None);436/// # Ok::<(), Error>(())437/// ```438pub fn pop(&mut self) -> Option<T> {439if self.is_empty() {440return None;441}442443let removed: *mut T = {444// SAFETY: We just checked that the length is at least one.445let slice = unsafe { self.dec_len(1) };446// SAFETY: The argument to `dec_len` was 1 so this returns a slice of length 1.447unsafe { slice.get_unchecked_mut(0) }448};449450// SAFETY: The guarantees of `dec_len` allow us to take ownership of this value.451Some(unsafe { removed.read() })452}453454/// Removes the element at the given index.455///456/// # Examples457///458/// ```459/// let mut v = kernel::kvec![1, 2, 3]?;460/// assert_eq!(v.remove(1)?, 2);461/// assert_eq!(v, [1, 3]);462/// # Ok::<(), Error>(())463/// ```464pub fn remove(&mut self, i: usize) -> Result<T, RemoveError> {465let value = {466let value_ref = self.get(i).ok_or(RemoveError)?;467// INVARIANT: This breaks the invariants by invalidating the value at index `i`, but we468// restore the invariants below.469// SAFETY: The value at index `i` is valid, because otherwise we would have already470// failed with `RemoveError`.471unsafe { ptr::read(value_ref) }472};473474// SAFETY: We checked that `i` is in-bounds.475let p = unsafe { self.as_mut_ptr().add(i) };476477// INVARIANT: After this call, the invalid value is at the last slot, so the Vec invariants478// are restored after the below call to `dec_len(1)`.479// SAFETY: `p.add(1).add(self.len - i - 1)` is `i+1+len-i-1 == len` elements after the480// beginning of the vector, so this is in-bounds of the vector's allocation.481unsafe { ptr::copy(p.add(1), p, self.len - i - 1) };482483// SAFETY: Since the check at the beginning of this call did not fail with `RemoveError`,484// the length is at least one.485unsafe { self.dec_len(1) };486487Ok(value)488}489490/// Creates a new [`Vec`] instance with at least the given capacity.491///492/// # Examples493///494/// ```495/// let v = KVec::<u32>::with_capacity(20, GFP_KERNEL)?;496///497/// assert!(v.capacity() >= 20);498/// # Ok::<(), Error>(())499/// ```500pub fn with_capacity(capacity: usize, flags: Flags) -> Result<Self, AllocError> {501let mut v = Vec::new();502503v.reserve(capacity, flags)?;504505Ok(v)506}507508/// Creates a `Vec<T, A>` from a pointer, a length and a capacity using the allocator `A`.509///510/// # Examples511///512/// ```513/// let mut v = kernel::kvec![1, 2, 3]?;514/// v.reserve(1, GFP_KERNEL)?;515///516/// let (mut ptr, mut len, cap) = v.into_raw_parts();517///518/// // SAFETY: We've just reserved memory for another element.519/// unsafe { ptr.add(len).write(4) };520/// len += 1;521///522/// // SAFETY: We only wrote an additional element at the end of the `KVec`'s buffer and523/// // correspondingly increased the length of the `KVec` by one. Otherwise, we construct it524/// // from the exact same raw parts.525/// let v = unsafe { KVec::from_raw_parts(ptr, len, cap) };526///527/// assert_eq!(v, [1, 2, 3, 4]);528///529/// # Ok::<(), Error>(())530/// ```531///532/// # Safety533///534/// If `T` is a ZST:535///536/// - `ptr` must be a dangling, well aligned pointer.537///538/// Otherwise:539///540/// - `ptr` must have been allocated with the allocator `A`.541/// - `ptr` must satisfy or exceed the alignment requirements of `T`.542/// - `ptr` must point to memory with a size of at least `size_of::<T>() * capacity` bytes.543/// - The allocated size in bytes must not be larger than `isize::MAX`.544/// - `length` must be less than or equal to `capacity`.545/// - The first `length` elements must be initialized values of type `T`.546///547/// It is also valid to create an empty `Vec` passing a dangling pointer for `ptr` and zero for548/// `cap` and `len`.549pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self {550let layout = if Self::is_zst() {551ArrayLayout::empty()552} else {553// SAFETY: By the safety requirements of this function, `capacity * size_of::<T>()` is554// smaller than `isize::MAX`.555unsafe { ArrayLayout::new_unchecked(capacity) }556};557558// INVARIANT: For ZSTs, we store an empty `ArrayLayout`, all other type invariants are559// covered by the safety requirements of this function.560Self {561// SAFETY: By the safety requirements, `ptr` is either dangling or pointing to a valid562// memory allocation, allocated with `A`.563ptr: unsafe { NonNull::new_unchecked(ptr) },564layout,565len: length,566_p: PhantomData::<A>,567}568}569570/// Consumes the `Vec<T, A>` and returns its raw components `pointer`, `length` and `capacity`.571///572/// This will not run the destructor of the contained elements and for non-ZSTs the allocation573/// will stay alive indefinitely. Use [`Vec::from_raw_parts`] to recover the [`Vec`], drop the574/// elements and free the allocation, if any.575pub fn into_raw_parts(self) -> (*mut T, usize, usize) {576let mut me = ManuallyDrop::new(self);577let len = me.len();578let capacity = me.capacity();579let ptr = me.as_mut_ptr();580(ptr, len, capacity)581}582583/// Clears the vector, removing all values.584///585/// Note that this method has no effect on the allocated capacity586/// of the vector.587///588/// # Examples589///590/// ```591/// let mut v = kernel::kvec![1, 2, 3]?;592///593/// v.clear();594///595/// assert!(v.is_empty());596/// # Ok::<(), Error>(())597/// ```598#[inline]599pub fn clear(&mut self) {600self.truncate(0);601}602603/// Ensures that the capacity exceeds the length by at least `additional` elements.604///605/// # Examples606///607/// ```608/// let mut v = KVec::new();609/// v.push(1, GFP_KERNEL)?;610///611/// v.reserve(10, GFP_KERNEL)?;612/// let cap = v.capacity();613/// assert!(cap >= 10);614///615/// v.reserve(10, GFP_KERNEL)?;616/// let new_cap = v.capacity();617/// assert_eq!(new_cap, cap);618///619/// # Ok::<(), Error>(())620/// ```621pub fn reserve(&mut self, additional: usize, flags: Flags) -> Result<(), AllocError> {622let len = self.len();623let cap = self.capacity();624625if cap - len >= additional {626return Ok(());627}628629if Self::is_zst() {630// The capacity is already `usize::MAX` for ZSTs, we can't go higher.631return Err(AllocError);632}633634// We know that `cap <= isize::MAX` because of the type invariants of `Self`. So the635// multiplication by two won't overflow.636let new_cap = core::cmp::max(cap * 2, len.checked_add(additional).ok_or(AllocError)?);637let layout = ArrayLayout::new(new_cap).map_err(|_| AllocError)?;638639// SAFETY:640// - `ptr` is valid because it's either `None` or comes from a previous call to641// `A::realloc`.642// - `self.layout` matches the `ArrayLayout` of the preceding allocation.643let ptr = unsafe {644A::realloc(645Some(self.ptr.cast()),646layout.into(),647self.layout.into(),648flags,649NumaNode::NO_NODE,650)?651};652653// INVARIANT:654// - `layout` is some `ArrayLayout::<T>`,655// - `ptr` has been created by `A::realloc` from `layout`.656self.ptr = ptr.cast();657self.layout = layout;658659Ok(())660}661662/// Shortens the vector, setting the length to `len` and drops the removed values.663/// If `len` is greater than or equal to the current length, this does nothing.664///665/// This has no effect on the capacity and will not allocate.666///667/// # Examples668///669/// ```670/// let mut v = kernel::kvec![1, 2, 3]?;671/// v.truncate(1);672/// assert_eq!(v.len(), 1);673/// assert_eq!(&v, &[1]);674///675/// # Ok::<(), Error>(())676/// ```677pub fn truncate(&mut self, len: usize) {678if let Some(count) = self.len().checked_sub(len) {679// SAFETY: `count` is `self.len() - len` so it is guaranteed to be less than or680// equal to `self.len()`.681let ptr: *mut [T] = unsafe { self.dec_len(count) };682683// SAFETY: the contract of `dec_len` guarantees that the elements in `ptr` are684// valid elements whose ownership has been transferred to the caller.685unsafe { ptr::drop_in_place(ptr) };686}687}688689/// Takes ownership of all items in this vector without consuming the allocation.690///691/// # Examples692///693/// ```694/// let mut v = kernel::kvec![0, 1, 2, 3]?;695///696/// for (i, j) in v.drain_all().enumerate() {697/// assert_eq!(i, j);698/// }699///700/// assert!(v.capacity() >= 4);701/// # Ok::<(), Error>(())702/// ```703pub fn drain_all(&mut self) -> DrainAll<'_, T> {704// SAFETY: This does not underflow the length.705let elems = unsafe { self.dec_len(self.len()) };706// INVARIANT: The first `len` elements of the spare capacity are valid values, and as we707// just set the length to zero, we may transfer ownership to the `DrainAll` object.708DrainAll {709elements: elems.iter_mut(),710}711}712713/// Removes all elements that don't match the provided closure.714///715/// # Examples716///717/// ```718/// let mut v = kernel::kvec![1, 2, 3, 4]?;719/// v.retain(|i| *i % 2 == 0);720/// assert_eq!(v, [2, 4]);721/// # Ok::<(), Error>(())722/// ```723pub fn retain(&mut self, mut f: impl FnMut(&mut T) -> bool) {724let mut num_kept = 0;725let mut next_to_check = 0;726while let Some(to_check) = self.get_mut(next_to_check) {727if f(to_check) {728self.swap(num_kept, next_to_check);729num_kept += 1;730}731next_to_check += 1;732}733self.truncate(num_kept);734}735}736737impl<T: Clone, A: Allocator> Vec<T, A> {738/// Extend the vector by `n` clones of `value`.739pub fn extend_with(&mut self, n: usize, value: T, flags: Flags) -> Result<(), AllocError> {740if n == 0 {741return Ok(());742}743744self.reserve(n, flags)?;745746let spare = self.spare_capacity_mut();747748for item in spare.iter_mut().take(n - 1) {749item.write(value.clone());750}751752// We can write the last element directly without cloning needlessly.753spare[n - 1].write(value);754755// SAFETY:756// - `self.len() + n < self.capacity()` due to the call to reserve above,757// - the loop and the line above initialized the next `n` elements.758unsafe { self.inc_len(n) };759760Ok(())761}762763/// Pushes clones of the elements of slice into the [`Vec`] instance.764///765/// # Examples766///767/// ```768/// let mut v = KVec::new();769/// v.push(1, GFP_KERNEL)?;770///771/// v.extend_from_slice(&[20, 30, 40], GFP_KERNEL)?;772/// assert_eq!(&v, &[1, 20, 30, 40]);773///774/// v.extend_from_slice(&[50, 60], GFP_KERNEL)?;775/// assert_eq!(&v, &[1, 20, 30, 40, 50, 60]);776/// # Ok::<(), Error>(())777/// ```778pub fn extend_from_slice(&mut self, other: &[T], flags: Flags) -> Result<(), AllocError> {779self.reserve(other.len(), flags)?;780for (slot, item) in core::iter::zip(self.spare_capacity_mut(), other) {781slot.write(item.clone());782}783784// SAFETY:785// - `other.len()` spare entries have just been initialized, so it is safe to increase786// the length by the same number.787// - `self.len() + other.len() <= self.capacity()` is guaranteed by the preceding `reserve`788// call.789unsafe { self.inc_len(other.len()) };790Ok(())791}792793/// Create a new `Vec<T, A>` and extend it by `n` clones of `value`.794pub fn from_elem(value: T, n: usize, flags: Flags) -> Result<Self, AllocError> {795let mut v = Self::with_capacity(n, flags)?;796797v.extend_with(n, value, flags)?;798799Ok(v)800}801802/// Resizes the [`Vec`] so that `len` is equal to `new_len`.803///804/// If `new_len` is smaller than `len`, the `Vec` is [`Vec::truncate`]d.805/// If `new_len` is larger, each new slot is filled with clones of `value`.806///807/// # Examples808///809/// ```810/// let mut v = kernel::kvec![1, 2, 3]?;811/// v.resize(1, 42, GFP_KERNEL)?;812/// assert_eq!(&v, &[1]);813///814/// v.resize(3, 42, GFP_KERNEL)?;815/// assert_eq!(&v, &[1, 42, 42]);816///817/// # Ok::<(), Error>(())818/// ```819pub fn resize(&mut self, new_len: usize, value: T, flags: Flags) -> Result<(), AllocError> {820match new_len.checked_sub(self.len()) {821Some(n) => self.extend_with(n, value, flags),822None => {823self.truncate(new_len);824Ok(())825}826}827}828}829830impl<T, A> Drop for Vec<T, A>831where832A: Allocator,833{834fn drop(&mut self) {835// SAFETY: `self.as_mut_ptr` is guaranteed to be valid by the type invariant.836unsafe {837ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut(838self.as_mut_ptr(),839self.len,840))841};842843// SAFETY:844// - `self.ptr` was previously allocated with `A`.845// - `self.layout` matches the `ArrayLayout` of the preceding allocation.846unsafe { A::free(self.ptr.cast(), self.layout.into()) };847}848}849850impl<T, A, const N: usize> From<Box<[T; N], A>> for Vec<T, A>851where852A: Allocator,853{854fn from(b: Box<[T; N], A>) -> Vec<T, A> {855let len = b.len();856let ptr = Box::into_raw(b);857858// SAFETY:859// - `b` has been allocated with `A`,860// - `ptr` fulfills the alignment requirements for `T`,861// - `ptr` points to memory with at least a size of `size_of::<T>() * len`,862// - all elements within `b` are initialized values of `T`,863// - `len` does not exceed `isize::MAX`.864unsafe { Vec::from_raw_parts(ptr.cast(), len, len) }865}866}867868impl<T, A: Allocator> Default for Vec<T, A> {869#[inline]870fn default() -> Self {871Self::new()872}873}874875impl<T: fmt::Debug, A: Allocator> fmt::Debug for Vec<T, A> {876fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {877fmt::Debug::fmt(&**self, f)878}879}880881impl<T, A> Deref for Vec<T, A>882where883A: Allocator,884{885type Target = [T];886887#[inline]888fn deref(&self) -> &[T] {889// SAFETY: The memory behind `self.as_ptr()` is guaranteed to contain `self.len`890// initialized elements of type `T`.891unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }892}893}894895impl<T, A> DerefMut for Vec<T, A>896where897A: Allocator,898{899#[inline]900fn deref_mut(&mut self) -> &mut [T] {901// SAFETY: The memory behind `self.as_ptr()` is guaranteed to contain `self.len`902// initialized elements of type `T`.903unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }904}905}906907/// # Examples908///909/// ```910/// # use core::borrow::Borrow;911/// struct Foo<B: Borrow<[u32]>>(B);912///913/// // Owned array.914/// let owned_array = Foo([1, 2, 3]);915///916/// // Owned vector.917/// let owned_vec = Foo(KVec::from_elem(0, 3, GFP_KERNEL)?);918///919/// let arr = [1, 2, 3];920/// // Borrowed slice from `arr`.921/// let borrowed_slice = Foo(&arr[..]);922/// # Ok::<(), Error>(())923/// ```924impl<T, A> Borrow<[T]> for Vec<T, A>925where926A: Allocator,927{928fn borrow(&self) -> &[T] {929self.as_slice()930}931}932933/// # Examples934///935/// ```936/// # use core::borrow::BorrowMut;937/// struct Foo<B: BorrowMut<[u32]>>(B);938///939/// // Owned array.940/// let owned_array = Foo([1, 2, 3]);941///942/// // Owned vector.943/// let owned_vec = Foo(KVec::from_elem(0, 3, GFP_KERNEL)?);944///945/// let mut arr = [1, 2, 3];946/// // Borrowed slice from `arr`.947/// let borrowed_slice = Foo(&mut arr[..]);948/// # Ok::<(), Error>(())949/// ```950impl<T, A> BorrowMut<[T]> for Vec<T, A>951where952A: Allocator,953{954fn borrow_mut(&mut self) -> &mut [T] {955self.as_mut_slice()956}957}958959impl<T: Eq, A> Eq for Vec<T, A> where A: Allocator {}960961impl<T, I: SliceIndex<[T]>, A> Index<I> for Vec<T, A>962where963A: Allocator,964{965type Output = I::Output;966967#[inline]968fn index(&self, index: I) -> &Self::Output {969Index::index(&**self, index)970}971}972973impl<T, I: SliceIndex<[T]>, A> IndexMut<I> for Vec<T, A>974where975A: Allocator,976{977#[inline]978fn index_mut(&mut self, index: I) -> &mut Self::Output {979IndexMut::index_mut(&mut **self, index)980}981}982983macro_rules! impl_slice_eq {984($([$($vars:tt)*] $lhs:ty, $rhs:ty,)*) => {985$(986impl<T, U, $($vars)*> PartialEq<$rhs> for $lhs987where988T: PartialEq<U>,989{990#[inline]991fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] }992}993)*994}995}996997impl_slice_eq! {998[A1: Allocator, A2: Allocator] Vec<T, A1>, Vec<U, A2>,999[A: Allocator] Vec<T, A>, &[U],1000[A: Allocator] Vec<T, A>, &mut [U],1001[A: Allocator] &[T], Vec<U, A>,1002[A: Allocator] &mut [T], Vec<U, A>,1003[A: Allocator] Vec<T, A>, [U],1004[A: Allocator] [T], Vec<U, A>,1005[A: Allocator, const N: usize] Vec<T, A>, [U; N],1006[A: Allocator, const N: usize] Vec<T, A>, &[U; N],1007}10081009impl<'a, T, A> IntoIterator for &'a Vec<T, A>1010where1011A: Allocator,1012{1013type Item = &'a T;1014type IntoIter = slice::Iter<'a, T>;10151016fn into_iter(self) -> Self::IntoIter {1017self.iter()1018}1019}10201021impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec<T, A>1022where1023A: Allocator,1024{1025type Item = &'a mut T;1026type IntoIter = slice::IterMut<'a, T>;10271028fn into_iter(self) -> Self::IntoIter {1029self.iter_mut()1030}1031}10321033/// # Examples1034///1035/// ```1036/// # use kernel::prelude::*;1037/// use kernel::alloc::allocator::VmallocPageIter;1038/// use kernel::page::{AsPageIter, PAGE_SIZE};1039///1040/// let mut vec = VVec::<u8>::new();1041///1042/// assert!(vec.page_iter().next().is_none());1043///1044/// vec.reserve(PAGE_SIZE, GFP_KERNEL)?;1045///1046/// let page = vec.page_iter().next().expect("At least one page should be available.\n");1047///1048/// // SAFETY: There is no concurrent read or write to the same page.1049/// unsafe { page.fill_zero_raw(0, PAGE_SIZE)? };1050/// # Ok::<(), Error>(())1051/// ```1052impl<T> AsPageIter for VVec<T> {1053type Iter<'a>1054= VmallocPageIter<'a>1055where1056T: 'a;10571058fn page_iter(&mut self) -> Self::Iter<'_> {1059let ptr = self.ptr.cast();1060let size = self.layout.size();10611062// SAFETY:1063// - `ptr` is a valid pointer to the beginning of a `Vmalloc` allocation.1064// - `ptr` is guaranteed to be valid for the lifetime of `'a`.1065// - `size` is the size of the `Vmalloc` allocation `ptr` points to.1066unsafe { VmallocPageIter::new(ptr, size) }1067}1068}10691070/// An [`Iterator`] implementation for [`Vec`] that moves elements out of a vector.1071///1072/// This structure is created by the [`Vec::into_iter`] method on [`Vec`] (provided by the1073/// [`IntoIterator`] trait).1074///1075/// # Examples1076///1077/// ```1078/// let v = kernel::kvec![0, 1, 2]?;1079/// let iter = v.into_iter();1080///1081/// # Ok::<(), Error>(())1082/// ```1083pub struct IntoIter<T, A: Allocator> {1084ptr: *mut T,1085buf: NonNull<T>,1086len: usize,1087layout: ArrayLayout<T>,1088_p: PhantomData<A>,1089}10901091impl<T, A> IntoIter<T, A>1092where1093A: Allocator,1094{1095fn into_raw_parts(self) -> (*mut T, NonNull<T>, usize, usize) {1096let me = ManuallyDrop::new(self);1097let ptr = me.ptr;1098let buf = me.buf;1099let len = me.len;1100let cap = me.layout.len();1101(ptr, buf, len, cap)1102}11031104/// Same as `Iterator::collect` but specialized for `Vec`'s `IntoIter`.1105///1106/// # Examples1107///1108/// ```1109/// let v = kernel::kvec![1, 2, 3]?;1110/// let mut it = v.into_iter();1111///1112/// assert_eq!(it.next(), Some(1));1113///1114/// let v = it.collect(GFP_KERNEL);1115/// assert_eq!(v, [2, 3]);1116///1117/// # Ok::<(), Error>(())1118/// ```1119///1120/// # Implementation details1121///1122/// Currently, we can't implement `FromIterator`. There are a couple of issues with this trait1123/// in the kernel, namely:1124///1125/// - Rust's specialization feature is unstable. This prevents us to optimize for the special1126/// case where `I::IntoIter` equals `Vec`'s `IntoIter` type.1127/// - We also can't use `I::IntoIter`'s type ID either to work around this, since `FromIterator`1128/// doesn't require this type to be `'static`.1129/// - `FromIterator::from_iter` does return `Self` instead of `Result<Self, AllocError>`, hence1130/// we can't properly handle allocation failures.1131/// - Neither `Iterator::collect` nor `FromIterator::from_iter` can handle additional allocation1132/// flags.1133///1134/// Instead, provide `IntoIter::collect`, such that we can at least convert a `IntoIter` into a1135/// `Vec` again.1136///1137/// Note that `IntoIter::collect` doesn't require `Flags`, since it re-uses the existing backing1138/// buffer. However, this backing buffer may be shrunk to the actual count of elements.1139pub fn collect(self, flags: Flags) -> Vec<T, A> {1140let old_layout = self.layout;1141let (mut ptr, buf, len, mut cap) = self.into_raw_parts();1142let has_advanced = ptr != buf.as_ptr();11431144if has_advanced {1145// Copy the contents we have advanced to at the beginning of the buffer.1146//1147// SAFETY:1148// - `ptr` is valid for reads of `len * size_of::<T>()` bytes,1149// - `buf.as_ptr()` is valid for writes of `len * size_of::<T>()` bytes,1150// - `ptr` and `buf.as_ptr()` are not be subject to aliasing restrictions relative to1151// each other,1152// - both `ptr` and `buf.ptr()` are properly aligned.1153unsafe { ptr::copy(ptr, buf.as_ptr(), len) };1154ptr = buf.as_ptr();11551156// SAFETY: `len` is guaranteed to be smaller than `self.layout.len()` by the type1157// invariant.1158let layout = unsafe { ArrayLayout::<T>::new_unchecked(len) };11591160// SAFETY: `buf` points to the start of the backing buffer and `len` is guaranteed by1161// the type invariant to be smaller than `cap`. Depending on `realloc` this operation1162// may shrink the buffer or leave it as it is.1163ptr = match unsafe {1164A::realloc(1165Some(buf.cast()),1166layout.into(),1167old_layout.into(),1168flags,1169NumaNode::NO_NODE,1170)1171} {1172// If we fail to shrink, which likely can't even happen, continue with the existing1173// buffer.1174Err(_) => ptr,1175Ok(ptr) => {1176cap = len;1177ptr.as_ptr().cast()1178}1179};1180}11811182// SAFETY: If the iterator has been advanced, the advanced elements have been copied to1183// the beginning of the buffer and `len` has been adjusted accordingly.1184//1185// - `ptr` is guaranteed to point to the start of the backing buffer.1186// - `cap` is either the original capacity or, after shrinking the buffer, equal to `len`.1187// - `alloc` is guaranteed to be unchanged since `into_iter` has been called on the original1188// `Vec`.1189unsafe { Vec::from_raw_parts(ptr, len, cap) }1190}1191}11921193impl<T, A> Iterator for IntoIter<T, A>1194where1195A: Allocator,1196{1197type Item = T;11981199/// # Examples1200///1201/// ```1202/// let v = kernel::kvec![1, 2, 3]?;1203/// let mut it = v.into_iter();1204///1205/// assert_eq!(it.next(), Some(1));1206/// assert_eq!(it.next(), Some(2));1207/// assert_eq!(it.next(), Some(3));1208/// assert_eq!(it.next(), None);1209///1210/// # Ok::<(), Error>(())1211/// ```1212fn next(&mut self) -> Option<T> {1213if self.len == 0 {1214return None;1215}12161217let current = self.ptr;12181219// SAFETY: We can't overflow; decreasing `self.len` by one every time we advance `self.ptr`1220// by one guarantees that.1221unsafe { self.ptr = self.ptr.add(1) };12221223self.len -= 1;12241225// SAFETY: `current` is guaranteed to point at a valid element within the buffer.1226Some(unsafe { current.read() })1227}12281229/// # Examples1230///1231/// ```1232/// let v: KVec<u32> = kernel::kvec![1, 2, 3]?;1233/// let mut iter = v.into_iter();1234/// let size = iter.size_hint().0;1235///1236/// iter.next();1237/// assert_eq!(iter.size_hint().0, size - 1);1238///1239/// iter.next();1240/// assert_eq!(iter.size_hint().0, size - 2);1241///1242/// iter.next();1243/// assert_eq!(iter.size_hint().0, size - 3);1244///1245/// # Ok::<(), Error>(())1246/// ```1247fn size_hint(&self) -> (usize, Option<usize>) {1248(self.len, Some(self.len))1249}1250}12511252impl<T, A> Drop for IntoIter<T, A>1253where1254A: Allocator,1255{1256fn drop(&mut self) {1257// SAFETY: `self.ptr` is guaranteed to be valid by the type invariant.1258unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.ptr, self.len)) };12591260// SAFETY:1261// - `self.buf` was previously allocated with `A`.1262// - `self.layout` matches the `ArrayLayout` of the preceding allocation.1263unsafe { A::free(self.buf.cast(), self.layout.into()) };1264}1265}12661267impl<T, A> IntoIterator for Vec<T, A>1268where1269A: Allocator,1270{1271type Item = T;1272type IntoIter = IntoIter<T, A>;12731274/// Consumes the `Vec<T, A>` and creates an `Iterator`, which moves each value out of the1275/// vector (from start to end).1276///1277/// # Examples1278///1279/// ```1280/// let v = kernel::kvec![1, 2]?;1281/// let mut v_iter = v.into_iter();1282///1283/// let first_element: Option<u32> = v_iter.next();1284///1285/// assert_eq!(first_element, Some(1));1286/// assert_eq!(v_iter.next(), Some(2));1287/// assert_eq!(v_iter.next(), None);1288///1289/// # Ok::<(), Error>(())1290/// ```1291///1292/// ```1293/// let v = kernel::kvec![];1294/// let mut v_iter = v.into_iter();1295///1296/// let first_element: Option<u32> = v_iter.next();1297///1298/// assert_eq!(first_element, None);1299///1300/// # Ok::<(), Error>(())1301/// ```1302#[inline]1303fn into_iter(self) -> Self::IntoIter {1304let buf = self.ptr;1305let layout = self.layout;1306let (ptr, len, _) = self.into_raw_parts();13071308IntoIter {1309ptr,1310buf,1311len,1312layout,1313_p: PhantomData::<A>,1314}1315}1316}13171318/// An iterator that owns all items in a vector, but does not own its allocation.1319///1320/// # Invariants1321///1322/// Every `&mut T` returned by the iterator references a `T` that the iterator may take ownership1323/// of.1324pub struct DrainAll<'vec, T> {1325elements: slice::IterMut<'vec, T>,1326}13271328impl<'vec, T> Iterator for DrainAll<'vec, T> {1329type Item = T;13301331fn next(&mut self) -> Option<T> {1332let elem: *mut T = self.elements.next()?;1333// SAFETY: By the type invariants, we may take ownership of this value.1334Some(unsafe { elem.read() })1335}13361337fn size_hint(&self) -> (usize, Option<usize>) {1338self.elements.size_hint()1339}1340}13411342impl<'vec, T> Drop for DrainAll<'vec, T> {1343fn drop(&mut self) {1344if core::mem::needs_drop::<T>() {1345let iter = core::mem::take(&mut self.elements);1346let ptr: *mut [T] = iter.into_slice();1347// SAFETY: By the type invariants, we own these values so we may destroy them.1348unsafe { ptr::drop_in_place(ptr) };1349}1350}1351}13521353#[macros::kunit_tests(rust_kvec)]1354mod tests {1355use super::*;1356use crate::prelude::*;13571358#[test]1359fn test_kvec_retain() {1360/// Verify correctness for one specific function.1361#[expect(clippy::needless_range_loop)]1362fn verify(c: &[bool]) {1363let mut vec1: KVec<usize> = KVec::with_capacity(c.len(), GFP_KERNEL).unwrap();1364let mut vec2: KVec<usize> = KVec::with_capacity(c.len(), GFP_KERNEL).unwrap();13651366for i in 0..c.len() {1367vec1.push_within_capacity(i).unwrap();1368if c[i] {1369vec2.push_within_capacity(i).unwrap();1370}1371}13721373vec1.retain(|i| c[*i]);13741375assert_eq!(vec1, vec2);1376}13771378/// Add one to a binary integer represented as a boolean array.1379fn add(value: &mut [bool]) {1380let mut carry = true;1381for v in value {1382let new_v = carry != *v;1383carry = carry && *v;1384*v = new_v;1385}1386}13871388// This boolean array represents a function from index to boolean. We check that `retain`1389// behaves correctly for all possible boolean arrays of every possible length less than1390// ten.1391let mut func = KVec::with_capacity(10, GFP_KERNEL).unwrap();1392for len in 0..10 {1393for _ in 0u32..1u32 << len {1394verify(&func);1395add(&mut func);1396}1397func.push_within_capacity(false).unwrap();1398}1399}1400}140114021403