//! Exact-width immutable native storage for a present multi-slot Dynamic. use crate::resource_budget::{ Reservation, ResourceFailure, ResourceReason, RuntimeBudget, RuntimeResource as Q, }; use crate::value_contract::ValueError; use prometeu_bytecode::Value; use prometeu_bytecode::registry::{Registry, TypeId}; use std::alloc::{Layout, alloc, dealloc}; use std::ptr::NonNull; use std::sync::Arc; #[derive(Debug)] pub(super) struct DynamicBox { registry: Arc, type_id: TypeId, values: Box<[Value]>, charge: Reservation, } impl DynamicBox { /// Heap validates the exact non-Dynamic multi-slot group before construction. /// Source owners remain borrowed until publication; allocation never invokes GC. pub fn new( registry: Arc, type_id: TypeId, values: &[Value], budget: &RuntimeBudget, ) -> Result { let bytes = budget.bytes::(values.len(), Q::GuestBytes)?; let layout = Layout::array::(values.len()) .map_err(|_| budget.failure(Q::GuestBytes, ResourceReason::SizeOverflow, bytes))?; let charge = budget.reserve(Q::GuestBytes, bytes)?; let ptr = if values.is_empty() { NonNull::dangling() } else { // SAFETY: checked nonzero array layout; a null allocator result is a // recoverable resource failure and drops the provisional reservation. NonNull::new(unsafe { alloc(layout) }.cast::()).ok_or_else(|| { budget.failure(Q::GuestBytes, ResourceReason::AllocationFailed, bytes) })? }; let mut pending = PendingValues { ptr, layout, initialized: 0 }; for value in values { let cloned = value.clone(); // SAFETY: initialized advances within the exactly allocated Value array; // ptr::write moves each owner into an unused, aligned native slot. unsafe { ptr.as_ptr().add(pending.initialized).write(cloned); } pending.initialized += 1; } // SAFETY: allocation came from the global allocator with precisely the // Box<[Value]> layout; all elements are initialized. Transfer ownership // without Vec capacity/shrink reallocations or a second allocation. let boxed = unsafe { Box::from_raw(std::ptr::slice_from_raw_parts_mut(ptr.as_ptr(), values.len())) }; std::mem::forget(pending); Ok(Self { registry, type_id, values: boxed, charge }) } pub fn bytes(&self) -> u64 { self.charge.amount() } pub fn values(&self) -> &[Value] { &self.values } pub fn typed_values( &self, registry: &Registry, type_id: TypeId, ) -> Result<&[Value], ValueError> { if !std::ptr::eq(self.registry.as_ref(), registry) || self.type_id != type_id { return Err(ValueError::Type); } Ok(&self.values) } } /// Owns the partially initialized allocation until Box takes over. A panic /// while constructing an owner drops only the initialized prefix, then frees it. struct PendingValues { ptr: NonNull, layout: Layout, initialized: usize, } impl Drop for PendingValues { fn drop(&mut self) { // SAFETY: initialized counts constructed Values only, all uniquely owned. unsafe { std::ptr::drop_in_place(std::ptr::slice_from_raw_parts_mut( self.ptr.as_ptr(), self.initialized, )); if self.layout.size() != 0 { dealloc(self.ptr.as_ptr().cast(), self.layout); } } } } #[cfg(test)] mod tests { use super::*; #[test] fn interrupted_native_initialization_drops_the_constructed_prefix_and_refunds() { let budget = RuntimeBudget::default(); let text: Arc = Arc::from("partially initialized"); let result = std::panic::catch_unwind(|| { let layout = Layout::array::(3).unwrap(); let _charge = budget.reserve(Q::GuestBytes, layout.size() as u64).unwrap(); // SAFETY: checked nonzero layout; only the first slot is initialized. let ptr = NonNull::new(unsafe { alloc(layout) }.cast::()).unwrap(); let mut pending = PendingValues { ptr, layout, initialized: 0 }; unsafe { ptr.as_ptr().write(Value::String(text.clone())); } pending.initialized = 1; assert_eq!(Arc::strong_count(&text), 2); panic!("simulate interrupted construction before the next native slot"); }); assert!(result.is_err()); assert_eq!(Arc::strong_count(&text), 1); assert_eq!(budget.used(Q::GuestBytes), 0); } #[test] fn zero_width_storage_owns_no_allocation_and_is_not_a_valid_guest_box() { let registry = crate::typed_storage::tests::fixture_registry(); let budget = RuntimeBudget::default(); let empty = DynamicBox::new(registry, TypeId(5), &[], &budget).unwrap(); assert!(empty.values().is_empty()); assert_eq!(empty.bytes(), 0); drop(empty); assert_eq!(budget.used(Q::GuestBytes), 0); // Heap's group validator rejects empty values before invoking this storage constructor. let mut heap = crate::heap::Heap::with_budget(&budget); assert_eq!( heap.allocate_dynamic_box( crate::typed_storage::tests::fixture_registry(), TypeId(5), &[] ) .unwrap_err(), ValueError::Type ); } }