//! `std/table` (issue #407, ADR 0073): tables any actor reads without a //! message, like Erlang's ETS with `read_concurrency` or `persistent_term`. //! //! Every stored value is shared (`send::share`): its counts are atomic, so //! any thread may retain or release it. The map is sharded, each shard //! behind a read-write lock. A reader retains the value *before* releasing //! the lock, and a writer releases a replaced value only *after* releasing //! it, so no write can free a value a reader is about to retain. //! //! Tables are never freed (a table is an id); their entries are released //! on replace and remove. use crate::abi::{Ctx, UNIT, Value, int}; use crate::heap::{drop_value, dup_value}; use crate::int::saturating; use crate::send::{NotSendable, share}; use crate::values::{cell, text}; use std::collections::HashMap; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::sync::atomic::{AtomicI64, Ordering}; use std::sync::{OnceLock, PoisonError, RwLock}; const SHARDS: usize = 64; /// A shared value the map owns one count of. struct Held(Value); // SAFETY: every held value is shared (atomic counts, `send::share`), so it // may be retained and released from any thread. unsafe impl Send for Held {} // SAFETY: as above; the map only retains through the shard lock. unsafe impl Sync for Held {} type Shard = RwLock, Held>>>; static MAP: OnceLock> = OnceLock::new(); static NEXT: AtomicI64 = AtomicI64::new(1); fn shard(table: i64, key: &str) -> &'static Shard { let shards = MAP.get_or_init(|| (0..SHARDS).map(|_| RwLock::default()).collect()); let mut hasher = DefaultHasher::new(); (table, key).hash(&mut hasher); &shards[(hasher.finish() % SHARDS as u64) as usize] } /// A new table's id, as an `Int`. #[unsafe(no_mangle)] pub extern "C" fn tl_table_new(_ctx: *mut Ctx) -> Value { int(NEXT.fetch_add(1, Ordering::Relaxed)) } /// `Some(value)` for `key` in `table`, retained for the caller, or `None`. /// /// # Safety /// `table` must be a live `Int` and `key` a live string (both borrowed). #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_table_get(ctx: *mut Ctx, table: Value, key: Value) -> Value { // SAFETY: caller guarantees a live Int and string. let (table, key) = unsafe { (saturating(table), text(key)) }; let found = { let map = shard(table, key) .read() .unwrap_or_else(PoisonError::into_inner); // SAFETY: held values are live and shared; the lock keeps them so. map.get(&table) .and_then(|keys| keys.get(key)) .map(|held| unsafe { dup_value(held.0) }) }; match found { Some(v) => cell(ctx, 1, &[v]), None => int(0), } } /// Store `value` under `key` in `table`, releasing what it replaces. /// Panics if `value` cannot be shared. Consumes its arguments. /// /// # Safety /// `ctx` must be the running actor's; `table` a live `Int`, `key` a live /// string and `value` a live value, all owned. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_table_put( ctx: *mut Ctx, table: Value, key: Value, value: Value, ) -> Value { // SAFETY: caller guarantees live, owned arguments. unsafe { let (id, name) = (saturating(table), Box::::from(text(key))); drop_value(ctx, key); if let Err(NotSendable(reason)) = share(value) { drop_value(ctx, value); return crate::effects::tl_panic_str(ctx, reason.as_ptr()); } let replaced = shard(id, &name) .write() .unwrap_or_else(PoisonError::into_inner) .entry(id) .or_default() .insert(name, Held(value)); if let Some(Held(old)) = replaced { drop_value(ctx, old); } } UNIT } /// Remove `key` from `table`, releasing its value; nothing if absent. /// /// # Safety /// `ctx` must be the running actor's; `table` a live `Int` and `key` a /// live string (both borrowed). #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_table_remove(ctx: *mut Ctx, table: Value, key: Value) -> Value { // SAFETY: caller guarantees a live Int and string. let (table, key) = unsafe { (saturating(table), text(key)) }; let removed = shard(table, key) .write() .unwrap_or_else(PoisonError::into_inner) .get_mut(&table) .and_then(|keys| keys.remove(key)); if let Some(Held(old)) = removed { // SAFETY: the map held this count. unsafe { drop_value(ctx, old) }; } UNIT } #[cfg(test)] mod tests { use super::*; use crate::abi::Block; use crate::heap::tl_alloc; use crate::values::tl_string_from; fn cell1(ctx: *mut Ctx, field: Value) -> Value { let b = tl_alloc(ctx, 0, 1, 0); // SAFETY: a fresh block with one field. unsafe { Block::fields_ptr(b).write(field) }; b as Value } fn key(ctx: *mut Ctx, s: &str) -> Value { // SAFETY: `s` is valid for its length. unsafe { tl_string_from(ctx, s.as_ptr().cast(), s.len()) } } fn drop(ctx: *mut Ctx, v: Value) { // SAFETY: `v` is owned. unsafe { drop_value(ctx, v) } } /// Put, get, replace and remove keep every count exact: nothing is /// left alive at the end. unsafe extern "C" fn scenarios(ctx: *mut Ctx) -> Value { let table = tl_table_new(ctx); let name = key(ctx, "ada"); // SAFETY: live arguments throughout. unsafe { assert_eq!(tl_table_get(ctx, table, name), int(0)); tl_table_put(ctx, table, key(ctx, "ada"), cell1(ctx, int(1))); let first = tl_table_get(ctx, table, name); tl_table_put(ctx, table, key(ctx, "ada"), cell1(ctx, int(2))); let second = tl_table_get(ctx, table, name); let other = tl_table_new(ctx); assert_eq!(tl_table_get(ctx, other, name), int(0)); tl_table_remove(ctx, table, name); assert_eq!(tl_table_get(ctx, table, name), int(0)); tl_table_remove(ctx, table, name); drop(ctx, first); drop(ctx, second); } drop(ctx, name); assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0); UNIT } #[test] fn counts_stay_exact() { // SAFETY: `scenarios` follows the generated-code convention. assert_eq!(unsafe { crate::sched::run_test_actor(scenarios) }, 0); } }