← alloc

alloc/collections/arena_map.kur

//! Hash maps and sets stored in a caller-owned arena.
// A hash map, and a set on top of it, whose storage lives in the caller's
// `Arena!['k]` and that remember the order their keys were first inserted.
//
// The handles are `Copy`, like `ArenaVec`'s: each names one header in the
// arena, so a change made through one copy is seen through every other, and
// a map can sit inside other `Copy` arena data. Keys and values are `Copy`
// and are read and written whole; nothing hands out a reference into the
// map, so growing never leaves one dangling.
//
// Keys are hashed and compared through `core::hash::HashIn[K, C]`, under
// the same context `C` that lends the domain's capability (`Access`) and,
// to insert, the arena (`Allocate`): a key that points into the domain
// (text, a vec, a program's own tree) is read under that context.
// Every map of an arena hashes under the arena's seed (`Arena!::seed`,
// `core::hash`), which the map reads when it is made. The seed decides only
// where keys sit in the slots: what the map lists, and in what order, is
// the same under any seed.
//
// The entries are kept in insertion order in one `ArenaVec`, and the hash
// slots, open-addressed with linear probing, hold their indices. Removing a
// key marks its entry dead and keeps the order of the rest; inserting it
// again puts it at the end. `keys` and `values` list the live entries in
// order; `positions` and `key_at` read them in place, without copying. The
// slots are made at the first key, 8 of them, and made again (`grow`) when
// the entries, dead ones included, pass half the slots: a power of two
// more than twice the entries; nothing is freed until the arena is, so the
// old ones stay. When `grow` finds more dead entries than live ones, it first drops
// the dead ones, keeping the order of the rest, and places the live ones in
// the slots it has when they are enough. So a map whose keys come and go
// stays the size of what it holds, and takes no more of the arena.
//
// Each entry keeps the low 32 bits of its key's hash. A probe compares
// keys only where those bits agree, and making the slots again (`grow`,
// `clone`) places each live key by them without hashing or comparing it.

use package as alloc;

use alloc::arena::{Allocate, Domain!, ref_in, seed};
use alloc::collections::arena_vec::ArenaVec;
use alloc::heap::{checked_add, checked_mul};
use core::process::trap;
use core::cap::Access;
use core::hash::{HashIn, Seed, key_hash};
use core::mem::Ref;
use core::option::Option;
use core::slice::Slice;

