From dc538ef788c5c1068c33244f6a68f3208f010a57 Mon Sep 17 00:00:00 2001 From: Brendan Hansknecht Date: Tue, 17 Sep 2024 13:27:39 -0700 Subject: [PATCH] add function from basic-webserver impl --- crates/roc_std_heap/src/lib.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/crates/roc_std_heap/src/lib.rs b/crates/roc_std_heap/src/lib.rs index 018840071b..19a4da6500 100644 --- a/crates/roc_std_heap/src/lib.rs +++ b/crates/roc_std_heap/src/lib.rs @@ -61,6 +61,15 @@ impl ThreadSafeRefcountedResourceHeap { pub fn box_to_resource<'a>(data: RocBox<()>) -> &'a mut T { RefcountedResourceHeap::box_to_resource(data) } + + pub fn box_to_refcount<'a>(data: &RocBox<()>) -> &'a mut usize { + RefcountedResourceHeap::::box_to_refcount(data) + } + + pub fn promote_all_to_constant(self: &Self) { + let _g = self.guard.lock().unwrap(); + unsafe { &mut *self.heap.get() }.promote_all_to_constant(); + } } unsafe impl Sync for ThreadSafeRefcountedResourceHeap {} @@ -104,6 +113,26 @@ impl RefcountedResourceHeap { let alloc: &mut Refcounted = unsafe { &mut *alloc_ptr }; &mut alloc.1 } + + pub fn box_to_refcount<'a>(data: &RocBox<()>) -> &'a mut usize { + let box_ptr: &usize = unsafe { std::mem::transmute(data) }; + + let rc_ptr = (*box_ptr - mem::size_of::()) as *mut usize; + unsafe { &mut *rc_ptr } + } + + /// Promotes all live references to constants. + /// Does this my walking all allocations and setting the refcount to zero (constant). + /// It will also end up walking freed elements, but their bytes are uninitialized and don't matter. + /// This is great for calling after an init function where all lived data is guarenteed to live until the server finishes running. + pub fn promote_all_to_constant(self: &mut Self) { + for i in 0..self.0.elements { + let offset = i * Heap::>::node_size(); + let elem_ptr = unsafe { self.0.data.as_mut_ptr().offset(offset as isize) }; + let rc_ptr = elem_ptr as *mut usize; + unsafe { *rc_ptr = 0 }; + } + } } /// The Heap is one mmap of data that can be interpreted multiple ways.