blob: 33c3d6cddd8fd68ca9697bd1f4fdc664b8903aae [file]
// Copyright 2026 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Fallible growable array [`Vec<T>`] (`24 B`, backed by non-generic [`RawVec`]).
use core::borrow::Borrow;
use core::marker::PhantomData;
use core::mem::{ManuallyDrop, MaybeUninit, align_of, needs_drop, size_of};
use core::ops::{Deref, DerefMut};
use core::{ptr, slice};
use crate::alloc::AllocError;
use crate::raw_vec::{
RawVec, raw_vec_extend_bytes, raw_vec_free, raw_vec_pop_bytes, raw_vec_push_bytes,
raw_vec_try_grow,
};
/// Fallible, `#![no_std]` growable vector (`alloc::vec::Vec<T>` analog).
///
/// Layout (`#[repr(C)]`, 24 bytes, 8-byte aligned):
/// - `+0`: `raw: RawVec` (`ptr: NonNull<u8>`, `cap: usize`)
/// - `+16`: `len: usize` (`0 <= len <= raw.cap`)
///
/// All generic methods are `#[inline(always)]` thin wrappers over the
/// non-generic verified [`RawVec`] core.
#[repr(C)]
pub struct Vec<T> {
pub(crate) raw: RawVec,
pub(crate) len: usize,
_marker: PhantomData<T>,
}
const _: () = assert!(size_of::<Vec<u64>>() == 24);
const _: () = assert!(align_of::<Vec<u64>>() == 8);
const _: () = assert!(size_of::<Option<Vec<u64>>>() == 24);
impl<T> Vec<T> {
/// Construct a [`Vec<T>`] from its raw components inside this crate.
#[inline(always)]
pub(crate) const fn from_raw(raw: RawVec, len: usize) -> Self {
Self { raw, len, _marker: PhantomData }
}
/// Construct an empty [`Vec<T>`] without allocating.
#[inline(always)]
pub const fn new() -> Self {
Self { raw: RawVec::new_for_align(align_of::<T>()), len: 0, _marker: PhantomData }
}
/// Construct an empty [`Vec<T>`] with capacity reserved for at least `cap` elements.
#[inline(always)]
pub fn try_with_capacity(cap: usize) -> Result<Self, AllocError> {
let mut v = Self::new();
if cap > 0 {
v.try_reserve(cap)?;
}
Ok(v)
}
/// Reserve capacity for at least `additional` more elements.
///
/// On `Err(AllocError)`, existing elements and capacity remain untouched.
#[inline(always)]
pub fn try_reserve(&mut self, additional: usize) -> Result<(), AllocError> {
// SAFETY: `self.raw` maintains the `(size_of::<T>(), align_of::<T>())`
// invariant with `self.len <= self.raw.cap` initialized elements.
unsafe {
raw_vec_try_grow(&mut self.raw, self.len, additional, size_of::<T>(), align_of::<T>())
}
}
/// Append `value` to the end of the vector, growing if needed.
///
/// On `Err(AllocError)`, `value` is dropped cleanly and existing elements
/// remain unchanged.
#[inline(always)]
pub fn try_push(&mut self, value: T) -> Result<(), AllocError> {
let md = ManuallyDrop::new(value);
// SAFETY: `&md` is stack-local (disjoint from `self.raw.ptr`) and valid
// for `size_of::<T>()` bytes.
let res = unsafe {
raw_vec_push_bytes(
&mut self.raw,
&mut self.len,
(&*md as *const T) as *const u8,
size_of::<T>(),
align_of::<T>(),
)
};
if res.is_err() {
let _ = ManuallyDrop::into_inner(md);
return Err(AllocError);
}
Ok(())
}
/// Remove and return the last element, or `None` if empty.
#[inline(always)]
pub fn pop(&mut self) -> Option<T> {
let mut out = MaybeUninit::<T>::uninit();
// SAFETY: `out` is stack-local (disjoint from `self.raw.ptr`) and valid
// for `size_of::<T>()` bytes.
let popped = unsafe {
raw_vec_pop_bytes(
&mut self.raw,
&mut self.len,
out.as_mut_ptr() as *mut u8,
size_of::<T>(),
)
};
if popped {
// SAFETY: `raw_vec_pop_bytes` initialized `out` with the moved-out element.
Some(unsafe { out.assume_init() })
} else {
None
}
}
/// Return the number of initialized elements in the vector.
#[inline(always)]
pub const fn len(&self) -> usize {
self.len
}
/// Return the current element capacity.
#[inline(always)]
pub const fn capacity(&self) -> usize {
self.raw.cap
}
/// Return `true` if the vector contains no elements.
#[inline(always)]
pub const fn is_empty(&self) -> bool {
self.len == 0
}
/// Return a non-null, properly aligned const pointer to the vector's buffer.
#[inline(always)]
pub const fn as_ptr(&self) -> *const T {
self.raw.ptr.as_ptr() as *const T
}
/// Return a non-null, properly aligned mutable pointer to the vector's buffer.
#[inline(always)]
pub const fn as_mut_ptr(&mut self) -> *mut T {
self.raw.ptr.as_ptr() as *mut T
}
/// Borrow all initialized elements as a slice.
#[inline(always)]
pub fn as_slice(&self) -> &[T] {
// SAFETY: `self.raw.ptr` is non-null and `align_of::<T>()`-aligned,
// and `self.len` elements are initialized.
unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
}
/// Borrow all initialized elements as a mutable slice.
#[inline(always)]
pub fn as_mut_slice(&mut self) -> &mut [T] {
let len = self.len;
// SAFETY: `self.raw.ptr` is non-null and `align_of::<T>()`-aligned,
// and `len` elements are exclusively owned and initialized.
unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), len) }
}
/// Return a shared reference to the element at `index`, or `None` if out of bounds.
#[inline(always)]
pub fn get(&self, index: usize) -> Option<&T> {
self.as_slice().get(index)
}
/// Return a mutable reference to the element at `index`, or `None` if out of bounds.
#[inline(always)]
pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
self.as_mut_slice().get_mut(index)
}
/// Drop all initialized elements while retaining the allocated capacity.
#[inline(always)]
pub fn clear(&mut self) {
let old_len = self.len;
self.len = 0;
if needs_drop::<T>() {
let base = self.as_mut_ptr();
let mut i: usize = 0;
while i < old_len {
// SAFETY: Each element `0..old_len` was initialized and is dropped once.
unsafe {
ptr::drop_in_place(base.add(i));
}
i += 1;
}
}
}
}
impl Vec<u8> {
/// Bulk-append `bytes` onto a byte vector using the verified byte-extend core.
#[inline(always)]
pub fn try_extend_from_slice(&mut self, bytes: &[u8]) -> Result<(), AllocError> {
// SAFETY: `self.raw` is a byte `RawVec` (`elem_size = 1, elem_align = 1`)
// and `bytes` is disjoint from `self.raw.ptr`.
unsafe { raw_vec_extend_bytes(&mut self.raw, &mut self.len, bytes.as_ptr(), bytes.len()) }
}
}
impl<T> Default for Vec<T> {
#[inline(always)]
fn default() -> Self {
Self::new()
}
}
impl<T> Deref for Vec<T> {
type Target = [T];
#[inline(always)]
fn deref(&self) -> &[T] {
self.as_slice()
}
}
impl<T> DerefMut for Vec<T> {
#[inline(always)]
fn deref_mut(&mut self) -> &mut [T] {
self.as_mut_slice()
}
}
impl<T> AsRef<[T]> for Vec<T> {
#[inline(always)]
fn as_ref(&self) -> &[T] {
self.as_slice()
}
}
impl<T> AsMut<[T]> for Vec<T> {
#[inline(always)]
fn as_mut(&mut self) -> &mut [T] {
self.as_mut_slice()
}
}
impl<T> Borrow<[T]> for Vec<T> {
#[inline(always)]
fn borrow(&self) -> &[T] {
self.as_slice()
}
}
impl<T: PartialEq> PartialEq for Vec<T> {
#[inline(always)]
fn eq(&self, other: &Self) -> bool {
self.as_slice() == other.as_slice()
}
}
impl<T: Eq> Eq for Vec<T> {}
impl<T> Drop for Vec<T> {
#[inline(always)]
fn drop(&mut self) {
self.clear();
// SAFETY: All initialized elements were dropped above; free backing storage.
unsafe {
raw_vec_free(&mut self.raw, size_of::<T>(), align_of::<T>());
}
}
}