← alloc

alloc/collections/arena_vec.kur

//! Growable sequences stored in a caller-owned arena.
// A growable sequence whose storage lives in the caller's `Arena!['k]`.
//
// The handle is `Copy`: it names one header in the arena, so every copy of
// it sees every change made through any other, and its brand never
// changes. That is the difference from `Vec!`, which owns one heap block
// and rebrands on every growth: an `ArenaVec` can sit inside other `Copy`
// arena data (a syntax tree's children, a table's rows).
//
// Elements never move. The storage is a run of segments, each twice the
// size of the one before, and growing adds a segment rather than copying
// into a bigger block, so nothing is left behind for the arena to hold: a
// vec of `n` elements takes under `2n` elements of room, plus a table of
// one pointer per segment after the first. A `Ref` from `get_ref` names its
// element for as long as the arena lives. The first segment holds at least
// 4 elements and at least 32 bytes, so short runs of bytes stay in one
// piece; `to_str` copies longer ones into one block of the arena.
//
// Elements are `Copy` and are read and written whole. Every access
// presents the domain's `Exclusive!['k]`, lent by a context (`Access`);
// growing also needs the arena itself (`Allocate`), which alone may put new
// blocks in its domain. Two accessors read an element: `get` (`None` past
// the end) and `at` (the element must be there; past the end the process
// stops), and `set`/`replace`/`insert`/`remove` take an index that must be
// in range.
//
// `Header` and `ArenaVec` are restricted: only this module builds or opens
// them. The unsafe reads and writes below rely on what that protects: the
// header's `segments` blocks are live arena memory of the sizes `locate`
// computes, segment 0 at `first` and segment `k` at `table[k - 1]`, and
// `len` never exceeds their total.

use package as alloc;

use alloc::arena::{Allocate, Arena!, Domain!};
use alloc::buffer::Buffer!;
use core::fmt::Writer;
use alloc::heap::{HeapAllocator, checked_mul};
use core::process::trap;
use core::cap::{Access, Exclusive!};
use core::cmp::Order;
use core::hash::{HashIn, HashState};
use core::mem::{Ref, sizeof};
use core::option::Option;
use core::str::Str;
use core::ptr::{null, offset};
use core::slice::Slice;

/// One bottom-up merge pass of `ArenaVec::sort_by`: merges each pair of
/// adjacent sorted runs of `width` elements of `src` into `dst`. Ties take
/// from the left run, which keeps the sort stable. Caller: `src` and `dst`
/// each hold `n` elements, in blocks that do not overlap.
forall T, Env, C where Copy[T], Copy[Env], Sized[T].
unsafe fn merge_runs(&cx: C, src: *T, dst: *T, n: usize, width: usize, cmp: closure[Env](&_: C, T, T) -> Order) {
    var lo = 0usize;
    while lo < n {
        let mid = if width < n - lo { lo + width } else { n };
        let hi = if width < n - mid { mid + width } else { n };
        var l = lo;
        var r = mid;
        var k = lo;
        while k < hi {
            var take_right = l >= mid;
            if !take_right && r < hi {
                take_right = match cmp(&cx, unsafe *(unsafe offset(src, r)), unsafe *(unsafe offset(src, l))) {
                    Less => true,
                    _ => false,
                };
            }
            if take_right {
                unsafe *(unsafe offset(dst, k)) = unsafe *(unsafe offset(src, r));
                r = r + 1usize;
            } else {
                unsafe *(unsafe offset(dst, k)) = unsafe *(unsafe offset(src, l));
                l = l + 1usize;
            }
            k = k + 1usize;
        }
        lo = hi;
    }
}

/// An `ArenaVec`'s length and segments, in the arena: segment 0, and a
/// table of the later ones, each twice as long as the one before. Used by
/// `ArenaVec`; not meant for direct use.
forall T, 'k.
struct Header {
    len: usize,
    segments: usize,
    // Segment 0, or null before the first element.
    first: *T,
    // Segments 1 and on, or null; room for the next power of two of
    // `segments - 1` pointers.
    table: *(*T),
}

