| // 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. | |
| //! Owned heap pointer [`Box<T>`] (`8 B`; `Option<Box<T>>` and | |
| //! `Result<Box<T>, AllocError>` are `8 B` in `x0`, zero `SRET(x8)`). | |
| use core::marker::PhantomData; | |
| use core::mem::{ManuallyDrop, align_of, size_of}; | |
| use core::ops::{Deref, DerefMut}; | |
| use core::ptr::{self, NonNull}; | |
| use crate::alloc::{AllocError, dangling_for_align, is_valid_layout, raw_alloc, raw_dealloc}; | |
| /// Allocate backing storage for a boxed value of `(size, align)`. | |
| /// | |
| /// For zero-sized types (`size == 0`), performs no heap allocation and returns | |
| /// a properly aligned non-null dangling pointer. | |
| /// | |
| /// # Safety | |
| /// | |
| /// Same preconditions as [`raw_alloc`]. | |
| #[curry::verified] | |
| pub unsafe fn raw_box_alloc(size: usize, align: usize) -> Result<NonNull<u8>, AllocError> { | |
| if !is_valid_layout(size, align) { | |
| return Err(AllocError); | |
| } | |
| if size == 0 { | |
| return Ok(dangling_for_align(align)); | |
| } | |
| // SAFETY: `size > 0` and `(size, align)` validated above. | |
| unsafe { raw_alloc(size, align) } | |
| } | |
| /// Deallocate backing storage for a boxed value of `(size, align)`. | |
| /// | |
| /// No-op for zero-sized types (`size == 0`) or null pointers. | |
| /// | |
| /// # Safety | |
| /// | |
| /// When `size > 0` and `ptr` is non-null, `ptr` must have been allocated by | |
| /// [`raw_box_alloc`] with the exact same `(size, align)` and not yet freed. | |
| #[curry::verified] | |
| pub unsafe fn raw_box_dealloc(ptr: *mut u8, size: usize, align: usize) { | |
| if size == 0 || ptr.is_null() { | |
| return; | |
| } | |
| // SAFETY: `size > 0`, `ptr` is non-null, and caller guarantees active allocation. | |
| unsafe { raw_dealloc(ptr, size, align) } | |
| } | |
| /// Fallible, `#![no_std]` owned heap pointer (`alloc::boxed::Box<T>` analog). | |
| /// | |
| /// All generic methods are `#[inline(always)]` thin wrappers over the | |
| /// non-generic verified [`raw_box_alloc`] / [`raw_box_dealloc`] core. | |
| #[repr(transparent)] | |
| pub struct Box<T> { | |
| ptr: NonNull<T>, | |
| _marker: PhantomData<T>, | |
| } | |
| const _: () = assert!(size_of::<Box<u64>>() == 8); | |
| const _: () = assert!(align_of::<Box<u64>>() == 8); | |
| const _: () = assert!(size_of::<Option<Box<u64>>>() == 8); | |
| const _: () = assert!(size_of::<Result<Box<u64>, AllocError>>() == 8); | |
| impl<T> Box<T> { | |
| /// Allocate heap space and move `value` into it. | |
| /// | |
| /// Returns `Err(AllocError)` (dropping `value` cleanly) on allocation | |
| /// failure. Performs zero heap allocations when `size_of::<T>() == 0`. | |
| #[inline(always)] | |
| pub fn try_new(value: T) -> Result<Self, AllocError> { | |
| // SAFETY: `(size_of::<T>(), align_of::<T>())` is a valid Rust layout. | |
| let raw = unsafe { raw_box_alloc(size_of::<T>(), align_of::<T>())? }; | |
| let typed = raw.cast::<T>(); | |
| // SAFETY: `typed` is properly aligned and valid for a write of `T` | |
| // (or a properly aligned dangling pointer when `size_of::<T>() == 0`). | |
| unsafe { | |
| ptr::write(typed.as_ptr(), value); | |
| } | |
| Ok(Self { ptr: typed, _marker: PhantomData }) | |
| } | |
| /// Return a raw const pointer to the boxed value. | |
| #[inline(always)] | |
| pub const fn as_ptr(&self) -> *const T { | |
| self.ptr.as_ptr() | |
| } | |
| /// Return a raw mutable pointer to the boxed value. | |
| #[inline(always)] | |
| pub const fn as_mut_ptr(&mut self) -> *mut T { | |
| self.ptr.as_ptr() | |
| } | |
| /// Consume the box, move the inner value out, and free its heap slot. | |
| #[inline(always)] | |
| pub fn into_inner(this: Self) -> T { | |
| let this = ManuallyDrop::new(this); | |
| let ptr = this.ptr.as_ptr(); | |
| // SAFETY: `this` owns an initialized `T` at `ptr` and will not run | |
| // `Drop` because it is wrapped in `ManuallyDrop`. | |
| let value = unsafe { ptr::read(ptr) }; | |
| // SAFETY: `ptr` was allocated with `raw_box_alloc(size_of::<T>(), align_of::<T>())`. | |
| unsafe { | |
| raw_box_dealloc(ptr as *mut u8, size_of::<T>(), align_of::<T>()); | |
| } | |
| value | |
| } | |
| } | |
| impl<T> Deref for Box<T> { | |
| type Target = T; | |
| #[inline(always)] | |
| fn deref(&self) -> &T { | |
| // SAFETY: `self.ptr` points to a live, initialized `T` for `&self`. | |
| unsafe { self.ptr.as_ref() } | |
| } | |
| } | |
| impl<T> DerefMut for Box<T> { | |
| #[inline(always)] | |
| fn deref_mut(&mut self) -> &mut T { | |
| // SAFETY: `self.ptr` points to a live, exclusively owned `T`. | |
| unsafe { self.ptr.as_mut() } | |
| } | |
| } | |
| impl<T> AsRef<T> for Box<T> { | |
| #[inline(always)] | |
| fn as_ref(&self) -> &T { | |
| self | |
| } | |
| } | |
| impl<T> AsMut<T> for Box<T> { | |
| #[inline(always)] | |
| fn as_mut(&mut self) -> &mut T { | |
| self | |
| } | |
| } | |
| impl<T: PartialEq> PartialEq for Box<T> { | |
| #[inline(always)] | |
| fn eq(&self, other: &Self) -> bool { | |
| **self == **other | |
| } | |
| } | |
| impl<T: Eq> Eq for Box<T> {} | |
| impl<T> Drop for Box<T> { | |
| #[inline(always)] | |
| fn drop(&mut self) { | |
| let ptr = self.ptr.as_ptr(); | |
| // SAFETY: `ptr` points to an initialized `T` being dropped exactly once, | |
| // and was allocated via `raw_box_alloc(size_of::<T>(), align_of::<T>())`. | |
| unsafe { | |
| ptr::drop_in_place(ptr); | |
| raw_box_dealloc(ptr as *mut u8, size_of::<T>(), align_of::<T>()); | |
| } | |
| } | |
| } |