Skip to main content

RawStack

Struct RawStack 

Source
pub struct RawStack { /* private fields */ }
Expand description

A simple raw stack that stores values as raw bytes. Each value is naturally aligned given the base alignment of the stack, which is the maximum alignment of any value stored in the stack. Live values are owned until popped, explicitly released, or destroyed in reverse push order.

§Examples

See the module example for typed ownership transfer.

§Thread confinement

The erased owners may contain non-Send values, so the stack remains on its creating thread.

ⓘ
let mut stack = cel_runtime::RawStack::with_base_alignment(4096);
stack.push(std::rc::Rc::new(()));
std::thread::spawn(move || drop(stack));

Implementations§

Source§

impl RawStack

Source

pub fn with_base_alignment(base_alignment: usize) -> Self

Creates a new RawStack with base alignment.

  • Precondition: base_alignment is a power of two.
§Examples
use cel_runtime::raw_stack::RawStack;
let stack = RawStack::with_base_alignment(align_of::<u32>());
Source

pub unsafe fn release_top(&mut self, count: usize)

Removes the latest ownership entries without destroying or changing their bytes.

  • Precondition: count does not exceed the logical depth.
  • Postcondition: The caller owns the released values’ destruction obligations.
  • Complexity: O(count), excluding descriptor destruction.
§Safety

Removing entries can leave released bytes above the retained owners. Before any owner-based stack operation or stack destruction, including unwinding, the buffer’s length, values, and padding must again match all retained ownership entries. The caller must not permit unwinding while that physical frame is invalid; complete its raw repair before invoking user code or another potentially panicking operation. If no owners remain, unowned bytes may remain in the buffer without invalidating its destruction.

Released values remain the caller’s responsibility. If transferred or destroyed, their abandoned representations must not be used again. Intentionally forgetting a released value is permitted; leaking resources alone does not violate memory safety.

§Examples

See Self::drop_at for releasing a value before destroying it in place.

Unguarded calls are rejected even when no owners would be removed:

ⓘ
let mut stack = cel_runtime::RawStack::with_base_alignment(1);
stack.release_top(0);
Source

pub fn len(&self) -> usize

Returns the number of bytes currently on the stack.

§Examples
use cel_runtime::RawStack;
let mut stack = RawStack::with_base_alignment(1);
stack.push(7u8);
assert_eq!(stack.len(), 1);
Source

pub fn push<T: 'static>(&mut self, value: T) -> bool

Pushes a value of type T onto the stack.

The stack owns the value until it is popped using the correct type or destroyed. T: 'static prevents owned destructors from retaining nonstatic borrows; borrowed inputs must instead use explicitly borrowed adapters.

  • Precondition: T requires no greater alignment than this stack’s base alignment. This requirement is checked in release builds to preserve memory safety.
§Type Parameters
  • T: The type of the value to push.
§Examples
use cel_runtime::raw_stack::RawStack;
let mut stack = RawStack::with_base_alignment(align_of::<u32>());
let _ = stack.push(42u32);

A value whose destructor borrows nonstatic data cannot enter this owning stack:

ⓘ
use cel_runtime::raw_stack::RawStack;

/// Borrows text that must remain live until destruction.
struct BorrowedDrop<'a>(&'a str);
impl Drop for BorrowedDrop<'_> {
    /// Reads the borrowed text during destruction.
    fn drop(&mut self) {
        assert!(!self.0.is_empty());
    }
}