/// A growable sequence in an arena whose elements never move: a `Copy`
/// handle whose copies all name the same vec.
forall T, 'k.
struct ArenaVec {
    header: Ref[Header[T, 'k], 'k],
}

/// The size of segment 0: at least 4 elements and 32 bytes, a power of two.
forall T.
fn first_capacity() -> usize {
    let size = sizeof[T]();
    if size >= 8usize {
        4usize
    } else if size >= 4usize {
        8usize
    } else if size >= 2usize {
        16usize
    } else {
        32usize
    }
}

/// The segment holding element `i`, and its offset there. Segment `k` holds
/// `first_capacity() << k` elements, and the segments before it
/// `first_capacity() * (2^k - 1)`.
forall T.
fn locate(i: usize) -> (usize, usize) {
    let b = first_capacity[T]();
    if i < b {
        return (0usize, i);
    }
    var q = i / b + 1usize;
    var k = 0usize;
    // `q >> 32`, written as two shifts so that it is 0, not undefined, where
    // `usize` has 32 bits.
    let high = (q >> 16usize) >> 16usize;
    if high != 0usize {
        k = 32usize;
        q = high;
    }
    if q >= 65536usize {
        k = k + 16usize;
        q = q >> 16usize;
    }
    if q >= 256usize {
        k = k + 8usize;
        q = q >> 8usize;
    }
    if q >= 16usize {
        k = k + 4usize;
        q = q >> 4usize;
    }
    if q >= 4usize {
        k = k + 2usize;
        q = q >> 2usize;
    }
    if q >= 2usize {
        k = k + 1usize;
    }
    (k, i - b * ((1usize << k) - 1usize))
}

/// Where element `i` of `h`'s storage lives. Caller: `i` is below the
/// capacity of `h`'s segments.
forall T, 'k.
unsafe fn place(h: Header[T, 'k], i: usize) -> *T {
    if i < first_capacity[T]() {
        return unsafe offset(h.first, i);
    }
    let (k, at) = locate[T](i);
    let base = if k == 0usize {
        h.first
    } else {
        unsafe *(unsafe offset(h.table, k - 1usize))
    };
    unsafe offset(base, at)
}

/// The number of elements `h`'s segments hold.
forall T, 'k.
fn capacity(h: Header[T, 'k]) -> usize {
    first_capacity[T]() * ((1usize << h.segments) - 1usize)
}

/// `h` with one more segment, its elements set to `fill`.
forall T, 'k where Copy[T], Sized[T].
fn add_segment(&tag: Exclusive!['k], &arena: Arena!['k], h: Header[T, 'k], fill: T) -> Header[T, 'k] {
    let k = h.segments;
    let block = &arena.alloc_slice(&tag, first_capacity[T]() << k, fill);
    let (base, size, marker) = block.into_parts();
    if k == 0usize {
        return Header.{ len: h.len, segments: 1usize, first: base, table: h.table };
    }
    // The table holds `k - 1` pointers; at a power of two it is full.
    let used = k - 1usize;
    let table = if used == 0usize || (used & (used - 1usize)) == 0usize {
        let grown = &arena.alloc_slice(&tag, if used == 0usize { 1usize } else { used * 2usize }, base);
        let (fresh, room, m) = grown.into_parts();
        var j = 0usize;
        while j < used {
            unsafe *(unsafe offset(fresh, j)) = unsafe *(unsafe offset(h.table, j));
            j = j + 1usize;
        }
        fresh
    } else {
        h.table
    };
    unsafe *(unsafe offset(table, used)) = base;
    Header.{ len: h.len, segments: k + 1usize, first: h.first, table }
}

// Every method takes the context by place, `&cx`: one that lends the
// domain's capability (`Access`) to read and write, one that lends the arena
// too (`Allocate`) to grow.
forall T, 'k where Copy[T], Sized[T].
impl ArenaVec[T, 'k] {
    /// An empty vec. It takes no room for elements until its first one.
    forall C, R where Allocate[C -> 'k, R].
    fn new(&cx: C) -> ArenaVec[T, 'k] {
        var (tag, arena, rest) = Allocate[C -> 'k, R]::open(cx);
        let header = &arena.alloc(&tag, Header.{ len: 0usize, segments: 0usize, first: null[T](), table: null[*T]() });
        cx = Allocate[C -> 'k, R]::close(tag, arena, rest);
        ArenaVec.{ header }
    }

    /// A vec holding `value`.
    forall C, R where Allocate[C -> 'k, R].
    fn one(&cx: C, value: T) -> ArenaVec[T, 'k] {
        let v: ArenaVec[T, 'k] = ArenaVec::new(&cx);
        v.push(&cx, value);
        v
    }

    /// A vec holding `a` then `b`.
    forall C, R where Allocate[C -> 'k, R].
    fn two(&cx: C, a: T, b: T) -> ArenaVec[T, 'k] {
        let v: ArenaVec[T, 'k] = ArenaVec::new(&cx);
        v.push(&cx, a);
        v.push(&cx, b);
        v
    }

    /// `count` copies of `fill`.
    forall C, R where Allocate[C -> 'k, R].
    fn filled(&cx: C, count: usize, fill: T) -> ArenaVec[T, 'k] {
        let v: ArenaVec[T, 'k] = ArenaVec::new(&cx);
        v.resize(&cx, count, fill);
        v
    }

    /// How many elements the vec holds.
    forall C, R where Access[C -> 'k, R].
    fn len(self, &cx: C) -> usize {
        self.header.copy(&cx).len
    }

    /// Whether the vec holds no elements.
    forall C, R where Access[C -> 'k, R].
    fn is_empty(self, &cx: C) -> bool {
        self.header.copy(&cx).len == 0usize
    }

    /// The vec's identity, as a number: equal for copies of one handle,
    /// different for different vecs (`Ref::address`).
    fn address(self) -> usize {
        self.header.address()
    }

    /// Element `i`, or `None` past the end.
    forall C, R where Access[C -> 'k, R].
    fn get(self, &cx: C, i: usize) -> Option[T] {
        var (tag, rest) = Access[C -> 'k, R]::open(cx);
        let h = self.header.copy(&tag);
        let value = if i < h.len {
            Option::Some.(unsafe *(unsafe place(h, i)))
        } else {
            Option::None
        };
        cx = Access[C -> 'k, R]::close(tag, rest);
        value
    }

    /// Element `i`, which must be there: past the end, the process stops
    /// (`core::process::trap`).
    forall C, R where Access[C -> 'k, R].
    fn at(self, &cx: C, i: usize) -> T {
        var (tag, rest) = Access[C -> 'k, R]::open(cx);
        let h = self.header.copy(&tag);
        if i >= h.len {
            trap();
        }
        let value = unsafe *(unsafe place(h, i));
        cx = Access[C -> 'k, R]::close(tag, rest);
        value
    }

    /// Where element `i` lives, or `None` past the end. Elements never move,
    /// so the place is the element's for as long as the arena lives.
    forall C, R where Access[C -> 'k, R].
    fn get_ref(self, &cx: C, i: usize) -> Option[Ref[T, 'k]] {
        var (tag, rest) = Access[C -> 'k, R]::open(cx);
        let h = self.header.copy(&tag);
        let found = if i < h.len {
            let (at, marker) = self.header.into_parts();
            // In range of the vec's segments, which are memory of this
            // arena's domain, the one the header's own brand names.
            Option::Some.(unsafe Ref::from_raw(unsafe place(h, i), marker))
        } else {
            Option::None
        };
        cx = Access[C -> 'k, R]::close(tag, rest);
        found
    }

    /// Puts `value` at `i`, which must be there, and hands back the value
    /// it replaces.
    forall C, R where Access[C -> 'k, R].
    fn replace(self, &cx: C, i: usize, value: T) -> T {
        var (tag, rest) = Access[C -> 'k, R]::open(cx);
        let h = self.header.copy(&tag);
        if i >= h.len {
            trap();
        }
        let at = unsafe place(h, i);
        let old = unsafe *at;
        unsafe *at = value;
        cx = Access[C -> 'k, R]::close(tag, rest);
        old
    }

    /// Puts `value` at `i`, which must be there.
    forall C, R where Access[C -> 'k, R].
    fn set(self, &cx: C, i: usize, value: T) {
        let old = self.replace(&cx, i, value);
    }

    /// The first element, or `None` when empty.
    forall C, R where Access[C -> 'k, R].
    fn first(self, &cx: C) -> Option[T] {
        self.get(&cx, 0usize)
    }

    /// The last element, or `None` when empty.
    forall C, R where Access[C -> 'k, R].
    fn last(self, &cx: C) -> Option[T] {
        let n = self.len(&cx);
        if n == 0usize {
            Option::None
        } else {
            self.get(&cx, n - 1usize)
        }
    }

    /// Adds `value` at the end, adding a segment first when the vec is full.
    forall C, R where Allocate[C -> 'k, R].
    fn push(self, &cx: C, value: T) {
        var (tag, arena, rest) = Allocate[C -> 'k, R]::open(cx);
        let h = self.header.copy(&tag);
        let h = if h.len < capacity(h) { h } else { add_segment(&tag, &arena, h, value) };
        unsafe *(unsafe place(h, h.len)) = value;
        self.header.set(&tag, Header.{ len: h.len + 1usize, segments: h.segments, first: h.first, table: h.table });
        cx = Allocate[C -> 'k, R]::close(tag, arena, rest);
    }

    /// Removes and hands back the last element, or `None` when empty.
    forall C, R where Access[C -> 'k, R].
    fn pop(self, &cx: C) -> Option[T] {
        var (tag, rest) = Access[C -> 'k, R]::open(cx);
        let h = self.header.copy(&tag);
        let value = if h.len == 0usize {
            Option::None
        } else {
            self.header.set(&tag, Header.{ len: h.len - 1usize, segments: h.segments, first: h.first, table: h.table });
            Option::Some.(unsafe *(unsafe place(h, h.len - 1usize)))
        };
        cx = Access[C -> 'k, R]::close(tag, rest);
        value
    }

    /// Keeps the first `len` elements; nothing changes when there are no
    /// more than that.
    forall C, R where Access[C -> 'k, R].
    fn truncate(self, &cx: C, len: usize) {
        var (tag, rest) = Access[C -> 'k, R]::open(cx);
        let h = self.header.copy(&tag);
        if len < h.len {
            self.header.set(&tag, Header.{ len, segments: h.segments, first: h.first, table: h.table });
        }
        cx = Access[C -> 'k, R]::close(tag, rest);
    }

    /// Removes every element, keeping the room.
    forall C, R where Access[C -> 'k, R].
    fn clear(self, &cx: C) {
        self.truncate(&cx, 0usize);
    }

    /// Grows to `len` elements, the new ones set to `fill`, or keeps the
    /// first `len`.
    forall C, R where Allocate[C -> 'k, R].
    fn resize(self, &cx: C, len: usize, fill: T) {
        var (tag, arena, rest) = Allocate[C -> 'k, R]::open(cx);
        var h = self.header.copy(&tag);
        while capacity(h) < len {
            h = add_segment(&tag, &arena, h, fill);
        }
        var i = h.len;
        while i < len {
            unsafe *(unsafe place(h, i)) = fill;
            i = i + 1usize;
        }
        self.header.set(&tag, Header.{ len, segments: h.segments, first: h.first, table: h.table });
        cx = Allocate[C -> 'k, R]::close(tag, arena, rest);
    }

    /// Pushes every element of `other`, in order. `other` may be `self`.
    forall C, R where Allocate[C -> 'k, R].
    fn append(self, &cx: C, other: ArenaVec[T, 'k]) {
        let (tag, arena, rest) = Allocate[C -> 'k, R]::open(cx);
        var d = Domain!.{ tag, arena };
        let n = other.len(&d);
        var i = 0usize;
        while i < n {
            self.push(&d, other.at(&d, i));
            i = i + 1usize;
        }
        let { tag, arena } = d;
        cx = Allocate[C -> 'k, R]::close(tag, arena, rest);
    }

    /// A new vec holding the same elements.
    forall C, R where Allocate[C -> 'k, R].
    fn clone(self, &cx: C) -> ArenaVec[T, 'k] {
        let copy: ArenaVec[T, 'k] = ArenaVec::new(&cx);
        copy.append(&cx, self);
        copy
    }

    /// The elements of `self`, then those of `other`, in a new vec; `append`
    /// adds them to `self` instead.
    forall C, R where Allocate[C -> 'k, R].
    fn concat(self, &cx: C, other: ArenaVec[T, 'k]) -> ArenaVec[T, 'k] {
        let out = self.clone(&cx);
        out.append(&cx, other);
        out
    }

    /// Elements `start` to `end`, each clamped to the vec, as a new vec.
    forall C, R where Allocate[C -> 'k, R].
    fn slice(self, &cx: C, start: usize, end: usize) -> ArenaVec[T, 'k] {
        let (tag, arena, rest) = Allocate[C -> 'k, R]::open(cx);
        var d = Domain!.{ tag, arena };
        let out: ArenaVec[T, 'k] = ArenaVec::new(&d);
        let n = self.len(&d);
        var i = start;
        while i < end && i < n {
            out.push(&d, self.at(&d, i));
            i = i + 1usize;
        }
        let { tag, arena } = d;
        cx = Allocate[C -> 'k, R]::close(tag, arena, rest);
        out
    }

    /// The elements from `start` on, as a new vec.
    forall C, R where Allocate[C -> 'k, R].
    fn skip(self, &cx: C, start: usize) -> ArenaVec[T, 'k] {
        let (tag, arena, rest) = Allocate[C -> 'k, R]::open(cx);
        var d = Domain!.{ tag, arena };
        let out = self.slice(&d, start, self.len(&d));
        let { tag, arena } = d;
        cx = Allocate[C -> 'k, R]::close(tag, arena, rest);
        out
    }

    /// Puts `value` at `i`, at most the length, moving the elements from
    /// there on one place up.
    forall C, R where Allocate[C -> 'k, R].
    fn insert(self, &cx: C, i: usize, value: T) {
        let (tag, arena, rest) = Allocate[C -> 'k, R]::open(cx);
        var d = Domain!.{ tag, arena };
        if i > self.len(&d) {
            trap();
        }
        self.push(&d, value);
        var j = self.len(&d) - 1usize;
        while j > i {
            self.set(&d, j, self.at(&d, j - 1usize));
            j = j - 1usize;
        }
        self.set(&d, i, value);
        let { tag, arena } = d;
        cx = Allocate[C -> 'k, R]::close(tag, arena, rest);
    }

    /// Takes out the element at `i`, which must be there, moving the ones
    /// after it one place down.
    forall C, R where Access[C -> 'k, R].
    fn remove(self, &cx: C, i: usize) -> T {
        var (tag, rest) = Access[C -> 'k, R]::open(cx);
        let value = self.at(&tag, i);
        var j = i;
        let n = self.len(&tag);
        while j + 1usize < n {
            self.set(&tag, j, self.at(&tag, j + 1usize));
            j = j + 1usize;
        }
        self.truncate(&tag, n - 1usize);
        cx = Access[C -> 'k, R]::close(tag, rest);
        value
    }

    /// Reverses the elements in place.
    forall C, R where Access[C -> 'k, R].
    fn reverse(self, &cx: C) {
        var (tag, rest) = Access[C -> 'k, R]::open(cx);
        var i = 0usize;
        var j = self.len(&tag);
        while i + 1usize < j {
            j = j - 1usize;
            let a = self.at(&tag, i);
            self.set(&tag, i, self.at(&tag, j));
            self.set(&tag, j, a);
            i = i + 1usize;
        }
        cx = Access[C -> 'k, R]::close(tag, rest);
    }

    /// Sorts in place by `cmp`, keeping equal elements in their order. A
    /// short vec is sorted by insertion; a longer one is copied into a heap
    /// block of twice its length, merge sorted there bottom-up (O(n log n)
    /// comparisons) and copied back, and the block is freed.
    forall Env, C, R where Access[C -> 'k, R], Copy[Env].
    fn sort_by(self, &cx: C, cmp: closure[Env](&_: C, T, T) -> Order) {
        let n = self.len(&cx);
        if n <= 16usize {
            self.insertion_sort(&cx, cmp);
            return;
        }
        let (raw, extent) = HeapAllocator::alloc(checked_mul(checked_mul(n, sizeof[T]()), 2usize)).into_parts();
        let first = unsafe (raw as *T);
        let second = unsafe offset(first, n);
        var i = 0usize;
        while i < n {
            unsafe *(unsafe offset(first, i)) = self.at(&cx, i);
            i = i + 1usize;
        }
        var src = first;
        var dst = second;
        var width = 1usize;
        while width < n {
            unsafe merge_runs(&cx, src, dst, n, width, cmp);
            let t = src;
            src = dst;
            dst = t;
            width = width * 2usize;
        }
        i = 0usize;
        while i < n {
            self.set(&cx, i, unsafe *(unsafe offset(src, i)));
            i = i + 1usize;
        }
        let u = HeapAllocator::drop(unsafe HeapAllocator::adopt_raw_sized(raw, extent));
    }

    /// Sorts in place by `cmp`, stably, by insertion: `sort_by`'s way for a
    /// short vec.
    forall Env, C, R where Access[C -> 'k, R], Copy[Env].
    fn insertion_sort(self, &cx: C, cmp: closure[Env](&_: C, T, T) -> Order) {
        var i = 1usize;
        while i < self.len(&cx) {
            let value = self.at(&cx, i);
            var j = i;
            var moving = true;
            while moving && j > 0usize {
                let before = self.at(&cx, j - 1usize);
                moving = match cmp(&cx, value, before) {
                    Less => true,
                    _ => false,
                };
                if moving {
                    self.set(&cx, j, before);
                    j = j - 1usize;
                }
            }
            self.set(&cx, j, value);
            i = i + 1usize;
        }
    }

    // ------------------------------------------------------ combinators --
    // The computation goes to the vec: each lends its closure the context,
    // so the closure reads other data of the domain and captures only
    // `Copy` values. Searches stop at the first element that decides them.

    /// `f` on each element, in order, for what it does through the context.
    forall Env, C, R where Access[C -> 'k, R], Copy[Env].
    fn each(self, &cx: C, f: closure[Env](&_: C, T) -> ()) {
        var i = 0usize;
        while i < self.len(&cx) {
            f(&cx, self.at(&cx, i));
            i = i + 1usize;
        }
    }

    /// The first element `f` returns a value for, and that value.
    forall U, Env, C, R where Access[C -> 'k, R], Copy[U], Copy[Env].
    fn find_map(self, &cx: C, f: closure[Env](&_: C, T) -> Option[U]) -> Option[U] {
        let n = self.len(&cx);
        var i = 0usize;
        var found = Option::None;
        while found.is_none() && i < n {
            found = f(&cx, self.at(&cx, i));
            i = i + 1usize;
        }
        found
    }

    /// The first element `f` holds for.
    forall Env, C, R where Access[C -> 'k, R], Copy[Env].
    fn find(self, &cx: C, f: closure[Env](&_: C, T) -> bool) -> Option[T] {
        self.find_map(&cx, |&c, x| if f(&c, x) { Option::Some.(x) } else { Option::None })
    }

    /// The index of the first element `f` holds for.
    forall Env, C, R where Access[C -> 'k, R], Copy[Env].
    fn position(self, &cx: C, f: closure[Env](&_: C, T) -> bool) -> Option[usize] {
        let n = self.len(&cx);
        var i = 0usize;
        var found = Option::None;
        while found.is_none() && i < n {
            if f(&cx, self.at(&cx, i)) {
                found = Option::Some.(i);
            }
            i = i + 1usize;
        }
        found
    }

    /// Whether `f` holds for some element.
    forall Env, C, R where Access[C -> 'k, R], Copy[Env].
    fn any(self, &cx: C, f: closure[Env](&_: C, T) -> bool) -> bool {
        self.position(&cx, f).is_some()
    }

    /// Whether `f` holds for every element.
    forall Env, C, R where Access[C -> 'k, R], Copy[Env].
    fn all(self, &cx: C, f: closure[Env](&_: C, T) -> bool) -> bool {
        !self.any(&cx, |&c, x| !f(&c, x))
    }

    /// How many elements `f` holds for.
    forall Env, C, R where Access[C -> 'k, R], Copy[Env].
    fn count(self, &cx: C, f: closure[Env](&_: C, T) -> bool) -> usize {
        var n = 0usize;
        var i = 0usize;
        while i < self.len(&cx) {
            if f(&cx, self.at(&cx, i)) {
                n = n + 1usize;
            }
            i = i + 1usize;
        }
        n
    }

    /// `acc` through `f` with each element, in order.
    forall A, Env, C, R where Access[C -> 'k, R], Copy[Env].
    fn fold(self, &cx: C, acc: A, f: closure[Env](&_: C, A, T) -> A) -> A {
        var acc = acc;
        var i = 0usize;
        while i < self.len(&cx) {
            acc = f(&cx, acc, self.at(&cx, i));
            i = i + 1usize;
        }
        acc
    }

    /// Each element through `f`, in a new vec.
    forall U, Env, C, R, Q where Allocate[C -> 'k, R], Access[C -> 'k, Q], Copy[U], Copy[Env], Sized[U].
    fn map(self, &cx: C, f: closure[Env](&_: C, T) -> U) -> ArenaVec[U, 'k] {
        let out: ArenaVec[U, 'k] = ArenaVec::new(&cx);
        var i = 0usize;
        while i < self.len(&cx) {
            let u = f(&cx, self.at(&cx, i));
            out.push(&cx, u);
            i = i + 1usize;
        }
        out
    }

    /// The elements `f` holds for, in a new vec.
    forall Env, C, R, Q where Allocate[C -> 'k, R], Access[C -> 'k, Q], Copy[Env].
    fn filter(self, &cx: C, f: closure[Env](&_: C, T) -> bool) -> ArenaVec[T, 'k] {
        let out: ArenaVec[T, 'k] = ArenaVec::new(&cx);
        var i = 0usize;
        while i < self.len(&cx) {
            let x = self.at(&cx, i);
            if f(&cx, x) {
                out.push(&cx, x);
            }
            i = i + 1usize;
        }
        out
    }
}

// Elements compared as keys are, through `HashIn` under the context.
forall T, 'k where Copy[T], Sized[T].
impl ArenaVec[T, 'k] {
    /// The index of the first element equal to `value`.
    forall C, R where Access[C -> 'k, R], HashIn[T, C].
    fn index_of(self, &cx: C, value: T) -> Option[usize] {
        self.position(&cx, |&c, x| HashIn[T, C]::eq_in(&c, x, value))
    }

    /// Whether some element equals `value`.
    forall C, R where Access[C -> 'k, R], HashIn[T, C].
    fn contains(self, &cx: C, value: T) -> bool {
        self.index_of(&cx, value).is_some()
    }

    /// Whether `other` has the same length, and equal elements in the same
    /// order.
    forall C, R where Access[C -> 'k, R], HashIn[T, C].
    fn eq(self, &cx: C, other: ArenaVec[T, 'k]) -> bool {
        let n = self.len(&cx);
        var same = n == other.len(&cx);
        var i = 0usize;
        while same && i < n {
            same = HashIn[T, C]::eq_in(&cx, self.at(&cx, i), other.at(&cx, i));
            i = i + 1usize;
        }
        same
    }
}

/// A vec as a key, hashed and compared element by element under the
/// domain's context.
forall T, 'k where Copy[T], Sized[T], HashIn[T, Domain!['k]].
instance HashIn[ArenaVec[T, 'k], Domain!['k]] {
    fn hash_in(&cx: Domain!['k], key: ArenaVec[T, 'k], state: HashState) -> HashState {
        let n = key.len(&cx);
        var state = state.write_u64(n as u64);
        var i = 0usize;
        while i < n {
            state = HashIn[T, Domain!['k]]::hash_in(&cx, key.at(&cx, i), state);
            i = i + 1usize;
        }
        state
    }

    fn eq_in(&cx: Domain!['k], a: ArenaVec[T, 'k], b: ArenaVec[T, 'k]) -> bool {
        a.eq(&cx, b)
    }
}

forall 'k.
impl ArenaVec[u8, 'k] {
    /// Pushes the bytes of `bytes`, text of the same domain. The text may
    /// view this vec's own bytes (`to_str`), even ones past its length after a
    /// `truncate`, which the push then overwrites: each byte is read before
    /// it is overwritten, as `memmove` does.
    forall C, R where Allocate[C -> 'k, R].
    fn push_str(self, &cx: C, bytes: Str['k]) {
        let n = bytes.len();
        if n == 0usize {
            return;
        }
        var (tag, arena, rest) = Allocate[C -> 'k, R]::open(cx);
        var h = self.header.copy(&tag);
        while capacity(h) < h.len + n {
            h = add_segment(&tag, &arena, h, 0u8);
        }
        // `bytes` is read under the domain's capability, which `tag` is.
        let (source, count) = bytes.into_parts();
        // Text over this vec lies in segment 0 (`to_str` copies a longer run
        // out), where the destination's bytes follow one another too. A
        // source that starts below the destination is copied from its end,
        // so no byte is overwritten before it is read; any other, from its
        // start.
        let destination = unsafe place(h, h.len);
        if unsafe (source as usize) < unsafe (destination as usize) {
            var i = n;
            while i > 0usize {
                i = i - 1usize;
                unsafe *(unsafe place(h, h.len + i)) = unsafe *(unsafe offset(source, i));
            }
        } else {
            var i = 0usize;
            while i < n {
                unsafe *(unsafe place(h, h.len + i)) = unsafe *(unsafe offset(source, i));
                i = i + 1usize;
            }
        }
        self.header.set(&tag, Header.{ len: h.len + n, segments: h.segments, first: h.first, table: h.table });
        cx = Allocate[C -> 'k, R]::close(tag, arena, rest);
    }

    /// Pushes the bytes of a literal.
    forall C, R where Allocate[C -> 'k, R].
    fn push_static(self, &cx: C, bytes: Str['static]) {
        let (tag, arena, rest) = Allocate[C -> 'k, R]::open(cx);
        var d = Domain!.{ tag, arena };
        self.push_str(&d, Str::from_static(&d, bytes));
        let { tag, arena } = d;
        cx = Allocate[C -> 'k, R]::close(tag, arena, rest);
    }

    /// The bytes the vec holds now, as text: a view of them while they
    /// fit the first segment, else a copy in one block of the arena. Later
    /// pushes do not lengthen it; a `set`, or a push after a `truncate`,
    /// rewrites the bytes of a view.
    forall C, R where Allocate[C -> 'k, R].
    fn to_str(self, &cx: C) -> Str['k] {
        var (tag, arena, rest) = Allocate[C -> 'k, R]::open(cx);
        let h = self.header.copy(&tag);
        let s = if h.len == 0usize {
            Str::empty(&tag)
        } else if h.segments == 1usize {
            // The first `len` bytes of segment 0: initialized, and arena
            // memory of the domain `tag` governs.
            unsafe Str::from_raw_parts(&tag, h.first, h.len)
        } else {
            let block = &arena.alloc_slice(&tag, h.len, 0u8);
            let (dest, size, marker) = block.into_parts();
            var i = 0usize;
            while i < h.len {
                unsafe *(unsafe offset(dest, i)) = unsafe *(unsafe place(h, i));
                i = i + 1usize;
            }
            block.as_str()
        };
        cx = Allocate[C -> 'k, R]::close(tag, arena, rest);
        s
    }
}

forall 'k.
impl ArenaVec[Str['k], 'k] {
    /// The pieces of `text` between occurrences of `separator`, in order:
    /// one more than there are occurrences, empty ones included. An empty
    /// separator occurs nowhere: the one piece is the whole text.
    forall C, R where Allocate[C -> 'k, R].
    fn split(&cx: C, text: Str['k], separator: Str['k]) -> ArenaVec[Str['k], 'k] {
        let (tag, arena, rest) = Allocate[C -> 'k, R]::open(cx);
        var d = Domain!.{ tag, arena };
        let pieces: ArenaVec[Str['k], 'k] = ArenaVec::new(&d);
        var start = 0usize;
        var going = true;
        if separator.len() == 0usize {
            pieces.push(&d, text);
            going = false;
        }
        while going {
            match text.find(&d, separator, start) {
                Some(at) => {
                    pieces.push(&d, text.slice(start, at));
                    start = at + separator.len();
                },
                None => {
                    pieces.push(&d, text.skip(start));
                    going = false;
                },
            }
        }
        let { tag, arena } = d;
        cx = Allocate[C -> 'k, R]::close(tag, arena, rest);
        pieces
    }

    /// The pieces' bytes with `separator` between each two, as one new text:
    /// `split`'s inverse.
    forall C, R where Allocate[C -> 'k, R].
    fn join(self, &cx: C, separator: Str['static]) -> Str['k] {
        let (tag, arena, rest) = Allocate[C -> 'k, R]::open(cx);
        var d = Domain!.{ tag, arena };
        var out = Buffer!::new();
        var i = 0usize;
        while i < self.len(&d) {
            if i > 0usize {
                out = out.put(separator);
            }
            out = out.write(&d, self.at(&d, i));
            i = i + 1usize;
        }
        let joined = out.save(&d);
        let { tag, arena } = d;
        cx = Allocate[C -> 'k, R]::close(tag, arena, rest);
        joined
    }
}