| @@ -0,0 +1,185 @@ |
| 1 | +//! `std/table` (issue #407, ADR 0072): tables any actor reads without a |
| 2 | +//! message, like Erlang's ETS with `read_concurrency` or `persistent_term`. |
| 3 | +//! |
| 4 | +//! Every stored value is shared (`send::share`): its counts are atomic, so |
| 5 | +//! any thread may retain or release it. The map is sharded, each shard |
| 6 | +//! behind a read-write lock. A reader retains the value *before* releasing |
| 7 | +//! the lock, and a writer releases a replaced value only *after* releasing |
| 8 | +//! it, so no write can free a value a reader is about to retain. |
| 9 | +//! |
| 10 | +//! Tables are never freed (a table is an id); their entries are released |
| 11 | +//! on replace and remove. |
| 12 | + |
| 13 | +use crate::abi::{Ctx, UNIT, Value, int}; |
| 14 | +use crate::heap::{drop_value, dup_value}; |
| 15 | +use crate::int::saturating; |
| 16 | +use crate::send::{NotSendable, share}; |
| 17 | +use crate::values::{cell, text}; |
| 18 | +use std::collections::HashMap; |
| 19 | +use std::collections::hash_map::DefaultHasher; |
| 20 | +use std::hash::{Hash, Hasher}; |
| 21 | +use std::sync::atomic::{AtomicI64, Ordering}; |
| 22 | +use std::sync::{OnceLock, PoisonError, RwLock}; |
| 23 | + |
| 24 | +const SHARDS: usize = 64; |
| 25 | + |
| 26 | +/// A shared value the map owns one count of. |
| 27 | +struct Held(Value); |
| 28 | + |
| 29 | +// SAFETY: every held value is shared (atomic counts, `send::share`), so it |
| 30 | +// may be retained and released from any thread. |
| 31 | +unsafe impl Send for Held {} |
| 32 | +// SAFETY: as above; the map only retains through the shard lock. |
| 33 | +unsafe impl Sync for Held {} |
| 34 | + |
| 35 | +type Shard = RwLock<HashMap<i64, HashMap<Box<str>, Held>>>; |
| 36 | + |
| 37 | +static MAP: OnceLock<Vec<Shard>> = OnceLock::new(); |
| 38 | +static NEXT: AtomicI64 = AtomicI64::new(1); |
| 39 | + |
| 40 | +fn shard(table: i64, key: &str) -> &'static Shard { |
| 41 | + let shards = MAP.get_or_init(|| (0..SHARDS).map(|_| RwLock::default()).collect()); |
| 42 | + let mut hasher = DefaultHasher::new(); |
| 43 | + (table, key).hash(&mut hasher); |
| 44 | + &shards[(hasher.finish() % SHARDS as u64) as usize] |
| 45 | +} |
| 46 | + |
| 47 | +/// A new table's id, as an `Int`. |
| 48 | +#[unsafe(no_mangle)] |
| 49 | +pub extern "C" fn tl_table_new(_ctx: *mut Ctx) -> Value { |
| 50 | + int(NEXT.fetch_add(1, Ordering::Relaxed)) |
| 51 | +} |
| 52 | + |
| 53 | +/// `Some(value)` for `key` in `table`, retained for the caller, or `None`. |
| 54 | +/// |
| 55 | +/// # Safety |
| 56 | +/// `table` must be a live `Int` and `key` a live string (both borrowed). |
| 57 | +#[unsafe(no_mangle)] |
| 58 | +pub unsafe extern "C" fn tl_table_get(ctx: *mut Ctx, table: Value, key: Value) -> Value { |
| 59 | + // SAFETY: caller guarantees a live Int and string. |
| 60 | + let (table, key) = unsafe { (saturating(table), text(key)) }; |
| 61 | + let found = { |
| 62 | + let map = shard(table, key) |
| 63 | + .read() |
| 64 | + .unwrap_or_else(PoisonError::into_inner); |
| 65 | + // SAFETY: held values are live and shared; the lock keeps them so. |
| 66 | + map.get(&table) |
| 67 | + .and_then(|keys| keys.get(key)) |
| 68 | + .map(|held| unsafe { dup_value(held.0) }) |
| 69 | + }; |
| 70 | + match found { |
| 71 | + Some(v) => cell(ctx, 1, &[v]), |
| 72 | + None => int(0), |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +/// Store `value` under `key` in `table`, releasing what it replaces. |
| 77 | +/// Panics if `value` cannot be shared. Consumes its arguments. |
| 78 | +/// |
| 79 | +/// # Safety |
| 80 | +/// `ctx` must be the running actor's; `table` a live `Int`, `key` a live |
| 81 | +/// string and `value` a live value, all owned. |
| 82 | +#[unsafe(no_mangle)] |
| 83 | +pub unsafe extern "C" fn tl_table_put( |
| 84 | + ctx: *mut Ctx, |
| 85 | + table: Value, |
| 86 | + key: Value, |
| 87 | + value: Value, |
| 88 | +) -> Value { |
| 89 | + // SAFETY: caller guarantees live, owned arguments. |
| 90 | + unsafe { |
| 91 | + let (id, name) = (saturating(table), Box::<str>::from(text(key))); |
| 92 | + drop_value(ctx, key); |
| 93 | + if let Err(NotSendable(reason)) = share(value) { |
| 94 | + drop_value(ctx, value); |
| 95 | + return crate::effects::tl_panic_str(ctx, reason.as_ptr()); |
| 96 | + } |
| 97 | + let replaced = shard(id, &name) |
| 98 | + .write() |
| 99 | + .unwrap_or_else(PoisonError::into_inner) |
| 100 | + .entry(id) |
| 101 | + .or_default() |
| 102 | + .insert(name, Held(value)); |
| 103 | + if let Some(Held(old)) = replaced { |
| 104 | + drop_value(ctx, old); |
| 105 | + } |
| 106 | + } |
| 107 | + UNIT |
| 108 | +} |
| 109 | + |
| 110 | +/// Remove `key` from `table`, releasing its value; nothing if absent. |
| 111 | +/// |
| 112 | +/// # Safety |
| 113 | +/// `ctx` must be the running actor's; `table` a live `Int` and `key` a |
| 114 | +/// live string (both borrowed). |
| 115 | +#[unsafe(no_mangle)] |
| 116 | +pub unsafe extern "C" fn tl_table_remove(ctx: *mut Ctx, table: Value, key: Value) -> Value { |
| 117 | + // SAFETY: caller guarantees a live Int and string. |
| 118 | + let (table, key) = unsafe { (saturating(table), text(key)) }; |
| 119 | + let removed = shard(table, key) |
| 120 | + .write() |
| 121 | + .unwrap_or_else(PoisonError::into_inner) |
| 122 | + .get_mut(&table) |
| 123 | + .and_then(|keys| keys.remove(key)); |
| 124 | + if let Some(Held(old)) = removed { |
| 125 | + // SAFETY: the map held this count. |
| 126 | + unsafe { drop_value(ctx, old) }; |
| 127 | + } |
| 128 | + UNIT |
| 129 | +} |
| 130 | + |
| 131 | +#[cfg(test)] |
| 132 | +mod tests { |
| 133 | + use super::*; |
| 134 | + use crate::abi::Block; |
| 135 | + use crate::heap::tl_alloc; |
| 136 | + use crate::values::tl_string_from; |
| 137 | + |
| 138 | + fn cell1(ctx: *mut Ctx, field: Value) -> Value { |
| 139 | + let b = tl_alloc(ctx, 0, 1, 0); |
| 140 | + // SAFETY: a fresh block with one field. |
| 141 | + unsafe { Block::fields_ptr(b).write(field) }; |
| 142 | + b as Value |
| 143 | + } |
| 144 | + |
| 145 | + fn key(ctx: *mut Ctx, s: &str) -> Value { |
| 146 | + // SAFETY: `s` is valid for its length. |
| 147 | + unsafe { tl_string_from(ctx, s.as_ptr().cast(), s.len()) } |
| 148 | + } |
| 149 | + |
| 150 | + fn drop(ctx: *mut Ctx, v: Value) { |
| 151 | + // SAFETY: `v` is owned. |
| 152 | + unsafe { drop_value(ctx, v) } |
| 153 | + } |
| 154 | + |
| 155 | + /// Put, get, replace and remove keep every count exact: nothing is |
| 156 | + /// left alive at the end. |
| 157 | + unsafe extern "C" fn scenarios(ctx: *mut Ctx) -> Value { |
| 158 | + let table = tl_table_new(ctx); |
| 159 | + let name = key(ctx, "ada"); |
| 160 | + // SAFETY: live arguments throughout. |
| 161 | + unsafe { |
| 162 | + assert_eq!(tl_table_get(ctx, table, name), int(0)); |
| 163 | + tl_table_put(ctx, table, key(ctx, "ada"), cell1(ctx, int(1))); |
| 164 | + let first = tl_table_get(ctx, table, name); |
| 165 | + tl_table_put(ctx, table, key(ctx, "ada"), cell1(ctx, int(2))); |
| 166 | + let second = tl_table_get(ctx, table, name); |
| 167 | + let other = tl_table_new(ctx); |
| 168 | + assert_eq!(tl_table_get(ctx, other, name), int(0)); |
| 169 | + tl_table_remove(ctx, table, name); |
| 170 | + assert_eq!(tl_table_get(ctx, table, name), int(0)); |
| 171 | + tl_table_remove(ctx, table, name); |
| 172 | + drop(ctx, first); |
| 173 | + drop(ctx, second); |
| 174 | + } |
| 175 | + drop(ctx, name); |
| 176 | + assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0); |
| 177 | + UNIT |
| 178 | + } |
| 179 | + |
| 180 | + #[test] |
| 181 | + fn counts_stay_exact() { |
| 182 | + // SAFETY: `scenarios` follows the generated-code convention. |
| 183 | + assert_eq!(unsafe { crate::sched::run_test_actor(scenarios) }, 0); |
| 184 | + } |
| 185 | +} |