| // 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. | |
| //! Non-generic verified growable buffer core (`vx_alloc::raw_vec`). | |
| //! | |
| //! [`RawVec`] is 16 bytes (`ptr: NonNull<u8>`, `cap: usize`), storing a | |
| //! properly aligned non-null dangling pointer whenever `cap == 0` (or for | |
| //! zero-sized elements). All deallocation paths strictly guard `__vx_dealloc` | |
| //! on `old_cap > 0 && elem_size > 0` so dangling pointers are never freed. | |
| use core::mem::{align_of, size_of}; | |
| use core::ptr::{self, NonNull}; | |
| use crate::alloc::{ | |
| AllocError, MAX_ALLOC_BYTES, dangling_for_align, is_valid_layout, raw_alloc, raw_dealloc, | |
| }; | |
| /// Minimum non-zero element capacity allocated on initial growth. | |
| const MIN_INITIAL_CAP: usize = 4; | |
| /// Non-generic growable allocation buffer (`#[repr(C)]`, 16 bytes, 8-byte aligned). | |
| /// | |
| /// Invariant: | |
| /// - When `cap == 0` or `elem_size == 0`, `ptr` is a non-null, `elem_align`-aligned | |
| /// dangling pointer and owns zero heap memory. | |
| /// - When `cap > 0` and `elem_size > 0`, `ptr` owns a live heap allocation of | |
| /// `(cap * elem_size, elem_align)`. | |
| #[repr(C)] | |
| pub struct RawVec { | |
| pub(crate) ptr: NonNull<u8>, | |
| pub(crate) cap: usize, | |
| } | |
| const _: () = assert!(size_of::<RawVec>() == 16); | |
| const _: () = assert!(align_of::<RawVec>() == 8); | |
| const _: () = assert!(size_of::<Option<RawVec>>() == 16); | |
| const _: () = assert!(core::mem::offset_of!(RawVec, ptr) == 0); | |
| const _: () = assert!(core::mem::offset_of!(RawVec, cap) == 8); | |
| impl RawVec { | |
| /// Construct an empty [`RawVec`] with a dangling pointer aligned to `elem_align`. | |
| #[inline(always)] | |
| pub const fn new_for_align(elem_align: usize) -> Self { | |
| Self { ptr: dangling_for_align(elem_align), cap: 0 } | |
| } | |
| /// Return the current backing (or dangling) pointer. | |
| #[inline(always)] | |
| pub const fn ptr(&self) -> NonNull<u8> { | |
| self.ptr | |
| } | |
| /// Return the current allocated element capacity. | |
| #[inline(always)] | |
| pub const fn capacity(&self) -> usize { | |
| self.cap | |
| } | |
| } | |
| /// Compute the next capacity satisfying `>= needed` via overflow-checked | |
| /// doubling, guaranteeing `new_cap * elem_size <= MAX_ALLOC_BYTES - (elem_align - 1)`. | |
| #[curry::verified] | |
| pub fn raw_vec_next_cap( | |
| cap: usize, | |
| needed: usize, | |
| elem_size: usize, | |
| elem_align: usize, | |
| ) -> Result<usize, AllocError> { | |
| if elem_align == 0 || (elem_align & (elem_align - 1)) != 0 { | |
| return Err(AllocError); | |
| } | |
| if needed <= cap { | |
| return Ok(cap); | |
| } | |
| let max_bytes = MAX_ALLOC_BYTES - (elem_align - 1); | |
| if elem_size == 0 { | |
| if needed > max_bytes { | |
| return Err(AllocError); | |
| } | |
| return Ok(needed); | |
| } | |
| match needed.checked_mul(elem_size) { | |
| Some(b) if b <= max_bytes => {} | |
| _ => return Err(AllocError), | |
| } | |
| let candidate = if cap == 0 { | |
| if needed < MIN_INITIAL_CAP { MIN_INITIAL_CAP } else { needed } | |
| } else { | |
| match cap.checked_mul(2) { | |
| Some(d) if d >= needed => d, | |
| _ => needed, | |
| } | |
| }; | |
| match candidate.checked_mul(elem_size) { | |
| Some(b) if b <= max_bytes => Ok(candidate), | |
| _ => Ok(needed), | |
| } | |
| } | |
| /// Copy `len` initialized elements from `old_ptr` into `new_ptr` and deallocate | |
| /// `(old_ptr, old_cap * elem_size, elem_align)` strictly when `old_cap > 0 && elem_size > 0`. | |
| /// | |
| /// # Safety | |
| /// | |
| /// When `old_cap > 0 && elem_size > 0`, `old_ptr` must be a live allocation of | |
| /// `(old_cap * elem_size, elem_align)` containing `len <= old_cap` initialized | |
| /// elements, and `new_ptr` must be a disjoint writable buffer of at least | |
| /// `len * elem_size` bytes. | |
| #[curry::verified] | |
| unsafe fn raw_vec_copy_and_free_old( | |
| old_ptr: *mut u8, | |
| new_ptr: *mut u8, | |
| len: usize, | |
| old_cap: usize, | |
| elem_size: usize, | |
| elem_align: usize, | |
| ) { | |
| if old_cap == 0 || elem_size == 0 { | |
| return; | |
| } | |
| if len > 0 { | |
| if let Some(copy_bytes) = len.checked_mul(elem_size) { | |
| // SAFETY: Caller guarantees `old_ptr` and `new_ptr` are disjoint | |
| // and valid for `copy_bytes` bytes. | |
| unsafe { | |
| ptr::copy_nonoverlapping(old_ptr, new_ptr, copy_bytes); | |
| } | |
| } | |
| } | |
| if let Some(old_bytes) = old_cap.checked_mul(elem_size) { | |
| // SAFETY: `old_cap > 0 && elem_size > 0`, and caller guarantees | |
| // `(old_ptr, old_bytes, elem_align)` matches the live old allocation. | |
| unsafe { | |
| raw_dealloc(old_ptr, old_bytes, elem_align); | |
| } | |
| } | |
| } | |
| /// Ensure `raw` has capacity for at least `len + additional` elements of layout | |
| /// `(elem_size, elem_align)`. | |
| /// | |
| /// On `Err(AllocError)`, `raw` and all existing elements remain completely | |
| /// untouched and zero memory is leaked. | |
| /// | |
| /// # Safety | |
| /// | |
| /// `raw` must uphold the [`RawVec`] invariant for `(elem_size, elem_align)` | |
| /// with `len <= raw.cap` initialized elements. | |
| #[curry::verified] | |
| pub unsafe fn raw_vec_try_grow( | |
| raw: &mut RawVec, | |
| len: usize, | |
| additional: usize, | |
| elem_size: usize, | |
| elem_align: usize, | |
| ) -> Result<(), AllocError> { | |
| if elem_align == 0 || (elem_align & (elem_align - 1)) != 0 || len > raw.cap { | |
| return Err(AllocError); | |
| } | |
| let Some(needed) = len.checked_add(additional) else { | |
| return Err(AllocError); | |
| }; | |
| if needed <= raw.cap { | |
| return Ok(()); | |
| } | |
| let new_cap = raw_vec_next_cap(raw.cap, needed, elem_size, elem_align)?; | |
| if elem_size == 0 { | |
| raw.cap = new_cap; | |
| return Ok(()); | |
| } | |
| let new_bytes = match new_cap.checked_mul(elem_size) { | |
| Some(b) if is_valid_layout(b, elem_align) => b, | |
| _ => return Err(AllocError), | |
| }; | |
| // SAFETY: `new_bytes > 0` and `(new_bytes, elem_align)` was validated above. | |
| let new_ptr = unsafe { raw_alloc(new_bytes, elem_align)? }; | |
| // SAFETY: `raw.ptr` holds `len <= raw.cap` elements (if `raw.cap > 0`) and | |
| // `new_ptr` is disjoint with space for `new_cap >= needed >= len` elements. | |
| unsafe { | |
| raw_vec_copy_and_free_old( | |
| raw.ptr.as_ptr(), | |
| new_ptr.as_ptr(), | |
| len, | |
| raw.cap, | |
| elem_size, | |
| elem_align, | |
| ); | |
| } | |
| raw.ptr = new_ptr; | |
| raw.cap = new_cap; | |
| Ok(()) | |
| } | |
| /// Free the backing buffer of `raw` strictly when `old_cap > 0 && elem_size > 0`, | |
| /// resetting `raw.ptr` to a dangling aligned pointer and `raw.cap = 0`. | |
| /// | |
| /// Caller is responsible for dropping any live elements before freeing. | |
| /// | |
| /// # Safety | |
| /// | |
| /// `raw` must uphold the [`RawVec`] invariant for `(elem_size, elem_align)`. | |
| #[curry::verified] | |
| pub unsafe fn raw_vec_free(raw: &mut RawVec, elem_size: usize, elem_align: usize) { | |
| let old_ptr = raw.ptr.as_ptr(); | |
| let old_cap = raw.cap; | |
| if old_cap > 0 && elem_size > 0 { | |
| if let Some(old_bytes) = old_cap.checked_mul(elem_size) { | |
| // SAFETY: `old_cap > 0 && elem_size > 0` guarantees `old_ptr` is a | |
| // live allocation of `(old_bytes, elem_align)`. | |
| unsafe { | |
| raw_dealloc(old_ptr, old_bytes, elem_align); | |
| } | |
| } | |
| } | |
| raw.ptr = dangling_for_align(elem_align); | |
| raw.cap = 0; | |
| } | |
| /// Append one raw element of `elem_size` bytes copied from `src` onto | |
| /// `(raw, len)`, growing with overflow-checked doubling if needed. | |
| /// | |
| /// # Safety | |
| /// | |
| /// `raw` must uphold the [`RawVec`] invariant for `(elem_size, elem_align)` | |
| /// with `*len <= raw.cap`, and when `elem_size > 0`, `src` must be valid for | |
| /// reads of `elem_size` bytes disjoint from `raw.ptr`. | |
| #[curry::verified] | |
| pub unsafe fn raw_vec_push_bytes( | |
| raw: &mut RawVec, | |
| len: &mut usize, | |
| src: *const u8, | |
| elem_size: usize, | |
| elem_align: usize, | |
| ) -> Result<(), AllocError> { | |
| let cur_len = *len; | |
| if cur_len >= raw.cap { | |
| // SAFETY: Forwarded from caller. | |
| unsafe { raw_vec_try_grow(raw, cur_len, 1, elem_size, elem_align)? }; | |
| } | |
| if elem_size > 0 { | |
| if raw.cap == 0 { | |
| return Err(AllocError); | |
| } | |
| let Some(off) = cur_len.checked_mul(elem_size) else { | |
| return Err(AllocError); | |
| }; | |
| // SAFETY: `cur_len < raw.cap`, `raw.cap * elem_size <= MAX_ALLOC_BYTES`, | |
| // and `src` is disjoint and readable for `elem_size` bytes. | |
| unsafe { | |
| ptr::copy_nonoverlapping(src, raw.ptr.as_ptr().add(off), elem_size); | |
| } | |
| } | |
| *len = cur_len + 1; | |
| Ok(()) | |
| } | |
| /// Pop the last element of `(raw, len)`, copying its `elem_size` bytes into `dst`. | |
| /// | |
| /// Returns `true` if an element was popped, or `false` if `*len == 0`. | |
| /// | |
| /// # Safety | |
| /// | |
| /// `raw` must uphold the [`RawVec`] invariant for `(elem_size, elem_align)` | |
| /// with `*len <= raw.cap`, and when `elem_size > 0 && *len > 0`, `dst` must be | |
| /// valid for writes of `elem_size` bytes disjoint from `raw.ptr`. | |
| #[curry::verified] | |
| pub unsafe fn raw_vec_pop_bytes( | |
| raw: &mut RawVec, | |
| len: &mut usize, | |
| dst: *mut u8, | |
| elem_size: usize, | |
| ) -> bool { | |
| let cur_len = *len; | |
| if cur_len == 0 { | |
| return false; | |
| } | |
| let new_len = cur_len - 1; | |
| if elem_size > 0 { | |
| if raw.cap == 0 { | |
| return false; | |
| } | |
| let Some(off) = new_len.checked_mul(elem_size) else { | |
| return false; | |
| }; | |
| // SAFETY: `new_len < cur_len <= raw.cap`, so `[raw.ptr + off, +elem_size)` | |
| // is readable and disjoint from `dst`. | |
| unsafe { | |
| ptr::copy_nonoverlapping(raw.ptr.as_ptr().add(off), dst, elem_size); | |
| } | |
| } | |
| *len = new_len; | |
| true | |
| } | |
| /// Bulk-append `count` bytes from `src` onto a byte-oriented `(raw, len)` | |
| /// (`elem_size = 1`, `elem_align = 1`). | |
| /// | |
| /// # Safety | |
| /// | |
| /// `raw` must uphold the byte [`RawVec`] invariant (`elem_size = 1, elem_align = 1`) | |
| /// with `*len <= raw.cap`, and when `count > 0`, `src` must be valid for reads | |
| /// of `count` bytes disjoint from `raw.ptr`. | |
| #[curry::verified] | |
| pub unsafe fn raw_vec_extend_bytes( | |
| raw: &mut RawVec, | |
| len: &mut usize, | |
| src: *const u8, | |
| count: usize, | |
| ) -> Result<(), AllocError> { | |
| if count == 0 { | |
| return Ok(()); | |
| } | |
| let cur_len = *len; | |
| // SAFETY: Forwarded from caller. | |
| unsafe { raw_vec_try_grow(raw, cur_len, count, 1, 1)? }; | |
| if raw.cap == 0 { | |
| return Err(AllocError); | |
| } | |
| // SAFETY: `cur_len + count <= raw.cap` and `src` is disjoint and readable for `count` bytes. | |
| unsafe { | |
| ptr::copy_nonoverlapping(src, raw.ptr.as_ptr().add(cur_len), count); | |
| } | |
| *len = cur_len + count; | |
| Ok(()) | |
| } |