tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

60 lignes · 2048 octetsBrut · Historique
1//! Resources: foreign pointers with a finalizer (`std/ffi`; ADR 0005).
2//!
3//! A `Resource<t>` is a block holding a foreign pointer and its finalizer,
4//! called when the last reference is dropped. Resources that are not
5//! thread-safe are pinned: they cannot be sent to another thread's actor.
6
7use crate::abi::{Block, Ctx, Value};
8use crate::heap::tl_alloc;
9
10const WORD: usize = size_of::<Value>();
11
12/// A finalizer for a foreign pointer. It must not touch Louise values.
13pub type Finalizer = unsafe extern "C" fn(*mut std::ffi::c_void);
14
15/// Wrap `ptr` with `finalize` (may be null) as a resource value (owned).
16#[unsafe(no_mangle)]
17pub extern "C" fn tl_resource_new(
18 ctx: *mut Ctx,
19 ptr: *mut std::ffi::c_void,
20 finalize: Option<Finalizer>,
21 thread_safe: bool,
22) -> Value {
23 let b = tl_alloc(ctx, crate::abi::TAG_RESOURCE, 0, 2 * WORD);
24 // SAFETY: the raw area holds the pointer, then the finalizer.
25 unsafe {
26 let raw = Block::fields_ptr(b).cast::<usize>();
27 raw.write(ptr as usize);
28 raw.add(1).write(finalize.map_or(0, |f| f as usize));
29 if !thread_safe {
30 (*b).header.flags |= crate::abi::FLAG_PINNED;
31 }
32 }
33 b as Value
34}
35
36/// The foreign pointer of a resource (borrowed).
37///
38/// # Safety
39/// `r` must be a live resource.
40#[unsafe(no_mangle)]
41pub unsafe extern "C" fn tl_resource_get(r: Value) -> *mut std::ffi::c_void {
42 // SAFETY: caller guarantees a resource.
43 unsafe { Block::fields_ptr(r as *mut Block).cast::<usize>().read() as *mut std::ffi::c_void }
44}
45
46/// Called when a resource block is freed: run its finalizer.
47///
48/// # Safety
49/// `b` must be a resource block being freed.
50pub(crate) unsafe fn finalize_resource(b: *mut Block) {
51 // SAFETY: caller guarantees a resource block.
52 unsafe {
53 let raw = Block::fields_ptr(b).cast::<usize>();
54 let (ptr, f) = (raw.read(), raw.add(1).read());
55 if f != 0 {
56 let f: Finalizer = std::mem::transmute(f);
57 f(ptr as *mut std::ffi::c_void);
58 }
59 }
60}