/// A hash map in an arena, its keys in insertion order: a `Copy` handle
/// whose copies all name the same map.
forall K, V, 'k.
struct ArenaMap {
    state: Ref[MapState[K, V, 'k], 'k],
}

/// What an `ArenaMap`'s copies share, in the arena: its slots, its entries
/// and its count. Used by `ArenaMap`; not meant for direct use.
forall K, V, 'k.
struct MapState {
    // Indices into `entries`, plus one; zero for an empty slot. A power of
    // two long; none until the first key.
    slots: Option[Slice[usize, 'k]],
    // Every key inserted, in insertion order; a removed one stays, dead.
    entries: ArenaVec[Entry[K, V], 'k],
    count: usize,
    // The arena's seed (`Arena!::seed`), which every map of the arena
    // shares, so an entry's `hash` holds in any of them (`assign`).
    seed: Seed,
}

/// One key inserted into an `ArenaMap`, with its value, whether it is
/// still live, and its hash's low bits. Used by `ArenaMap`; not meant for
/// direct use.
forall K, V.
struct Entry {
    key: K,
    value: V,
    live: bool,
    // the low bits of `key_hash` of `key` under the map's seed
    hash: u32,
}

/// The bits of a key's hash under `seed` an entry keeps.
forall K, C where HashIn[K, C].
fn entry_hash(&cx: C, key: K, seed: Seed) -> u32 {
    key_hash(&cx, key, seed) as u32
}

/// Slot `i` of `slots`, read under `cx`; stops the program past the end.
/// Used by `ArenaMap`; not meant for direct use.
forall 'k, C, R where Access[C -> 'k, R].
fn slot_at(&cx: C, slots: Slice[usize, 'k], i: usize) -> usize {
    match slots.get_ref(i) {
        Some(at) => at.copy(&cx),
        None => trap(),
    }
}

/// Sets slot `i` of `slots` to `value` under `cx`; stops the program past
/// the end. Used by `ArenaMap`; not meant for direct use.
forall 'k, C, R where Access[C -> 'k, R].
fn set_slot(&cx: C, slots: Slice[usize, 'k], i: usize, value: usize) {
    match slots.get_ref(i) {
        Some(at) => at.set(&cx, value),
        None => trap(),
    }
}

forall K, V, 'k where Copy[K], Copy[V], Sized[K], Sized[V].
impl ArenaMap[K, V, 'k] {
    /// An empty map in the context's arena.
    forall C, R where Allocate[C -> 'k, R].
    fn new(&cx: C) -> ArenaMap[K, V, 'k] {
        let state = MapState.{ slots: Option::None, entries: ArenaVec::new(&cx), count: 0usize, seed: seed(&cx) };
        ArenaMap.{ state: ref_in(&cx, state) }
    }

    /// How many keys are in the map.
    forall C, R where Access[C -> 'k, R].
    fn len(self, &cx: C) -> usize {
        self.state.copy(&cx).count
    }

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

    /// The map's identity: equal for copies of one map, different for
    /// different maps.
    fn address(self) -> usize {
        self.state.address()
    }

    /// The number of positions `key_at` reads: one per key inserted since
    /// `grow` last dropped dead entries, in insertion order. Reading
    /// positions `0..positions()` visits the keys as `keys` lists them;
    /// removing a key meanwhile only empties its position, but inserting a
    /// new key may renumber them (`grow`).
    forall C, R where Access[C -> 'k, R].
    fn positions(self, &cx: C) -> usize {
        self.state.copy(&cx).entries.len(&cx)
    }

    /// The key at a position, unless it was removed.
    forall C, R where Access[C -> 'k, R].
    fn key_at(self, &cx: C, i: usize) -> Option[K] {
        let e = self.state.copy(&cx).entries.at(&cx, i);
        if e.live { Option::Some.(e.key) } else { Option::None }
    }

    // ------------------------------------------------------ combinators --
    // As `ArenaVec`'s: each lends its closure the context, and visits the
    // live entries in insertion order; searches stop at the first entry
    // that decides them.

    /// `f` on each key and its value, 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, K, V) -> ()) {
        let entries = self.state.copy(&cx).entries;
        var i = 0usize;
        while i < entries.len(&cx) {
            let e = entries.at(&cx, i);
            if e.live {
                f(&cx, e.key, e.value);
            }
            i = i + 1usize;
        }
    }

    /// Whether `f` holds for some key and its value.
    forall Env, C, R where Access[C -> 'k, R], Copy[Env].
    fn any(self, &cx: C, f: closure[Env](&_: C, K, V) -> bool) -> bool {
        let entries = self.state.copy(&cx).entries;
        var found = false;
        var i = 0usize;
        while !found && i < entries.len(&cx) {
            let e = entries.at(&cx, i);
            found = e.live && f(&cx, e.key, e.value);
            i = i + 1usize;
        }
        found
    }

    /// Whether `f` holds for every key and its value.
    forall Env, C, R where Access[C -> 'k, R], Copy[Env].
    fn all(self, &cx: C, f: closure[Env](&_: C, K, V) -> bool) -> bool {
        !self.any(&cx, |&c, k, v| !f(&c, k, v))
    }

    /// The live keys, in insertion order, in a new vec.
    forall C, R, Q where Access[C -> 'k, R], Allocate[C -> 'k, Q].
    fn keys(self, &cx: C) -> ArenaVec[K, 'k] {
        let entries = self.state.copy(&cx).entries;
        let out: ArenaVec[K, 'k] = ArenaVec::new(&cx);
        var i = 0usize;
        while i < entries.len(&cx) {
            let e = entries.at(&cx, i);
            if e.live {
                out.push(&cx, e.key);
            }
            i = i + 1usize;
        }
        out
    }

    /// The values, in their keys' insertion order, in a new vec.
    forall C, R, Q where Access[C -> 'k, R], Allocate[C -> 'k, Q].
    fn values(self, &cx: C) -> ArenaVec[V, 'k] {
        let entries = self.state.copy(&cx).entries;
        let out: ArenaVec[V, 'k] = ArenaVec::new(&cx);
        var i = 0usize;
        while i < entries.len(&cx) {
            let e = entries.at(&cx, i);
            if e.live {
                out.push(&cx, e.value);
            }
            i = i + 1usize;
        }
        out
    }
}

forall K, V, 'k where Copy[K], Copy[V], Sized[K], Sized[V].
impl ArenaMap[K, V, 'k] {
    /// The slot holding `key`, whose hash bits are `hash`, or the empty slot
    /// where it would go, and what that slot holds.
    forall C, R where Access[C -> 'k, R], HashIn[K, C].
    fn slot(self, &cx: C, slots: Slice[usize, 'k], entries: ArenaVec[Entry[K, V], 'k], key: K, hash: u32) -> (usize, usize) {
        let mask = slots.len() - 1usize;
        var i = (hash as usize) & mask;
        var entry = slot_at(&cx, slots, i);
        var found = false;
        while !found && entry != 0usize {
            let e = entries.at(&cx, entry - 1usize);
            found = e.hash == hash && HashIn[K, C]::eq_in(&cx, e.key, key);
            if !found {
                i = (i + 1usize) & mask;
                entry = slot_at(&cx, slots, i);
            }
        }
        (i, entry)
    }

    /// The position of a live key.
    forall C, R where Access[C -> 'k, R], HashIn[K, C].
    fn index(self, &cx: C, key: K) -> Option[usize] {
        let h = self.state.copy(&cx);
        let slots = match h.slots {
            Some(s) => s,
            None => return Option::None,
        };
        let (slot, entry) = self.slot(&cx, slots, h.entries, key, entry_hash(&cx, key, h.seed));
        if entry == 0usize || !h.entries.at(&cx, entry - 1usize).live {
            Option::None
        } else {
            Option::Some.(entry - 1usize)
        }
    }

    /// Whether `key` is in the map.
    forall C, R where Access[C -> 'k, R], HashIn[K, C].
    fn contains(self, &cx: C, key: K) -> bool {
        self.index(&cx, key).is_some()
    }

    /// The value of `key`, or `None` when it is not in the map.
    forall C, R where Access[C -> 'k, R], HashIn[K, C].
    fn get(self, &cx: C, key: K) -> Option[V] {
        match self.index(&cx, key) {
            Some(i) => Option::Some.(self.state.copy(&cx).entries.at(&cx, i).value),
            None => Option::None,
        }
    }

    /// The value of a key that must be in the map: without it, the process
    /// stops (`core::process::trap`).
    forall C, R where Access[C -> 'k, R], HashIn[K, C].
    fn at(self, &cx: C, key: K) -> V {
        match self.get(&cx, key) {
            Some(v) => v,
            None => trap(),
        }
    }

    /// The value of `key`, or `default` when it is not in the map.
    forall C, R where Access[C -> 'k, R], HashIn[K, C].
    fn get_or(self, &cx: C, key: K, default: V) -> V {
        match self.get(&cx, key) {
            Some(v) => v,
            None => default,
        }
    }

    /// Maps `key` to `value`, handing back the value it replaces, if any. A
    /// key already present is replaced, key and value, as
    /// `alloc::collections::hashmap` replaces one, and keeps its place in
    /// the order; a new key goes at the end, and so does a removed one
    /// coming back.
    forall C, R, Q where Access[C -> 'k, R], Allocate[C -> 'k, Q], HashIn[K, C].
    fn insert(self, &cx: C, key: K, value: V) -> Option[V] {
        let h = self.state.copy(&cx);
        let slots = match h.slots {
            Some(s) => s,
            None => {
                let fresh = slice_of_zeros(&cx, 8usize);
                self.state.set(&cx, MapState.{ slots: Option::Some.(fresh), entries: h.entries, count: h.count, seed: h.seed });
                fresh
            },
        };
        let hash = entry_hash(&cx, key, h.seed);
        let (slot, entry) = self.slot(&cx, slots, h.entries, key, hash);
        if entry != 0usize && h.entries.at(&cx, entry - 1usize).live {
            let old = h.entries.replace(&cx, entry - 1usize, Entry.{ key, value, live: true, hash });
            return Option::Some.(old.value);
        }
        set_slot(&cx, slots, slot, h.entries.len(&cx) + 1usize);
        h.entries.push(&cx, Entry.{ key, value, live: true, hash });
        self.state.set(&cx, MapState.{ slots: Option::Some.(slots), entries: h.entries, count: h.count + 1usize, seed: h.seed });
        if h.entries.len(&cx) * 2usize > slots.len() {
            self.grow(&cx, 0usize);
        }
        Option::None
    }

    /// The value of `key`; when it is not in the map, `default` is inserted
    /// under it first.
    forall C, R, Q where Access[C -> 'k, R], Allocate[C -> 'k, Q], HashIn[K, C].
    fn get_or_insert(self, &cx: C, key: K, default: V) -> V {
        match self.get(&cx, key) {
            Some(v) => v,
            None => {
                let none = self.insert(&cx, key, default);
                default
            },
        }
    }

    /// Maps `key` to `f` of its value, or of `default` when it is not in the
    /// map, and returns the new value. `f` is lent the context, as the
    /// combinators are. (`update`, elsewhere, lends a value in place.)
    forall Env, C, R, Q where Access[C -> 'k, R], Allocate[C -> 'k, Q], HashIn[K, C], Copy[Env].
    fn upsert(self, &cx: C, key: K, default: V, f: closure[Env](&_: C, V) -> V) -> V {
        let value = f(&cx, self.get_or(&cx, key, default));
        let old = self.insert(&cx, key, value);
        value
    }

    /// Takes `key` out of the map, handing back its value, if it was there.
    forall C, R where Access[C -> 'k, R], HashIn[K, C].
    fn remove(self, &cx: C, key: K) -> Option[V] {
        match self.index(&cx, key) {
            Some(i) => {
                let h = self.state.copy(&cx);
                let e = h.entries.at(&cx, i);
                h.entries.set(&cx, i, Entry.{ key: e.key, value: e.value, live: false, hash: e.hash });
                self.state.set(&cx, MapState.{ slots: h.slots, entries: h.entries, count: h.count - 1usize, seed: h.seed });
                Option::Some.(e.value)
            },
            None => Option::None,
        }
    }

    /// Makes the slots again, at least `slot_count` of them, every live key
    /// placed again by its hash bits. Their number is a power of two, at
    /// least 8 and more than twice the entries, whatever `slot_count` asks
    /// for, so the next insertion has room; the slots the map has are
    /// emptied and used again when there are that many, and the arena gives
    /// new ones otherwise. When more entries are dead than
    /// live, the dead ones are dropped first, the live ones keeping their
    /// order; positions (`key_at`) then count the live entries only.
    forall C, R, Q where Access[C -> 'k, R], Allocate[C -> 'k, Q].
    fn grow(self, &cx: C, slot_count: usize) {
        let h = self.state.copy(&cx);
        let total = h.entries.len(&cx);
        if total - h.count > h.count {
            var kept = 0usize;
            var k = 0usize;
            while k < total {
                let e = h.entries.at(&cx, k);
                if e.live {
                    h.entries.set(&cx, kept, e);
                    kept = kept + 1usize;
                }
                k = k + 1usize;
            }
            h.entries.truncate(&cx, kept);
        }
        let entries = h.entries.len(&cx);
        let wanted = if slot_count > checked_add(checked_mul(entries, 2usize), 2usize) {
            slot_count
        } else {
            checked_add(checked_mul(entries, 2usize), 2usize)
        };
        var count = 8usize;
        while count < wanted {
            count = checked_mul(count, 2usize);
        }
        // The slots the map has are emptied and kept when they are enough,
        // as after dropping dead entries; the arena gives new ones only for
        // more keys than the map has held.
        let slots = match h.slots {
            Some(s) => if s.len() >= count {
                zero_slots(&cx, s);
                s
            } else {
                slice_of_zeros(&cx, count)
            },
            None => slice_of_zeros(&cx, count),
        };
        self.state.set(&cx, MapState.{ slots: Option::Some.(slots), entries: h.entries, count: h.count, seed: h.seed });
        var k = 0usize;
        while k < entries {
            let e = h.entries.at(&cx, k);
            if e.live {
                place(&cx, slots, e.hash, k + 1usize);
            }
            k = k + 1usize;
        }
    }

    /// Keeps the entries `f` holds for, in their order, and removes the rest.
    ///
    /// `f` is lent the context, so it can change the map through a copy of
    /// its handle. The entries are visited by position as they stand after
    /// each call, and an entry `f` rejects is removed only if it is still
    /// live there; the count is the map's own at each removal, so it stays
    /// the number of live keys whatever `f` did. An insertion that makes the
    /// map drop its dead entries (`grow`) moves the live ones, so a call
    /// after it sees the entries from their new positions on.
    forall Env, C, R where Access[C -> 'k, R], Copy[Env].
    fn retain(self, &cx: C, f: closure[Env](&_: C, K, V) -> bool) {
        // The entries vec is the map's for its whole life: `grow`, `clear`
        // and `assign` change it in place.
        let entries = self.state.copy(&cx).entries;
        var i = 0usize;
        while i < entries.len(&cx) {
            let e = entries.at(&cx, i);
            if e.live && !f(&cx, e.key, e.value) && i < entries.len(&cx) {
                let now = entries.at(&cx, i);
                if now.live {
                    entries.set(&cx, i, Entry.{ key: now.key, value: now.value, live: false, hash: now.hash });
                    let h = self.state.copy(&cx);
                    self.state.set(&cx, MapState.{ slots: h.slots, entries: h.entries, count: h.count - 1usize, seed: h.seed });
                }
            }
            i = i + 1usize;
        }
    }

    /// The same live entries, in the same order, in a map of their own.
    forall C, R, Q where Access[C -> 'k, R], Allocate[C -> 'k, Q].
    fn clone(self, &cx: C) -> ArenaMap[K, V, 'k] {
        let h = self.state.copy(&cx);
        let entries: ArenaVec[Entry[K, V], 'k] = ArenaVec::new(&cx);
        if h.count == 0usize {
            return ArenaMap.{ state: ref_in(&cx, MapState.{ slots: Option::None, entries, count: 0usize, seed: h.seed }) };
        }
        var slot_count = 8usize;
        while h.count * 2usize > slot_count {
            slot_count = slot_count * 2usize;
        }
        let slots = slice_of_zeros(&cx, slot_count);
        var i = 0usize;
        while i < h.entries.len(&cx) {
            let e = h.entries.at(&cx, i);
            if e.live {
                place(&cx, slots, e.hash, entries.len(&cx) + 1usize);
                entries.push(&cx, e);
            }
            i = i + 1usize;
        }
        ArenaMap.{ state: ref_in(&cx, MapState.{ slots: Option::Some.(slots), entries, count: h.count, seed: h.seed }) }
    }
}

forall K, V, 'k where Copy[K], Copy[V], Sized[K], Sized[V].
impl ArenaMap[K, V, 'k] {
    /// Removes every key, keeping the room the map has for the keys
    /// inserted next. Slots far more than its entries need are let go, so
    /// that clearing costs in proportion to what the map held: a map that
    /// once held many keys does not empty all their slots every time.
    forall C, R where Access[C -> 'k, R].
    fn clear(self, &cx: C) {
        let h = self.state.copy(&cx);
        let slots = match h.slots {
            Some(s) => if s.len() > 16usize * h.entries.len(&cx) + 64usize {
                Option::None
            } else {
                zero_slots(&cx, s);
                h.slots
            },
            None => Option::None,
        };
        h.entries.clear(&cx);
        self.state.set(&cx, MapState.{ slots, entries: h.entries, count: 0usize, seed: h.seed });
    }

    /// Makes the map hold `other`'s live entries, in their order, in the
    /// room it already has: its entries are refilled in place, and its slots
    /// are cleared and kept while they are enough. A map loaded again and
    /// again (a scratch state) takes new room only to hold more keys than
    /// it has held before.
    forall C, R, Q where Access[C -> 'k, R], Allocate[C -> 'k, Q].
    fn assign(self, &cx: C, other: ArenaMap[K, V, 'k]) {
        if self.address() == other.address() {
            return;
        }
        self.clear(&cx);
        let from = other.state.copy(&cx);
        if from.count == 0usize {
            return;
        }
        let h = self.state.copy(&cx);
        var slot_count = 8usize;
        while from.count * 2usize > slot_count {
            slot_count = slot_count * 2usize;
        }
        let slots = match h.slots {
            Some(s) => if s.len() >= slot_count { s } else { slice_of_zeros(&cx, slot_count) },
            None => slice_of_zeros(&cx, slot_count),
        };
        var i = 0usize;
        while i < from.entries.len(&cx) {
            let e = from.entries.at(&cx, i);
            if e.live {
                place(&cx, slots, e.hash, h.entries.len(&cx) + 1usize);
                h.entries.push(&cx, e);
            }
            i = i + 1usize;
        }
        self.state.set(&cx, MapState.{ slots: Option::Some.(slots), entries: h.entries, count: from.count, seed: h.seed });
    }
}

/// Every slot emptied.
forall 'k, C, R where Access[C -> 'k, R].
fn zero_slots(&cx: C, slots: Slice[usize, 'k]) {
    var i = 0usize;
    while i < slots.len() {
        set_slot(&cx, slots, i, 0usize);
        i = i + 1usize;
    }
}

/// Puts `entry` in the first empty slot from where `hash` starts probing.
forall 'k, C, R where Access[C -> 'k, R].
fn place(&cx: C, slots: Slice[usize, 'k], hash: u32, entry: usize) {
    let mask = slots.len() - 1usize;
    var i = (hash as usize) & mask;
    while slot_at(&cx, slots, i) != 0usize {
        i = (i + 1usize) & mask;
    }
    set_slot(&cx, slots, i, entry);
}

/// `count` zeros in one block of the arena.
forall 'k, C, R where Allocate[C -> 'k, R].
fn slice_of_zeros(&cx: C, count: usize) -> Slice[usize, 'k] {
    var (tag, arena, rest) = Allocate[C -> 'k, R]::open(cx);
    let slots = &arena.alloc_slice(&tag, count, 0usize);
    cx = Allocate[C -> 'k, R]::close(tag, arena, rest);
    slots
}

/// A set, in insertion order: an `ArenaMap` whose values say nothing.
forall K, 'k.
struct ArenaSet {
    map: ArenaMap[K, bool, 'k],
}

forall K, 'k where Copy[K], Sized[K].
impl ArenaSet[K, 'k] {
    /// An empty set in the context's arena.
    forall C, R where Allocate[C -> 'k, R].
    fn new(&cx: C) -> ArenaSet[K, 'k] {
        ArenaSet.{ map: ArenaMap::new(&cx) }
    }

    /// How many keys are in the set.
    forall C, R where Access[C -> 'k, R].
    fn len(self, &cx: C) -> usize {
        self.map.len(&cx)
    }

    /// Whether the set holds no keys.
    forall C, R where Access[C -> 'k, R].
    fn is_empty(self, &cx: C) -> bool {
        self.map.is_empty(&cx)
    }

    /// The set's identity: equal for copies of one set, different for
    /// different sets.
    fn address(self) -> usize {
        self.map.address()
    }

    /// The number of positions `key_at` reads. As for `ArenaMap`: positions
    /// `0..positions()` hold the keys, or none where one was removed.
    forall C, R where Access[C -> 'k, R].
    fn positions(self, &cx: C) -> usize {
        self.map.positions(&cx)
    }

    /// The key at a position, unless it was removed.
    forall C, R where Access[C -> 'k, R].
    fn key_at(self, &cx: C, i: usize) -> Option[K] {
        self.map.key_at(&cx, i)
    }

    /// The keys, in insertion order, in a new vec.
    forall C, R, Q where Access[C -> 'k, R], Allocate[C -> 'k, Q].
    fn keys(self, &cx: C) -> ArenaVec[K, 'k] {
        self.map.keys(&cx)
    }

    /// `f` on each key, in insertion order.
    forall Env, C, R where Access[C -> 'k, R], Copy[Env].
    fn each(self, &cx: C, f: closure[Env](&_: C, K) -> ()) {
        self.map.each(&cx, |&c, k, v| f(&c, k));
    }

    /// Whether `f` holds for some key.
    forall Env, C, R where Access[C -> 'k, R], Copy[Env].
    fn any(self, &cx: C, f: closure[Env](&_: C, K) -> bool) -> bool {
        self.map.any(&cx, |&c, k, v| f(&c, k))
    }

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

    /// Whether `key` is in the set.
    forall C, R where Access[C -> 'k, R], HashIn[K, C].
    fn contains(self, &cx: C, key: K) -> bool {
        self.map.contains(&cx, key)
    }

    /// Adds `key`; whether it was not there before.
    forall C, R, Q where Access[C -> 'k, R], Allocate[C -> 'k, Q], HashIn[K, C].
    fn insert(self, &cx: C, key: K) -> bool {
        self.map.insert(&cx, key, true).is_none()
    }

    /// Adds each of `keys`, in order.
    forall C, R, Q where Access[C -> 'k, R], Allocate[C -> 'k, Q], HashIn[K, C].
    fn insert_all(self, &cx: C, keys: ArenaVec[K, 'k]) {
        var i = 0usize;
        while i < keys.len(&cx) {
            let fresh = self.insert(&cx, keys.at(&cx, i));
            i = i + 1usize;
        }
    }

    /// The keys of `self`, then those of `other` it lacks, in a new set.
    forall C, R, Q where Access[C -> 'k, R], Allocate[C -> 'k, Q], HashIn[K, C].
    fn union(self, &cx: C, other: ArenaSet[K, 'k]) -> ArenaSet[K, 'k] {
        let out = self.clone(&cx);
        out.insert_all(&cx, other.keys(&cx));
        out
    }

    /// The keys of `self` that `other` holds too, in `self`'s order, in a
    /// new set.
    forall C, R, Q where Access[C -> 'k, R], Allocate[C -> 'k, Q], HashIn[K, C].
    fn intersection(self, &cx: C, other: ArenaSet[K, 'k]) -> ArenaSet[K, 'k] {
        let out = self.clone(&cx);
        out.retain(&cx, |&c, k| other.contains(&c, k));
        out
    }

    /// The keys of `self` that `other` lacks, in `self`'s order, in a new
    /// set.
    forall C, R, Q where Access[C -> 'k, R], Allocate[C -> 'k, Q], HashIn[K, C].
    fn difference(self, &cx: C, other: ArenaSet[K, 'k]) -> ArenaSet[K, 'k] {
        let out = self.clone(&cx);
        out.retain(&cx, |&c, k| !other.contains(&c, k));
        out
    }

    /// Keeps the keys `f` holds for, in their order (`ArenaMap::retain`).
    forall Env, C, R where Access[C -> 'k, R], Copy[Env].
    fn retain(self, &cx: C, f: closure[Env](&_: C, K) -> bool) {
        self.map.retain(&cx, |&c, k, v| f(&c, k));
    }

    /// Takes `key` out; whether it was there.
    forall C, R where Access[C -> 'k, R], HashIn[K, C].
    fn remove(self, &cx: C, key: K) -> bool {
        self.map.remove(&cx, key).is_some()
    }

    /// The same keys, in the same order, in a set of their own.
    forall C, R, Q where Access[C -> 'k, R], Allocate[C -> 'k, Q], HashIn[K, C].
    fn clone(self, &cx: C) -> ArenaSet[K, 'k] {
        ArenaSet.{ map: self.map.clone(&cx) }
    }

    /// Removes every key, keeping the room (`ArenaMap::clear`).
    forall C, R where Access[C -> 'k, R].
    fn clear(self, &cx: C) {
        self.map.clear(&cx);
    }

    /// Makes the set hold `other`'s keys, in their order, in the room it
    /// already has (`ArenaMap::assign`).
    forall C, R, Q where Access[C -> 'k, R], Allocate[C -> 'k, Q].
    fn assign(self, &cx: C, other: ArenaSet[K, 'k]) {
        self.map.assign(&cx, other.map);
    }
}