//! Resources: foreign pointers with a finalizer (`std/ffi`; ADR 0005). //! //! A `Resource` is a block holding a foreign pointer and its finalizer, //! called when the last reference is dropped. Resources that are not //! thread-safe are pinned: they cannot be sent to another thread's actor. use crate::abi::{Block, Ctx, Value}; use crate::heap::tl_alloc; const WORD: usize = size_of::(); /// A finalizer for a foreign pointer. It must not touch Louise values. pub type Finalizer = unsafe extern "C" fn(*mut std::ffi::c_void); /// Wrap `ptr` with `finalize` (may be null) as a resource value (owned). #[unsafe(no_mangle)] pub extern "C" fn tl_resource_new( ctx: *mut Ctx, ptr: *mut std::ffi::c_void, finalize: Option, thread_safe: bool, ) -> Value { let b = tl_alloc(ctx, crate::abi::TAG_RESOURCE, 0, 2 * WORD); // SAFETY: the raw area holds the pointer, then the finalizer. unsafe { let raw = Block::fields_ptr(b).cast::(); raw.write(ptr as usize); raw.add(1).write(finalize.map_or(0, |f| f as usize)); if !thread_safe { (*b).header.flags |= crate::abi::FLAG_PINNED; } } b as Value } /// The foreign pointer of a resource (borrowed). /// /// # Safety /// `r` must be a live resource. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_resource_get(r: Value) -> *mut std::ffi::c_void { // SAFETY: caller guarantees a resource. unsafe { Block::fields_ptr(r as *mut Block).cast::().read() as *mut std::ffi::c_void } } /// Called when a resource block is freed: run its finalizer. /// /// # Safety /// `b` must be a resource block being freed. pub(crate) unsafe fn finalize_resource(b: *mut Block) { // SAFETY: caller guarantees a resource block. unsafe { let raw = Block::fields_ptr(b).cast::(); let (ptr, f) = (raw.read(), raw.add(1).read()); if f != 0 { let f: Finalizer = std::mem::transmute(f); f(ptr as *mut std::ffi::c_void); } } }