← alloc

alloc/arena.kur

//! Bump allocation for `Copy` values that share one lifetime and access brand.
// alloc::arena -- a bump allocator over a chain of heap chunks (not one
// contiguous buffer, unlike `Vec!`). `Arena!::new` mints one brand `'k` and
// the arena keeps it for its whole life: `alloc` never rebrands, so a `Ref`
// obtained before a later allocation (even one that starts a new chunk)
// stays valid. The whole arena is freed as a unit by `Arena!::destroy`, the
// only place its memory goes away.
//
// The `Allocation!`/`RegionResume!` pair in `Arena!` covers the ROOT chunk's
// data buffer only. An `Allocation!` is the right to free one block, and an
// arena is many blocks under one brand, so no single record can stand for
// all of it. `destroy` consumes the caller's `Exclusive!['k]` through
// `RegionResume!::resume`, passes the rebuilt region to
// `Allocation!::release`, and frees the root buffer at the extent the
// allocator recorded. Chunks 2..n are allocated and freed inside this
// module, appear in no public signature, and are tracked by raw pointers.
//
// Unlike `Owned!` or `Vec!`, an arena does not track what it contains: it
// holds any number of values of different types with no way to walk them.
// `destroy` therefore cannot route every contained value through a
// consumer, so everything stored in an arena is `Copy`: `alloc`,
// `alloc_slice` and `ref_in` require it, and the arena collections
// (`ArenaVec`, `ArenaMap`, `ArenaSet`, `List`) require it of their
// elements. A linear value never enters an arena, so none is lost when the
// arena goes. Arenas are meant for `Copy` node data forming
// self-referential structures; their safety is aliasing safety through
// `Exclusive!`/`Ref`.
//
// `Chunk` and `Arena!` are restricted, so no other module can construct or
// destructure them. Forging an `Arena!` would pair a chunk chain with a
// brand it does not own, letting `alloc` hand out `'k` refs over foreign
// memory and `destroy` free a chain it never built; a forged `Chunk`'s
// `next`/`cap` would drive `free_chain_after_root_release`'s walk.

use package as alloc;

use alloc::heap::Uninit!;
use alloc::heap::HeapAllocator;
use core::cap::{Access, Brand, Exclusive!};
use core::mem::{Ref, alignof, sizeof};
use alloc::owned::Allocation!;
use core::mem::Region!;
use core::mem::RegionResume!;
use alloc::buffer::Buffer!;
use core::fmt::Writer;
use core::str::Str;
use core::ptr::offset;
use core::slice::{ReadBytes, Slice};
use core::option::Option;
use core::hash::Seed;
use alloc::heap::{checked_add, checked_mul};

/// One chunk of an arena: its data block, how many of its bytes are in
/// use, its size, and the chunk made before it (null for the root). Used by
/// `Arena!`; not meant for direct use.
struct Chunk {
    data: *u8,
    used: usize,
    cap: usize,
    next: *Chunk,
}