let mut stack = RawStack::with_base_alignment(align_of::<BorrowedDrop<'static>>());
{
    let text = String::from("borrowed");
    stack.push(BorrowedDrop(&text));
}
drop(stack);
  • Complexity: Amortized O(1 + s + p) time and storage, for s value bytes and p inserted padding bytes. Growth may copy existing bytes and owner entries.
Source

pub unsafe fn push_raw( &mut self, align: usize, size: usize, src: *const MaybeUninit<u8>, ) -> bool

Pushes size raw bytes from src, aligned to align, using the same padding/marker-byte bookkeeping as push.

src is typed as MaybeUninit<u8> rather than u8 because the bytes being copied may include a source value’s interior padding, which is itself uninitialized — reading it through a u8 pointer instead would be undefined behavior even though this function never inspects the bytes’ values.

  • Precondition: align is a power of two no greater than the stack’s base alignment.
  • Postcondition: A raw-byte slot is registered; its bytes are not destroyed as a typed value unless upgraded with own_top.
  • Complexity: Amortized O(1 + size + p) time and storage for p inserted padding bytes; growth may copy existing bytes and owner entries.
§Examples
use cel_runtime::RawStack;
let mut stack = RawStack::with_base_alignment(1);
let value = 7u8;
let padding = unsafe { stack.push_raw(1, 1, std::ptr::from_ref(&value).cast()) };
assert_eq!(unsafe { stack.pop::<u8>(padding) }, 7);
§Safety

src must be valid for reads of size bytes, and must not overlap the stack’s internal buffer.

Source

pub unsafe fn reserve_and_write( &mut self, align: usize, size: usize, write: impl FnOnce(*mut u8), ) -> bool

Reserves aligned space for size bytes (using the same padding/marker bookkeeping as push) and calls write with a pointer to that space instead of copying from a source buffer.

  • Precondition: align is a power of two no greater than the stack’s base alignment.
  • Postcondition: write is called exactly once, before this method returns, with a pointer to size freshly-reserved bytes.
  • Postcondition: Normal return registers a raw-byte slot; a panicking initializer registers no slot, leaving byte restoration to its caller.
  • Complexity: Amortized O(1 + size + p) plus initializer costs for p inserted padding bytes; growth may copy existing bytes and owner entries.
§Examples
use cel_runtime::RawStack;
let mut stack = RawStack::with_base_alignment(1);
let padding = unsafe { stack.reserve_and_write(1, 1, |ptr| ptr.write(7)) };
assert_eq!(unsafe { stack.pop::<u8>(padding) }, 7);
§Safety

write must fully initialize all size bytes at the pointer it’s given before returning, except interior padding. If it panics, the caller must guard partially initialized resources.

Source

pub unsafe fn copy_from( &self, offset: usize, size: usize, dst: *mut MaybeUninit<u8>, )

Copies size bytes starting at absolute buffer offset offset into dst.

dst is typed as MaybeUninit<u8> rather than u8 because the bytes being copied may be a value’s interior padding, which is itself uninitialized — reading it through a u8 pointer instead would be undefined behavior even though this function never inspects the bytes’ values.

  • Complexity: O(size) time and O(1) additional space.
§Examples

See Self::repack for copying a repacked byte array into caller storage.

§Safety

offset..offset + size must be within the current logical buffer; dst must be valid for writes of size bytes and must not overlap the stack’s internal buffer.

Source

pub unsafe fn drop_at(&mut self, offset: usize, run_drop: impl FnOnce(*mut u8))

Drops a value in place at absolute buffer offset offset, without altering the stack’s tracked length.

  • Complexity: The destructor’s cost; O(1) additional storage.
§Examples
use cel_runtime::RawStack;
let mut stack = RawStack::with_base_alignment(align_of::<String>());
stack.push(String::from("owned"));
// SAFETY: Releasing the sole owner leaves no retained value to destroy.
unsafe {
    stack.release_top(1);
    stack.drop_at(0, |ptr| ptr.cast::<String>().drop_in_place());
    stack.truncate_to(0, false);
}
assert_eq!(stack.len(), 0);
§Safety

offset must point to a live, valid value; run_drop must correctly run that value’s destructor given a pointer to its start. Its ownership entry must already have been removed with release_top.

Source

pub unsafe fn read_at<R>( &self, offset: usize, read: impl FnOnce(*const u8) -> R, ) -> R

Reads a value at absolute buffer offset offset, given a callback that receives a pointer to its bytes.

  • Complexity: The callback’s cost; O(1) additional storage.
§Examples
use cel_runtime::RawStack;
let mut stack = RawStack::with_base_alignment(align_of::<String>());
stack.push(String::from("borrowed"));
let before = stack.len();
let length = unsafe { stack.read_at(0, |ptr| (&*ptr.cast::<String>()).len()) };
assert_eq!(length, 8);
assert_eq!(stack.len(), before);
§Safety

offset must point to a live, valid, properly-aligned value for the type the caller will reinterpret it as; read must not retain the pointer beyond the call. This byte operation does not transfer ownership; a caller moving out a value must explicitly release its ownership entry before destruction or stack cleanup can occur.

Source

pub unsafe fn truncate_to(&mut self, new_len: usize, padding: bool)

Truncates the stack back to new_len, additionally stripping padding bytes that preceded the removed region (scanned the same way pop does).

  • Complexity: O(p) time for p preceding padding bytes when padding is true, otherwise O(1); O(1) additional space.
§Examples

See Self::drop_at for releasing, destroying, and truncating a value.

§Safety

No live (undropped) value may exist at or above new_len; the caller must explicitly release all removed ownership entries first. This byte operation does not infer ownership transfer, including for zero-sized values.

Source

pub unsafe fn drop_sized( &mut self, size: usize, padding: bool, run_drop: impl FnOnce(*mut u8), )

Removes the top owner’s bytes and metadata, then destroys its value in place.

  • Complexity: O(p) padding-scan time plus the destructor’s cost; O(1) additional storage, excluding the destructor.
§Examples
use cel_runtime::RawStack;
let mut stack = RawStack::with_base_alignment(align_of::<String>());
let padding = stack.push(String::from("owned"));
unsafe {
    stack.drop_sized(size_of::<String>(), padding, |ptr| {
        ptr.cast::<String>().drop_in_place()
    });
}
assert_eq!(stack.len(), 0);
§Safety

The top size bytes (plus padding if padding is true) must be a live, valid value; run_drop must correctly run its destructor given a pointer to its start. The value must have a registered top ownership entry.

Source

pub unsafe fn repack( &mut self, ambient_start: usize, dest_base: usize, total_size: usize, src_offsets: &[usize], dest_offsets: &[usize], sizes: &[usize], ) -> bool

Repacks sizes.len() already-pushed values (currently at the absolute byte offsets in src_offsets) into one contiguous, self-contained region of total_size bytes starting at dest_base, placing element i at dest_base + dest_offsets[i]. Adjusts the tracked length to dest_base + total_size and returns whether leading padding was inserted between ambient_start and dest_base.

Preserves bytes below ambient_start. Source and destination fields may move left, right, or remain in place, including self-overlapping moves. Interior padding bytes need not be initialized.

  • Complexity: O(n + b + p + r) time for n fields, b moved bytes, p leading padding bytes, and r existing buffer bytes if growth relocates the allocation. O(1) auxiliary space beyond any buffer growth.
§Examples
use cel_runtime::RawStack;
let mut stack = RawStack::with_base_alignment(1);
stack.push([11u8, 22, 33]);
let mut bytes = [0u8; 3];
// SAFETY: All owners are released; the byte array needs no destruction.
unsafe {
    stack.release_top(1);
    assert!(stack.repack(0, 1, 3, &[0], &[0], &[3]));
    stack.copy_from(1, 3, bytes.as_mut_ptr().cast());
    stack.truncate_to(0, false);
}
assert_eq!(bytes, [11, 22, 33]);
§Safety

The slices must have equal lengths. Source ranges must lie within the current buffer, and destination ranges within 0..total_size. Both layouts must have monotonically ordered, nonoverlapping fields; corresponding fields have the same size from sizes. Each field’s end must be at or before the next field’s start, including zero-sized fields. ambient_start must lie within the current buffer, dest_base must be at least ambient_start, and dest_base + total_size must fit in usize. The caller must release ownership entries for every moved value before repacking and separately register or dispose of the resulting values. No unrelated live value may occupy overwritten or truncated bytes. This byte operation never infers ownership transfer.

Source

pub unsafe fn pop<T>(&mut self, padding: bool) -> T

Pops a value of type T from the stack. Does not change the stack capacity.

  • Complexity: O(s + p) time for s value bytes and p preceding padding bytes; O(s) result storage and O(1) other additional space.
§Safety

The type T must be the same type as the value on the top of the stack. padding must match its push result, and the value must have a registered ownership entry. Incorrect usage can lead to undefined behavior.

§Type Parameters
  • T: The type of the value to pop.
§Examples
use cel_runtime::raw_stack::RawStack;
let mut stack = RawStack::with_base_alignment(align_of::<u32>());
let padding = stack.push(100u32);
let value: u32 = unsafe { stack.pop(padding) };
Source

pub unsafe fn drop<T>(&mut self, padding: bool)

Pops a value of type T from the stack and drops it.

  • Complexity: O(s + p) time plus destruction, for s value bytes and p preceding padding bytes; O(s) temporary value storage.
§Examples
use cel_runtime::RawStack;
let mut stack = RawStack::with_base_alignment(align_of::<String>());
let padding = stack.push(String::from("owned"));
unsafe { stack.drop::<String>(padding) };
assert_eq!(stack.len(), 0);
§Safety

The type, padding flag, and top ownership entry must satisfy Self::pop’s safety requirements.

Removes ownership and bytes before invoking the value’s destructor.

Trait Implementations§

Source§

impl Debug for RawStack

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for RawStack

Source§

fn drop(&mut self)

Destroys every live owner in reverse order.

  • Complexity: O(n + b + p) plus destruction for n live slots, b moved value bytes, and p scanned padding bytes.
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.