Re: [PATCH v4 2/7] rust: alloc: add ArrayVec
From: Alexandre Courbot
Date: Mon Oct 26 2026 - 01:27:40 EST
On Fri Oct 16, 2026 at 10:53 AM JST, Eliot Courtney wrote:
<...>
> +/// A fixed capacity vector that holds at most `N` elements.
> +///
> +/// # Invariants
> +///
> +/// - `len` is at most `N`.
> +/// - The first `len` elements of `data` are initialized.
> +///
> +/// # Examples
> +///
> +/// ```
> +/// use kernel::alloc::ArrayVec;
> +///
> +/// let mut v = ArrayVec::<u8, 4>::new();
> +/// v.extend_from_slice(b"abc")?;
> +/// assert_eq!(*v, *b"abc");
> +///
> +/// assert!(v.extend_from_slice(b"ab").is_err());
> +///
> +/// v.push(4u8)?;
> +/// assert_eq!(*v, *b"abc\x04");
> +/// assert!(v.push(5u8).is_err());
> +///
> +/// v.clear();
> +/// assert!(v.is_empty());
> +/// # Ok::<(), Error>(())
> +/// ```
> +#[derive(Zeroable)]
Do we need to derive `Zeroable` here? AFAICT we have no user and this
forces `T` to implement `Zeroable` as well. Worse, the derived
implementaiton does not check against `MAX_STACK_SIZE` before returning
the built value on the stack.
We also have `new` and `Default` that do basically the same thing,
without the constraint on `T`.
On a related note, it would be nice to have a method to initialize an
empty ArrayVec in-place. Currently we have two instances of
`ArrayVec::init_with::<Infallible>(|_| Ok(()))` in this series, which
imho justifies having a dedicated `init_empty` method for that.
> +pub struct ArrayVec<T, const N: usize> {
> + data: [MaybeUninit<T>; N],
> + len: usize,
> +}
> +
> +/// The maximum size in bytes of an [`ArrayVec`] returned by value from [`ArrayVec::new`].
> +const MAX_STACK_SIZE: usize = 512;
> +
> +impl<T, const N: usize> ArrayVec<T, N> {
> + /// Creates an empty [`ArrayVec`].
> + #[inline]
> + pub const fn new() -> Self {
> + const_assert!(
> + size_of::<Self>() <= MAX_STACK_SIZE,
> + "use `init_with` instead of constructing a large ArrayVec on the stack"
> + );
> +
> + // INVARIANT: An empty ArrayVec trivially has all its elements initialized.
> + Self {
> + data: [const { MaybeUninit::uninit() }; N],
> + len: 0,
> + }
> + }
> +
> + /// Creates an initializer for an [`ArrayVec`] populated by `f`.
> + ///
> + /// `f` gets an empty [`ArrayVec`] and can fill it in place.
> + ///
> + /// # Examples
> + ///
> + /// ```
> + /// use kernel::alloc::ArrayVec;
> + ///
> + /// let v = KBox::init(
> + /// ArrayVec::<u8, 4096>::init_with(|v| v.extend_from_slice(b"abc")),
> + /// GFP_KERNEL,
> + /// )?;
> + /// assert_eq!(**v, *b"abc");
> + /// # Ok::<(), Error>(())
> + /// ```
> + #[inline]
> + pub fn init_with<E>(f: impl FnOnce(&mut Self) -> Result<(), E>) -> impl Init<Self, E> {
> + let init_empty = |slot: *mut Self| {
> + // SAFETY: By the initializer contract `slot` is valid for writes. Once `len` is zero
> + // the slot holds a valid empty ArrayVec, since `data` requires no initialization.
> + // INVARIANT: An empty ArrayVec trivially has all its elements initialized.
> + unsafe { (&raw mut (*slot).len).write(0) };
> + Ok(())
> + };
> +
> + // SAFETY: `init_empty` fully initializes the slot and never fails.
> + unsafe { init_from_closure(init_empty) }.chain(f)
> + }
> +
> + /// Appends an element to the back of the [`ArrayVec`].
> + ///
> + /// Fails when the [`ArrayVec`] is full, handing the element back in [`PushError`].
> + #[inline]
> + pub fn push(&mut self, v: T) -> Result<(), PushError<T>> {
> + self.try_push_init(v)
> + .map_err(|TryPushInitError::Full(v)| PushError(v))
nit: could also be `self.push_init(v)`.
Pretty minor stuff, so as long as my first comment is somehow addressed:
Reviewed-by: Alexandre Courbot <acourbot@xxxxxxxxxx>