/// A bump allocator over a chain of heap chunks, every value in it under the
/// one brand `'k`.
///
/// `root`/`back` describe the root chunk's data buffer -- the block
/// `Arena!::new` allocates, over which `'k` was minted (see the module comment
/// for why only the root). `current` is the head of the chunk chain, and
/// `marker` is the same brand as a value, which `alloc` needs to brand the
/// pointers it computes. `seed` is what the arena's maps hash their keys
/// under (`ArenaMap`, `core::hash`).
forall 'k.
struct Arena! {
    root: Allocation![u8, 'k],
    back: RegionResume![u8, 'k],
    current: *Chunk,
    marker: Brand['k],
    seed: Seed,
}

/// The padding that brings the address `at` up to the next multiple of
/// `alignment`. `alignment` is a power of two (`core::mem::alignof`),
/// so this is a mask rather than a division. Callers pass the address, not
/// an offset into a chunk, so the result holds whatever alignment `malloc`
/// gave the chunk.
fn padding_for(at: usize, alignment: usize) -> usize {
    (0usize - at) & (alignment - 1usize)
}

/// Whether `need` bytes, after `padding`, fit in a chunk with `used` of its
/// `cap` bytes taken.
///
/// Check capacity by subtraction so wrapping usize addition cannot make an
/// out-of-bounds allocation appear to fit.
fn has_room(used: usize, cap: usize, padding: usize, need: usize) -> bool {
    if used > cap {
        false
    } else {
        let remaining = cap - used;
        if padding > remaining {
            false
        } else {
            need <= remaining - padding
        }
    }
}

/// Allocates the chunk header for an already-allocated data buffer. Kept
/// separate from `new_chunk` so that `Arena!::new` can pass the root buffer's
/// `Uninit!` straight to `Allocation!::adopt_value`, which records the
/// allocator's extent.
///
/// The header is a small, separate heap allocation (simpler than packing
/// it into the front of `data`, at the cost of one extra alloc/drop pair
/// per chunk), and is arena-private in every chunk including the root.
///
/// Caller: `data` is a live block of `cap` bytes that the chunk now owns,
/// and `next` is null or the arena's live current chunk.
unsafe fn new_header(data: *u8, cap: usize, next: *Chunk) -> *Chunk {
    let hdr_uninit = HeapAllocator::alloc(sizeof[Chunk]());
    let hdr_bytes = hdr_uninit.into_raw();
    let hdr = unsafe (hdr_bytes as *Chunk);
    let zero = 0usize;
    unsafe *hdr = Chunk.{ data, used: zero, cap, next };
    hdr
}

/// A fresh chunk ahead of `next`, the current one, with room for at least
/// `min_cap` bytes: twice `next`'s capacity up to 1 MiB, so a small arena
/// stays small and a large one takes few chunks, or bigger if the single
/// allocation that triggered growth needs more than that on its own. Used
/// for chunks 2..n only (`Arena!::new` builds the root itself, because the
/// root's buffer is the tracked one); its data buffer never becomes an
/// `Allocation!` and is freed by `free_chain_after_root_release`.
///
/// Caller: `next` is the arena's live current chunk.
unsafe fn new_chunk(min_cap: usize, next: *Chunk) -> *Chunk {
    let { data: _, used: _, cap: next_cap, next: _ } = unsafe *next;
    let max_cap = 1048576usize;
    let doubled = if next_cap >= max_cap / 2usize {
        max_cap
    } else {
        next_cap * 2usize
    };
    let base_cap = if doubled > 4096usize {
        doubled
    } else {
        4096usize
    };
    let cap = if min_cap > base_cap { min_cap } else { base_cap };
    let data_uninit = HeapAllocator::alloc(cap);
    let data = data_uninit.into_raw();
    unsafe new_header(data, cap, next)
}

/// Reserves `need` bytes at `alignment` in `cur`, growing into a new chunk
/// when it lacks room, and returns the chunk the bytes are in and their
/// address. Everything in `Arena!::alloc` that does not depend on its `T`,
/// kept out of it so each instantiation stays a few statements.
///
/// Caller: `cur` is the arena's live current chunk.
unsafe fn bump_chunk(cur: *Chunk, need: usize, alignment: usize) -> (*Chunk, *u8) {
    let { data: d, used: u, cap: c, next: n } = unsafe *cur;
    let padding = padding_for(unsafe (d as usize) + u, alignment);
    if has_room(u, c, padding, need) {
        let start = u + padding;
        unsafe *cur = Chunk.{ data: d, used: start + need, cap: c, next: n };
        (cur, unsafe offset(d, start))
    } else {
        // Room for the padding too, whatever alignment `malloc` gives.
        let fresh = unsafe new_chunk(checked_add(need, alignment), cur);
        let { data: d2, used: u2, cap: c2, next: n2 } = unsafe *fresh;
        let start = u2 + padding_for(unsafe (d2 as usize) + u2, alignment);
        unsafe *fresh = Chunk.{ data: d2, used: start + need, cap: c2, next: n2 };
        (fresh, unsafe offset(d2, start))
    }
}

/// Frees every chunk's header, plus every non-root chunk's data buffer.
///
/// Caller: `c` is the arena's current chunk, and `Arena!::destroy` has
/// already freed the root chunk's data buffer through `Allocation!::release` + `HeapAllocator::drop`, so freeing
/// it here would be a double free. The walk skips exactly the root because
/// the root is the chain's tail: `new_chunk` prepends (it stores
/// `next: cur`), `Arena!::new` builds the root with a null `next`, and
/// nothing else writes a chunk's `next`, so `next == null` holds for the
/// root alone.
unsafe fn free_chain_after_root_release(c: *Chunk) -> () {
    let z = 0usize;
    let nullc = unsafe (z as *Chunk);
    var cur = c;
    while cur != nullc {
        let { data: d, used: u, cap: cc, next: n } = unsafe *cur;
        let u2 = if n == nullc {
            ()
        } else {
            HeapAllocator::drop(unsafe HeapAllocator::adopt_raw(d))
        };
        let hb = unsafe (cur as *u8);
        let u3 = HeapAllocator::drop(unsafe HeapAllocator::adopt_raw(hb));
        cur = n;
    }
}

impl Arena! {
    /// A new arena with one 4 KiB chunk, under a fresh brand, with its
    /// capability; the maps made in it hash their keys under `seed`.
    fn new(seed: Seed) -> exists '1. (Exclusive!['1], Arena!['1]) {
        let z = 0usize;
        let nullchunk = unsafe (z as *Chunk);
        let cap = 4096usize;
        // The root chunk's data buffer goes straight from the allocator into
        // `Allocation!::adopt_value`, which mints and seals a fresh brand over
        // it, with its first byte zeroed.
        let exists 'open1. (a, rg) = Allocation!::adopt_value[u8](HeapAllocator::alloc(cap), 0u8);
        let (tag, base_ref, bk) = rg.share();
        // `share` hands the brand out inside the `Ref`; `Arena!` keeps it as
        // a value in `marker`, because `alloc` brands pointers this module
        // computes itself.
        let (d, am) = base_ref.into_parts();
        let c = unsafe new_header(d, cap, nullchunk);
        pack 'open1. (tag, Arena!.{ root: a, back: bk, current: c, marker: am, seed })
    }
}

forall 'k.
impl Arena!['k] {
    /// The arena's brand, for code that builds objects in its domain
    /// itself. Holding the arena is what entitles a caller to
    /// put new objects in its domain; the capability alone never does.
    fn marker(&self) -> Brand['k] {
        self.marker
    }

    /// The seed the arena's maps hash their keys under.
    fn seed(&self) -> Seed {
        self.seed
    }

    /// Puts `val` in the arena and hands back a `Ref` to it.
    ///
    /// Allocates naturally aligned room for one `T`, writes `val` into it,
    /// and hands back a `Ref` under the arena's own, never-changing brand --
    /// growing into a fresh chunk first if the current one doesn't have room
    /// for both alignment padding and the value, but never rebranding either
    /// way. `T` is `Copy`: the arena frees its chunks without reading them,
    /// so a linear value stored here would never reach its consumer.
    forall T where Copy[T], Sized[T].
    fn alloc(&self, &tag: Exclusive!['k], val: T) -> Ref[T, 'k] {
        let { root: a, back: bk, current: cur, marker: m, seed } = self;
        let (cur2, target) = unsafe bump_chunk(cur, sizeof[T](), alignof[T]());
        let target_t = unsafe (target as *T);
        unsafe *target_t = val;
        // `target_t` was just carved out of this arena's own chunk and
        // initialized; the arena's chunks are the domain `m` names.
        let r = unsafe Ref::from_raw(target_t, m);
        // `root`/`back` pass through untouched: growth adds a chunk rather
        // than moving the root, so the result keeps the same brand `'k`
        // whether or not growth happened, and this signature needs no
        // `exists` (unlike `Vec!::push`, which may relocate its one block).
        self = Arena!.{ root: a, back: bk, current: cur2, marker: m, seed };
        r
    }

    /// Fills `count` new elements of the arena with `fill` and hands back a
    /// view of them.
    ///
    /// Allocates room for `count` values of `T` in one naturally aligned
    /// block, writes `fill` into each, and hands back a view of them under
    /// the arena's brand, which, as with `alloc`, never changes. `T` is
    /// `Copy` because `fill` is written `count` times.
    forall T where Copy[T], Sized[T].
    fn alloc_slice(&self, &tag: Exclusive!['k], count: usize, fill: T) -> Slice[T, 'k] {
        let { root: a, back: bk, current: cur, marker: m, seed } = self;
        let (cur2, target) = unsafe bump_chunk(cur, checked_mul(count, sizeof[T]()), alignof[T]());
        let base = unsafe (target as *T);
        var i = 0usize;
        while i < count {
            unsafe *(unsafe offset(base, i)) = fill;
            i = i + 1usize;
        }
        self = Arena!.{ root: a, back: bk, current: cur2, marker: m, seed };
        // `count` values were just carved out of this arena's own chunk and
        // initialized; the arena's chunks are the domain `m` names.
        unsafe Slice::from_raw_parts(base, count, m)
    }

    /// Frees every chunk. See the module comment for why this cannot route
    /// every contained value through a consumer the way `Vec!`'s teardown
    /// does.
    ///
    /// The caller's witness is consumed by real work: `resume` demands this
    /// exact `Exclusive!['k]` and rebuilds the root chunk's `Region![u8,'k]`,
    /// `release` demands that complete region and returns the `Uninit!` whose
    /// base and extent `Allocation!::adopt_value` read off the allocator, and `drop`
    /// frees it. No `Ref` is constructed on the path. The remaining headers
    /// and non-root buffers are freed by `free_chain_after_root_release`.
    fn destroy(self, tag: Exclusive!['k]) -> () {
        let { root: a, back: bk, current: cur, marker: m, seed } = self;
        let rg = bk.resume(tag);
        let u = a.release(rg);
        let u2 = HeapAllocator::drop(u);
        unsafe free_chain_after_root_release(cur)
    }

    /// Bump-allocates `n` raw, uninitialized bytes and returns a bare
    /// pointer, with no brand. For a caller with a finished, exact-length run
    /// of bytes to copy in once (e.g. built in a scratch `Buffer!`), so the
    /// result can be read many times without linear tracking. Unlike `alloc`,
    /// nothing is written; the caller copies the bytes in (see `copy_bytes`).
    /// No alignment padding is added.
    ///
    /// Caller: writes the `n` bytes before reading any of them, and uses the
    /// pointer only while the arena lives.
    unsafe fn alloc_bytes(&self, n: usize) -> *u8 {
        let { root: a, back: bk, current: cur, marker: m, seed } = self;
        let { data: d, used: u, cap: c, next: nx } = unsafe *cur;
        let fits = has_room(u, c, 0usize, n);
        let cur2 = if fits {
            cur
        } else {
            unsafe new_chunk(n, cur)
        };
        let { data: d2, used: u2, cap: c2, next: n2 } = unsafe *cur2;
        let target = unsafe offset(d2, u2);
        let u3 = u2 + n;
        unsafe *cur2 = Chunk.{ data: d2, used: u3, cap: c2, next: n2 };
        self = Arena!.{ root: a, back: bk, current: cur2, marker: m, seed };
        target
    }
}

// ------------------------------------------------------------- contexts --
/// A context that lends an arena with its capability. It is what code that
/// allocates in domain `'k` takes, as `&cx: C` with
/// `where Allocate[C -> 'k, R]`, the way code that only reads or writes it
/// takes `core::cap::Access`. `Domain!['k]` is the plain pair; a program may
/// keep both in a context of its own and lend them through these instances.
///
///     let (tag, arena, rest) = Allocate[C -> 'k, R]::open(cx);
///     let r = &arena.alloc(&tag, value);
///     cx = Allocate[C -> 'k, R]::close(tag, arena, rest);
///
/// `Arena!::alloc`, `alloc_slice` and `alloc_bytes` are the primitives the
/// context forms below call once a context is open.
forall Self -> 'k, R.
trait Allocate {
    /// Takes the capability, the arena and the rest of the context out of `cx`.
    fn open(cx: Self) -> (Exclusive!['k], Arena!['k], R);
    /// Puts the capability, the arena and the rest back together as the context.
    fn close(tag: Exclusive!['k], arena: Arena!['k], rest: R) -> Self;
}

/// The seed the arena a context lends hashes its maps' keys under
/// (`Arena!::seed`).
forall 'k, C, R where Allocate[C -> 'k, R].
fn seed(&cx: C) -> Seed {
    var (tag, arena, rest) = Allocate[C -> 'k, R]::open(cx);
    let s = &arena.seed();
    cx = Allocate[C -> 'k, R]::close(tag, arena, rest);
    s
}

/// An arena with the one capability for its domain: the context for code
/// that reads, writes and allocates there (`Access`, `Allocate`), and reads
/// text of it (`ReadBytes`).
forall 'k.
exposed struct Domain! {
    tag: Exclusive!['k],
    arena: Arena!['k],
}

impl Domain! {
    /// A fresh, empty arena under a brand of its own, whose maps hash their
    /// keys under `seed`.
    fn new(seed: Seed) -> exists 'k. Domain!['k] {
        let exists 'k. (tag, arena) = Arena!::new(seed);
        pack 'k. Domain!.{ tag, arena }
    }
}

forall 'k.
impl Domain!['k] {
    /// Frees everything in the arena; nothing of its domain can be read after.
    fn destroy(self) {
        let { tag, arena } = self;
        arena.destroy(tag);
    }
}

/// A domain lends its capability, with its arena as the rest.
forall 'k.
instance Access[Domain!['k] -> 'k, Arena!['k]] {
    fn open(cx: Domain!['k]) -> (Exclusive!['k], Arena!['k]) {
        let { tag, arena } = cx;
        (tag, arena)
    }

    fn close(tag: Exclusive!['k], rest: Arena!['k]) -> Domain!['k] {
        Domain!.{ tag, arena: rest }
    }
}

/// A domain lends its arena with its capability.
forall 'k.
instance Allocate[Domain!['k] -> 'k, ()] {
    fn open(cx: Domain!['k]) -> (Exclusive!['k], Arena!['k], ()) {
        let { tag, arena } = cx;
        (tag, arena, ())
    }

    fn close(tag: Exclusive!['k], arena: Arena!['k], rest: ()) -> Domain!['k] {
        Domain!.{ tag, arena }
    }
}

/// Text of a domain is read through the domain itself, which lends its
/// capability to read it.
forall 'k.
instance ReadBytes[Domain!['k], Str['k]] {
    fn get(&cx: Domain!['k], bytes: Str['k], index: usize) -> Option[u8] {
        var { tag, arena } = cx;
        let b = bytes.get(&tag, index);
        cx = Domain!.{ tag, arena };
        b
    }

    fn len(&cx: Domain!['k], bytes: Str['k]) -> usize {
        bytes.len()
    }
}

/// `value`, put in the context's arena. `T` is `Copy`, as for
/// `Arena!::alloc`.
forall T, 'k, C, R where Copy[T], Allocate[C -> 'k, R], Sized[T].
fn ref_in(&cx: C, value: T) -> Ref[T, 'k] {
    var (tag, arena, rest) = Allocate[C -> 'k, R]::open(cx);
    let r = &arena.alloc(&tag, value);
    cx = Allocate[C -> 'k, R]::close(tag, arena, rest);
    r
}

impl Buffer! {
    /// The buffer's bytes copied into the context's arena in one block of
    /// exactly their length, as text that lives as long as the arena; the
    /// buffer is freed. `Buffer!::new().put("x").put(n).save(&cx)`.
    forall 'k, C, R where Allocate[C -> 'k, R].
    fn save(self, &cx: C) -> Str['k] {
        var (tag, arena, rest) = Allocate[C -> 'k, R]::open(cx);
        var buffer = self;
        let p = unsafe &buffer.as_ptr();
        let n = &buffer.len();
        let dest = unsafe &arena.alloc_bytes(n);
        let u = unsafe copy_bytes(dest, p, n);
        let u2 = buffer.destroy();
        let saved = unsafe Str::from_raw_parts_branded(dest, n, arena.marker);
        cx = Allocate[C -> 'k, R]::close(tag, arena, rest);
        saved
    }
}

/// The bytes of `text`, read under the capability `from` lends, copied into
/// the arena `to` lends: how text moves from one arena to another, so that
/// the first can be destroyed while the copy lives on.
forall 'j, 'k, C, R, D, Q where Access[C -> 'j, R], Allocate[D -> 'k, Q].
fn copy_str(text: Str['j], &from: C, &to: D) -> Str['k] {
    let (from_tag, from_rest) = Access[C -> 'j, R]::open(from);
    var (tag, arena, rest) = Allocate[D -> 'k, Q]::open(to);
    let (p, n) = text.into_parts();
    let dest = unsafe &arena.alloc_bytes(n);
    let u = unsafe copy_bytes(dest, p, n);
    let copied = unsafe Str::from_raw_parts_branded(dest, n, arena.marker);
    to = Allocate[D -> 'k, Q]::close(tag, arena, rest);
    from = Access[C -> 'j, R]::close(from_tag, from_rest);
    copied
}

/// The bytes of `first` then `second`, in one new block of the arena.
forall 'j, C, R where Allocate[C -> 'j, R].
fn concat(&cx: C, first: Str['j], second: Str['j]) -> Str['j] {
    let (tag, arena, rest) = Allocate[C -> 'j, R]::open(cx);
    var d = Domain!.{ tag, arena };
    let joined = Buffer!::new().write(&d, first).write(&d, second).save(&d);
    let { tag, arena } = d;
    cx = Allocate[C -> 'j, R]::close(tag, arena, rest);
    joined
}

/// Copies `count` bytes from `src` to `dest`, byte by byte (the same loop as
/// `Buffer!`'s `Writer::write_raw`). `alloc_bytes` only reserves room, so its
/// callers copy with this. Caller: `src[0..count)` is readable,
/// `dest[0..count)` writable, and the two do not overlap.
unsafe fn copy_bytes(dest: *u8, src: *u8, count: usize) -> () {
    var i = 0usize;
    while i < count {
        let s = unsafe offset(src, i);
        let v = unsafe *s;
        let d = unsafe offset(dest, i);
        unsafe *d = v;
        i = i + 1usize;
    }
}