//! `std/array`: immutable arrays, updated in place when unique (ADR 0014). //! //! An array is a `TAG_ARRAY` block with `scan_fsize` [`SCAN_LARGE`]. In //! words after the header: //! //! ```text //! [ tl_int(n) | x1 ... xn | spare | spare unused slots ] //! ``` //! //! The first `1 + n` words are the layout the ABI reserved for large //! blocks, so drop and `send` walk arrays like any block. The raw area is //! the spare capacity: a plain `i64` count, then that many zeroed slots. //! A block of capacity `cap` is always `2 + cap` words long. //! //! `set` and `push` are `owned` externs: they consume the array, so a //! count of 1 means nobody else can see it, and they update it in place. //! A shared array (count > 1, or negative: sent to other actors) is //! copied first. The other functions borrow their arguments, like every //! `@extern` function. All of them must behave like the interpreter's //! (`louise_interp`). use crate::abi::{Block, Ctx, Header, SCAN_LARGE, TAG_ARRAY, UNIT, Value, int, int_get}; use crate::heap::{alloc_bytes, block_size, drop_value, dup_value, realloc_block}; use crate::int::saturating; use crate::prims::panic_with; use crate::values::{cell, list, list_items}; const WORD: usize = size_of::(); const HEADER: usize = size_of::
(); /// The smallest capacity an array grows to. const MIN_GROW: usize = 4; /// `with_capacity` hints above this are capped (pushes still grow). const MAX_HINT: i64 = 1 << 24; /// A fresh array of `len` units with capacity `cap >= len`. pub(crate) fn alloc(ctx: *mut Ctx, len: usize, cap: usize) -> *mut Block { debug_assert!(len <= cap); let b = alloc_bytes(ctx, HEADER + WORD * (2 + cap)); // SAFETY: a fresh block of `2 + cap` words after the header. unsafe { b.cast::
().write(Header { rc: 1, tag: TAG_ARRAY, scan_fsize: SCAN_LARGE, flags: 0, }); let words = Block::fields_ptr(b); for i in 0..len { words.add(1 + i).write(UNIT); } // Zeroed spare slots: a copy (`send`) never reads uninitialised // memory. std::ptr::write_bytes(words.add(1 + len), 0, cap - len + 1); set_len(b, len, cap - len); } b } /// Record `len` elements and `spare` unused slots after them. /// /// # Safety /// `b` must be an array block of capacity `len + spare`. unsafe fn set_len(b: *mut Block, len: usize, spare: usize) { // SAFETY: forwarded caller guarantee: word `1 + len` is the spare count. unsafe { let words = Block::fields_ptr(b); words.write(int(len as i64)); words.add(1 + len).cast::().write(spare as i64); } } /// The number of elements. /// /// # Safety /// `a` must be a live array. unsafe fn len(a: Value) -> usize { // SAFETY: an array's first word is its count. int_get(unsafe { *Block::fields_ptr(a as *mut Block) }) as usize } /// The unused slots after the elements. /// /// # Safety /// `a` must be a live array. unsafe fn spare(a: Value) -> usize { // SAFETY: the word after the elements is the spare count. unsafe { elems(a).add(len(a)).cast::().read() as usize } } /// The first element's slot. pub(crate) fn elems(a: Value) -> *mut Value { Block::fields_ptr(a as *mut Block).wrapping_add(1) } /// The elements (borrowed). /// /// # Safety /// `a` must be a live array, not changed while the slice is used. unsafe fn items<'a>(a: Value) -> &'a [Value] { // SAFETY: forwarded caller guarantee. unsafe { std::slice::from_raw_parts(elems(a), len(a)) } } /// A new array holding `items` (borrowed: each is dup'd), with capacity /// `cap`. fn from_items(ctx: *mut Ctx, items: &[Value], cap: usize) -> Value { let b = alloc(ctx, items.len(), cap.max(items.len())); let a = b as Value; for (i, x) in items.iter().enumerate() { // SAFETY: `x` is live (borrowed from the caller); slot `i` exists. unsafe { dup_value(*x); elems(a).add(i).write(*x); } } a } /// `i` as an index of `a`, if it is one. /// /// # Safety /// `a` must be a live array, `i` a live Int. unsafe fn index(a: Value, i: Value) -> Option { // SAFETY: forwarded caller guarantee. let (n, i) = unsafe { (len(a), saturating(i)) }; usize::try_from(i).ok().filter(|i| *i < n) } /// An empty array with room for `n` elements before it grows. /// /// # Safety /// `n` must be a live Int. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_array_with_capacity(ctx: *mut Ctx, n: Value) -> Value { // SAFETY: caller guarantees a live Int. let n = unsafe { saturating(n) }; alloc(ctx, 0, n.clamp(0, MAX_HINT) as usize) as Value } /// # Safety /// `a` must be a live array. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_array_length(_ctx: *mut Ctx, a: Value) -> Value { // SAFETY: caller guarantees a live array. int(unsafe { len(a) } as i64) } /// An array of the elements of a `List`. /// /// # Safety /// `list` must be a live list. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_array_from_list(ctx: *mut Ctx, list: Value) -> Value { // SAFETY: caller guarantees a live list. let items: Vec = unsafe { list_items(list) }.collect(); from_items(ctx, &items, items.len()) } /// The elements as a `List`. /// /// # Safety /// `a` must be a live array. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_array_to_list(ctx: *mut Ctx, a: Value) -> Value { // SAFETY: caller guarantees a live array; its elements are live. let items = unsafe { items(a) }; list( ctx, items.iter().map(|x| { // SAFETY: as above. unsafe { dup_value(*x) }; *x }), ) } /// `Some(element)` at `i`, or `None` out of range. /// /// # Safety /// `a` must be a live array. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_array_get(ctx: *mut Ctx, a: Value, i: Value) -> Value { // SAFETY: caller guarantees a live array. match unsafe { index(a, i) } { // SAFETY: `i` is in range; the element is live. Some(i) => unsafe { let x = *elems(a).add(i); dup_value(x); cell(ctx, 1, &[x]) }, None => int(0), } } /// The element at `i`, which `std/array` keeps in range (`fold`, `map`); /// panics otherwise. Generated code calls the header's inline /// `tl_array_at`, which comes here only out of range (issue #128). /// /// # Safety /// `ctx` must be the running actor's context; `a` a live array. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_array_at_slow(ctx: *mut Ctx, a: Value, i: Value) -> Value { // SAFETY: caller guarantees a live array. match unsafe { index(a, i) } { // SAFETY: `i` is in range; the element is live. Some(i) => unsafe { let x = *elems(a).add(i); dup_value(x); x }, // SAFETY: caller guarantees the running actor's context, a live // array and a live Int. None => unsafe { panic_with(ctx, &out_of_range("array.at", a, i)) }, } } /// The message of an index out of range. /// /// # Safety /// `a` must be a live array, `i` a live Int. unsafe fn out_of_range(op: &str, a: Value, i: Value) -> String { // SAFETY: forwarded caller guarantee. let (n, i) = unsafe { (len(a), crate::int::to_big(i)) }; format!("{op}: index {i} out of range for length {n}") } /// `a` with `x` at index `i`: in place if `a` is unique, else in a copy. /// Panics if `i` is out of range. Consumes `a` and `x` (an `owned` /// extern). /// /// # Safety /// `ctx` must be the running actor's context; `a` an owned array, `x` an /// owned value. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_array_set(ctx: *mut Ctx, a: Value, i: Value, x: Value) -> Value { // SAFETY: caller guarantees an owned array and value. unsafe { let Some(i) = index(a, i) else { let message = out_of_range("array.set", a, i); drop_value(ctx, a); drop_value(ctx, x); return panic_with(ctx, &message); }; let a = unique(ctx, a, 0); let slot = elems(a).add(i); let old = slot.read(); slot.write(x); drop_value(ctx, old); a } } /// `a` with `x` appended: in place if `a` is unique and has a spare slot; /// a unique array without one grows (doubling). Consumes `a` and `x` (an /// `owned` extern). /// /// # Safety /// `ctx` must be the running actor's context; `a` an owned array, `x` an /// owned value. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_array_push(ctx: *mut Ctx, a: Value, x: Value) -> Value { // SAFETY: caller guarantees an owned array and value. unsafe { let a = unique(ctx, a, 1); let (n, s) = (len(a), spare(a)); let a = if s > 0 { a } else { let cap = (2 * n).max(MIN_GROW); let old = block_size(a as *mut Block); let b = realloc_block(a as *mut Block, old, HEADER + WORD * (2 + cap)); std::ptr::write_bytes(Block::fields_ptr(b).add(1 + n), 0, cap - n + 1); set_len(b, n, cap - n); b as Value }; let s = spare(a); elems(a).add(n).write(x); set_len(a as *mut Block, n + 1, s - 1); a } } /// `a` itself if it is unique, else a copy (giving up one reference to /// `a`), with at least `extra` spare slots. A copy for one more element /// gets room to grow, so pushes on it are in place afterwards. /// /// # Safety /// `ctx` must be the running actor's context; `a` an owned array. unsafe fn unique(ctx: *mut Ctx, a: Value, extra: usize) -> Value { // SAFETY: caller guarantees an owned (live) array. unsafe { if crate::heap::rc(a as *mut Block) == 1 { return a; } let n = len(a); let cap = if extra == 0 { n } else { (2 * n).max(n + extra).max(MIN_GROW) }; let copy = from_items(ctx, items(a), cap); drop_value(ctx, a); copy } } /// The elements from `start` up to `end` (excluded), both clamped to /// `0..length`; empty when `end <= start`. /// /// # Safety /// `a` must be a live array. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_array_slice( ctx: *mut Ctx, a: Value, start: Value, end: Value, ) -> Value { // SAFETY: caller guarantees a live array. let items = unsafe { items(a) }; // SAFETY: caller guarantees live Ints. let clamp = |v: Value| unsafe { saturating(v) }.clamp(0, items.len() as i64) as usize; let (start, end) = (clamp(start), clamp(end)); let part = &items[start..end.max(start)]; from_items(ctx, part, part.len()) } #[cfg(test)] mod tests { use super::*; fn ints(a: Value) -> Vec { // SAFETY: tests pass live arrays of ints. unsafe { items(a) }.iter().map(|v| int_get(*v)).collect() } fn rc(v: Value) -> i32 { // SAFETY: tests pass live blocks. unsafe { (*(v as *mut Block)).header.rc } } /// Pushes stay in the block while there is room, then grow it. unsafe fn push_in_place_and_grow(ctx: *mut Ctx) { // SAFETY: every array is owned by this test. unsafe { let mut a = tl_array_with_capacity(ctx, int(2)); let first = a; for i in 0..2 { a = tl_array_push(ctx, a, int(i)); } assert_eq!((a, spare(a)), (first, 0)); for i in 2..100 { a = tl_array_push(ctx, a, int(i)); } assert_eq!(ints(a), (0..100).collect::>()); assert_eq!(spare(a) + 100, 128); drop_value(ctx, a); } } /// Updates copy an array someone else holds, and change a unique one. unsafe fn shared_arrays_are_copied(ctx: *mut Ctx) { // SAFETY: every value is owned by this test. unsafe { let list = list(ctx, (1..=3).map(int)); let a = tl_array_from_list(ctx, list); drop_value(ctx, list); dup_value(a); let b = tl_array_set(ctx, a, int(0), int(9)); assert_ne!(a, b); assert_eq!((ints(a), ints(b)), (vec![1, 2, 3], vec![9, 2, 3])); assert_eq!((rc(a), rc(b)), (1, 1)); dup_value(a); let c = tl_array_push(ctx, a, int(4)); assert_eq!((ints(a), ints(c)), (vec![1, 2, 3], vec![1, 2, 3, 4])); // The copy has room: the next push is in place. let d = tl_array_push(ctx, c, int(5)); assert_eq!(c, d); let e = tl_array_set(ctx, a, int(2), int(7)); assert_eq!((e, ints(e)), (a, vec![1, 2, 7])); for v in [b, d, e] { drop_value(ctx, v); } } } /// Elements are counted: read, sliced, replaced and dropped. unsafe fn elements_are_counted(ctx: *mut Ctx) { // SAFETY: every value is owned by this test. unsafe { let s = crate::values::tl_string_from(ctx, c"x".as_ptr(), 1); dup_value(s); // the list's reference let list = list(ctx, [s].into_iter()); let a = tl_array_from_list(ctx, list); drop_value(ctx, list); assert_eq!(rc(s), 2); let part = tl_array_slice(ctx, a, int(-5), int(9)); assert_eq!(rc(s), 3); let got = tl_array_get(ctx, part, int(0)); assert_eq!(rc(s), 4); let a = tl_array_set(ctx, a, int(0), int(1)); assert_eq!(rc(s), 3); assert_eq!(tl_array_get(ctx, a, int(1)), int(0)); for v in [a, part, got] { drop_value(ctx, v); } assert_eq!(rc(s), 1); drop_value(ctx, s); } } /// The scenarios run as one root actor, so drops have a context. unsafe extern "C" fn scenarios(ctx: *mut Ctx) -> Value { // SAFETY: `ctx` is the root actor's. unsafe { push_in_place_and_grow(ctx); shared_arrays_are_copied(ctx); elements_are_counted(ctx); } assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0); UNIT } #[test] fn updates_in_place_and_copies() { // SAFETY: `scenarios` follows the generated-code convention. assert_eq!(unsafe { crate::sched::run_test_actor(scenarios) }, 0); } }