← alloc

alloc/collections/hashmap.kur

//! Owning hash maps and sets with separate chaining.
// A separate-chaining hash table. Like `alloc::collections::vec`, it owns
// its bucket array through an `Allocation!`/`RegionResume!` pair and hands
// out `Exclusive!`/`Ref` access, with no witness type of its own.
//
// `get`, `insert` and `remove` hash and compare keys through their
// `Hash`/`Eq` instances and are safe; `get_in`, `insert_in` and
// `remove_in` do the same for `Copy` keys read under a domain's capability
// (`HashIn`). Chains are walked in loops, so a long one costs no stack.
//
// The conventions, shared with `alloc::collections::arena_map`:
//
//   - A lookup is an `Option`: `get` is `None` for a missing key, `at`
//     stops the program (`core::process::trap`), `contains` says which.
//   - A key the map only looks up (`get`, `contains`, `remove`, `with`,
//     `update`) is lent by place, `&key`, so a linear key comes back
//     unchanged; a key the map keeps (`insert`) is moved in. `Copy` keys
//     (the `_in` forms, `ArenaMap`) are passed by value.
//   - `insert` of a key already present replaces the entry, key and
//     value, and hands back the ones it replaced: `Some.((key, value))`
//     here, `Some.(value)` where keys are `Copy` (`insert_in`, `ArenaMap`).
//   - `each` and `each_in` visit every entry in place and keep the map;
//     `drain` and `destroy_with` take it apart. A map whose keys own their
//     bytes (`Buffer!`) is looked up by a view of them with `find` and
//     `OwnedMap!`'s `find_with`/`find_update`, so no key is built to look
//     one up.
//   - Every map hashes its keys under a seed (`core::hash::Seed`): a
//     `HashMap!` the one it is made with, an `ArenaMap` its arena's. A
//     `HashMap!`'s `each`, `each_in` and `drain` visit the keys in an order
//     the seed decides, which a hosted program's seed
//     (`std::process::hash_seed`) changes from run to run; an `ArenaMap`
//     keeps insertion order.
//
// Keys and values each live in their own one-value allocation: `Entry`
// holds `*K`/`*V`, never `K`/`V` inline. A generic type parameter is not
// provably Copy, so an inline `key: K` could not be read out of a shared
// `Entry` and compared more than once in this generic code, whereas a raw
// pointer is always Copy. Keys and values are `Sized`, as a raw read or write
// is never at a zero-size type, so each allocation has bytes.
//
// Brand policy: `insert`, `remove` and `clear_with`, and the `_in` forms,
// always return a fresh `Exclusive!['2]`, minted by `Allocation!::adopt` and
// sealed by the operation's `exists '2.` return, whether or not an entry was
// added, replaced or freed. `len` and `is_empty` read the map's own count
// and present no capability; the lookups present the caller's
// `Exclusive!['k]` and hand it back. `insert` may replace the bucket array
// (`resize`) and frees the key it replaces, and `remove` frees the entry a `Ref` may name, so a `Ref[V,'k]` taken
// before either cannot be used after it, even though entries never move.
// `drain` and `destroy_with` consume the capability with the map.

use package as alloc;

use alloc::heap::Uninit!;
use alloc::heap::{AllocError, HeapAllocator, Storage, abort};
use alloc::heap::checked_mul;
use core::cap::Exclusive!;
use core::mem::{Ref, sizeof};
use core::ptr::{null, is_null, offset};
use alloc::owned::Allocation!;
use core::mem::Region!;
use core::mem::RegionResume!;
use core::hash::{Hash, Eq, HashIn, HashState, Seed};
use core::iter::{Iterator, Pair};
use core::option::{Option, Result};
use core::process::trap;

/// One key and value of a bucket's chain, and the next entry in it.
///
/// `Entry` stores only pointers, so it is Copy whatever `K` and `V` are; a
/// map with a linear value type, such as `HashMap![u32, Marker!]`, needs no
/// annotation here.
///
/// Neither `Entry` nor `HashMap!` is `exposed`, so other modules cannot
/// build or destructure them. The invariant protected is the tie between
/// `buckets`, `bucket_count` and the chains hanging off it: a forged
/// `HashMap!` with a mismatched `bucket_count` makes the bucket index run past
/// the allocation, and a forged `Entry` puts arbitrary addresses in front
/// of `free_one` and `destroy_chain`.
forall K, V.
struct Entry {
    key: *K,
    val: *V,
    next: *Entry[K, V],
}

/// A hash map that owns its keys and values, under brand `'k`, hashing
/// them under the seed it was made with (`core::hash`).
///
/// `alloc`/`back` describe the bucket array only. The per-entry `K`, `V`
/// and `Entry` allocations are single-value blocks reached through raw
/// pointers, freed by `free_one`, `take_chain` and `destroy_chain`, and
/// are not under a domain. The bucket array's free takes its address from
/// `alloc`, never from a `Ref`.
forall K, V, 'k.
struct HashMap! {
    alloc: Allocation![*Entry[K, V], 'k],
    back: RegionResume![*Entry[K, V], 'k],
    buckets: Ref[*Entry[K, V], 'k],
    bucket_count: usize,
    len: usize,
    seed: Seed,
}

/// Allocates a bucket array of `n` null slots and hands back the block
/// itself along with its base. Returning the `Uninit!` rather than a bare
/// pointer lets the caller pass it straight to `Allocation!::adopt` (the
/// only producer of an `Allocation!`) without re-stating a size; the
/// `into_parts`/`adopt_raw_sized` round trip keeps the extent the
/// allocator recorded. The allocation failure, when there is no block.
/// Caller: uses `base` only while the returned block, or the record that
/// adopts it, owns the storage.
forall K, V.
unsafe fn try_alloc_buckets(n: usize) -> Result[(Uninit!, *(*Entry[K, V])), AllocError] {
    let bytes = checked_mul(n, sizeof[*Entry[K, V]]());
    match Storage::try_alloc(bytes) {
        Err(e) => Result::Err.(e),
        Ok(u) => {
            let (raw, extent) = u.into_parts();
            let base = unsafe (raw as *(*Entry[K, V]));
            var i = 0usize;
            while i < n {
                let s = unsafe offset(base, i);
                unsafe *s = null();
                i = i + 1usize;
            }
            let u2 = unsafe HeapAllocator::adopt_raw_sized(raw, extent);
            Result::Ok.((u2, base))
        },
    }
}

/// `try_alloc_buckets`, aborting on failure. Caller: as for
/// `try_alloc_buckets`.
forall K, V.
unsafe fn alloc_buckets(n: usize) -> (Uninit!, *(*Entry[K, V])) {
    match unsafe try_alloc_buckets[K, V](n) {
        Ok(buckets) => buckets,
        Err(e) => unsafe abort(),
    }
}

/// A single value in its own allocation; used for both keys and values
/// (see the header for why neither lives inline in `Entry`). Caller: frees
/// the block once, through `free_one` or an entry's teardown, after moving
/// the value out or letting it go only if it is `Copy`.
forall T where Sized[T].
unsafe fn alloc_one(v: T) -> *T {
    let raw = HeapAllocator::alloc(sizeof[T]()).into_raw();
    let p = unsafe (raw as *T);
    unsafe *p = v;
    p
}

/// Frees what `alloc_one` allocated for `p`. Caller: `p` came from
/// `alloc_one`, is freed once, and holds no value still owed to anyone
/// (moved out, or `Copy`).
forall T.
unsafe fn free_one(p: *T) -> () {
    let raw = unsafe (p as *u8);
    HeapAllocator::drop(unsafe HeapAllocator::adopt_raw(raw));
}

/// A chain entry holding `key`, `val` and `next`, in its own allocation.
/// Caller: `key` and `val` are blocks from `alloc_one` that the entry now
/// owns, and `next` is null or an entry of the same chain. Used by
/// `put_chain` and `put_chain_in`; not meant for direct use.
forall K, V.
unsafe fn alloc_entry(key: *K, val: *V, next: *Entry[K, V]) -> *Entry[K, V] {
    let u = HeapAllocator::alloc(sizeof[Entry[K, V]]());
    let raw = u.into_raw();
    let p = unsafe (raw as *Entry[K, V]);
    let e = Entry.{ key, val, next };
    unsafe *p = e;
    p
}

/// Calls `f` once per entry (so linear `K`/`V` can be consumed), then frees
/// that entry's key, value and node allocations, walking the chain in a
/// loop. Caller: `head` is null or the first entry of a chain of live entries the map owns, which nothing else touches during the call, and no entry of it is reached again.
forall K, V where Sized[K], Sized[V].
unsafe fn destroy_chain(head: *Entry[K, V], f: fn(K, V) -> ()) -> () {
    var cur = head;
    while !is_null(cur) {
        let { key: kp, val: vp, next: nx } = unsafe *cur;
        f(unsafe *kp, unsafe *vp);
        unsafe free_one[K](kp);
        unsafe free_one[V](vp);
        HeapAllocator::drop(unsafe HeapAllocator::adopt_raw(unsafe (cur as *u8)));
        cur = nx;
    }
}

forall K, V where Sized[K], Sized[V].
impl HashMap![K, V] {
    /// An empty map with 8 buckets, under a fresh brand, that hashes its
    /// keys under `seed`, or the allocation failure. Growing it later
    /// (`insert`, which also allocates every entry) aborts on failure.
    fn try_new(seed: Seed) -> Result[exists '1. (Exclusive!['1], HashMap![K, V, '1]), AllocError] {
        let initial_buckets = 8usize;
        match unsafe try_alloc_buckets[K, V](initial_buckets) {
            Err(e) => Result::Err.(e),
            Ok(buckets) => {
                let (u, base) = buckets;
                // `adopt`'s obligation: `try_alloc_buckets` writes the null entry
                // to every one of the (at least 8) slots, so the block holds
                // initialized `*Entry`s.
                let exists 'open1. (a, rg) = unsafe Allocation!::adopt[*Entry[K, V]](u);
                let (tag, r, bk) = rg.share();
                Result::Ok.(pack 'open1. (tag, HashMap!.{ alloc: a, back: bk, buckets: r, bucket_count: initial_buckets, len: 0usize, seed }))
            },
        }
    }

    /// An empty map with 8 buckets, under a fresh brand, that hashes its
    /// keys under `seed`: `try_new`, aborting on failure.
    fn new(seed: Seed) -> exists '1. (Exclusive!['1], HashMap![K, V, '1]) {
        match HashMap!::try_new[K, V](seed) {
            Ok(map) => map,
            Err(e) => unsafe abort(),
        }
    }
}

forall K, V, 'k where Sized[K], Sized[V].
impl HashMap![K, V, 'k] {
    /// How many entries the map holds. The count is the map's own field,
    /// not a read of its storage, so no capability is presented.
    fn len(&self) -> usize {
        let { alloc: a, back: bk, buckets: r, bucket_count: bc, len: n, seed } = self;
        self = HashMap!.{ alloc: a, back: bk, buckets: r, bucket_count: bc, len: n, seed };
        n
    }

    /// Whether the map holds no entries.
    fn is_empty(&self) -> bool {
        &self.len() == 0usize
    }

    /// Consumes the map: calls `f` once per (key, value) pair, then frees
    /// every entry and the bucket array. The array's free takes its address
    /// from `alloc`, recorded by `Allocation!::adopt`; the per-entry frees in
    /// `destroy_chain` go through raw `*K`/`*V`/`*Entry` pointers.
    fn destroy_with(self, tag: Exclusive!['k], f: fn(K, V) -> ()) -> () {
        let { alloc: a, back: bk, buckets: r, bucket_count: bc, len: n, seed } = self;
        let (base, m) = r.into_parts();
        var i = 0usize;
        while i < bc {
            let s = unsafe offset(base, i);
            let head = unsafe *s;
            let u = unsafe destroy_chain[K, V](head, f);
            i = i + 1usize;
        }
        let rg = bk.resume(tag);
        let u0 = a.release(rg);
        HeapAllocator::drop(u0)
    }
}

// ---------------------------------------------------------------------
// The trait-based interface. Keys are hashed and compared through their
// own `Hash` and `Eq` instances rather than caller-supplied callbacks, so
// these operations are safe, and every key a call does not keep is handed
// back rather than dropped -- a linear key is never lost.

// A key the map only looks up is lent by place all the way down, so a
// lookup allocates nothing; a stored key is reached through its entry's
// pointer.

/// The hash of the key `k`, which is lent, under `seed`.
forall K where Hash[K].
fn hash_key(seed: Seed, &k: K) -> u64 {
    let (back, state) = k.hash(HashState::new(seed));
    k = back;
    state.finish()
}

/// Whether the stored key at `a` equals `b`; both are put back. Caller: `a`
/// is a live key block nothing else touches during the call.
forall K where Eq[K, K], Sized[K].
unsafe fn keys_equal(a: *K, &b: K) -> bool {
    let x = unsafe *a;
    let (x, y, same) = Eq[K, K]::eq(x, b);
    unsafe *a = x;
    b = y;
    same
}

/// The value block of the entry in the chain at `head` whose key equals
/// `key`, if any. Caller: `head` is null or the first entry of a chain of live entries the map owns, which nothing else touches during the call. Used by `HashMap!::get` and
/// `contains`; not meant for direct use.
forall K, V where Eq[K, K], Sized[K].
unsafe fn find_chain(head: *Entry[K, V], &key: K) -> Option[*V] {
    var cur = head;
    var found: Option[*V] = Option::None;
    while unsafe (cur as usize) != 0usize {
        let e = unsafe *cur;
        let { key: k, val: vp, next: nx } = e;
        cur = if unsafe keys_equal[K](k, &key) {
            found = Option::Some.(vp);
            null()
        } else {
            nx
        };
    }
    found
}

/// Stores `val` under the key at `key_ptr`, at the end of the chain when it
/// is new. When the key was already present, the entry takes the given key
/// and value, and the ones it held come back. The chain's new head, and
/// whether an entry was added. Caller: `head` is null or the first entry of a chain of live entries the map owns, which nothing else touches during the call; `key_ptr` is
/// an `alloc_one` block the chain now owns.
forall K, V where Eq[K, K], Sized[K], Sized[V].
unsafe fn put_chain(head: *Entry[K, V], key_ptr: *K, val: V) -> (*Entry[K, V], Option[(K, V)], bool) {
    var last = null();
    var cur = head;
    while !is_null(cur) {
        let { key: k, val: vp, next: nx } = unsafe *cur;
        // `key_ptr` is the new key's own block, which nothing else reaches.
        if unsafe keys_equal[K](k, unsafe &*key_ptr) {
            let stored = unsafe *k;
            unsafe free_one[K](k);
            unsafe *cur = Entry.{ key: key_ptr, val: vp, next: nx };
            let old = unsafe *vp;
            unsafe *vp = val;
            return (head, Option::Some.((stored, old)), false);
        }
        last = cur;
        cur = nx;
    }
    let added = unsafe alloc_entry[K, V](key_ptr, unsafe alloc_one[V](val), cur);
    (unsafe link_after[K, V](head, last, added), Option::None, true)
}

/// Unlinks the entry whose key equals `key`, handing back its stored key
/// and value. `key` is lent, and comes back. The chain's new head, and
/// whether an entry was removed. Caller: `head` is null or the first entry of a chain of live entries the map owns, which nothing else touches during the call.
forall K, V where Eq[K, K], Sized[K], Sized[V].
unsafe fn take_chain(head: *Entry[K, V], &key: K) -> (*Entry[K, V], Option[(K, V)], bool) {
    var last = null();
    var cur = head;
    while !is_null(cur) {
        let { key: k, val: vp, next: nx } = unsafe *cur;
        if unsafe keys_equal[K](k, &key) {
            let stored = unsafe *k;
            let old = unsafe *vp;
            unsafe free_one[K](k);
            unsafe free_one[V](vp);
            HeapAllocator::drop(unsafe HeapAllocator::adopt_raw(unsafe (cur as *u8)));
            return (unsafe link_after[K, V](head, last, nx), Option::Some.((stored, old)), true);
        }
        last = cur;
        cur = nx;
    }
    (head, Option::None, false)
}

/// Moves every entry of the chain at `head` to its bucket among the
/// `new_bc` at `new_base`. Caller: `head` is null or the first entry of a chain of live entries the map owns, which nothing else touches during the call; `new_base` holds `new_bc`
/// live slots. Used by `resize_hashed`; not meant for direct use.
forall K, V where Hash[K], Sized[K].
unsafe fn rehash_bucket_hashed(seed: Seed, head: *Entry[K, V], new_base: *(*Entry[K, V]), new_bc: usize) -> () {
    var cur = head;
    while unsafe (cur as usize) != 0usize {
        let e = unsafe *cur;
        let { key: k, val: vp, next: nx } = e;
        // `k` is this entry's key block, which only the entry reaches.
        let idx = (hash_key[K](seed, unsafe &*k) as usize) % new_bc;
        let slot = unsafe offset(new_base, idx);
        let old_head = unsafe *slot;
        unsafe *cur = Entry.{ key: k, val: vp, next: old_head };
        unsafe *slot = cur;
        cur = nx;
    }
}

/// A bucket array twice as long as the `old_bc` at `base`, every entry moved
/// into it, and its length; frees the old array `u_old`. Caller: `u_old`
/// is the map's bucket array, released from its record, and `base` its
/// base, holding `old_bc` chains the map owns. Used by `HashMap!::insert`;
/// not meant for direct use.
forall K, V where Hash[K], Sized[K].
unsafe fn resize_hashed(seed: Seed, u_old: Uninit!, base: *(*Entry[K, V]), old_bc: usize) -> (Uninit!, usize) {
    let new_bc = checked_mul(old_bc, 2usize);
    let (u_new, new_base) = unsafe alloc_buckets[K, V](new_bc);
    var i = 0usize;
    while i < old_bc {
        let head = unsafe *(unsafe offset(base, i));
        let u = unsafe rehash_bucket_hashed[K, V](seed, head, new_base, new_bc);
        i = i + 1usize;
    }
    let u2 = HeapAllocator::drop(u_old);
    (u_new, new_bc)
}

// The domain-keyed counterparts of the helpers above: `Copy` keys that
// point into a domain, hashed and compared through its capability `cx`
// (`HashIn`), which every helper borrows by place.

/// The hash of the domain key `key` under `seed`, read through `cx`. Used
/// by the `_in` operations; not meant for direct use.
forall K, C where Copy[K], HashIn[K, C].
fn hash_key_in(&cx: C, seed: Seed, key: K) -> u64 {
    HashIn[K, C]::hash_in(&cx, key, HashState::new(seed)).finish()
}

/// `find_chain` for a domain key, compared through `cx`. Caller: `head` is null or the first entry of a chain of live entries the map owns, which nothing else touches during the call.
/// Used by `HashMap!::get_in` and `contains_in`; not meant for direct use.
forall K, V, C where Copy[K], HashIn[K, C], Sized[K].
unsafe fn find_chain_in(&cx: C, head: *Entry[K, V], key: K) -> Option[*V] {
    var cur = head;
    var found: Option[*V] = Option::None;
    while unsafe (cur as usize) != 0usize {
        let e = unsafe *cur;
        let { key: k, val: vp, next: nx } = e;
        cur = if HashIn[K, C]::eq_in(&cx, unsafe *k, key) {
            found = Option::Some.(vp);
            null()
        } else {
            nx
        };
    }
    found
}

/// Stores `val` under `key`, at the end of the chain when it is new; an
/// entry already there takes `key` and `val` and hands back its value.
/// Caller: `head` is null or the first entry of a chain of live entries the map owns, which nothing else touches during the call.
forall K, V, C where Copy[K], HashIn[K, C], Sized[K], Sized[V].
unsafe fn put_chain_in(&cx: C, head: *Entry[K, V], key: K, val: V) -> (*Entry[K, V], Option[V], bool) {
    var last = null();
    var cur = head;
    while !is_null(cur) {
        let { key: k, val: vp, next: nx } = unsafe *cur;
        if HashIn[K, C]::eq_in(&cx, unsafe *k, key) {
            unsafe *k = key;
            let old = unsafe *vp;
            unsafe *vp = val;
            return (head, Option::Some.(old), false);
        }
        last = cur;
        cur = nx;
    }
    let added = unsafe alloc_entry[K, V](unsafe alloc_one[K](key), unsafe alloc_one[V](val), cur);
    (unsafe link_after[K, V](head, last, added), Option::None, true)
}

/// Unlinks `key`'s entry, handing back its value. Caller: `head` is null or the first entry of a chain of live entries the map owns, which nothing else touches during the call.
forall K, V, C where Copy[K], HashIn[K, C], Sized[K], Sized[V].
unsafe fn take_chain_in(&cx: C, head: *Entry[K, V], key: K) -> (*Entry[K, V], Option[V], bool) {
    var last = null();
    var cur = head;
    while !is_null(cur) {
        let { key: k, val: vp, next: nx } = unsafe *cur;
        if HashIn[K, C]::eq_in(&cx, unsafe *k, key) {
            let old = unsafe *vp;
            unsafe free_one[K](k);
            unsafe free_one[V](vp);
            HeapAllocator::drop(unsafe HeapAllocator::adopt_raw(unsafe (cur as *u8)));
            return (unsafe link_after[K, V](head, last, nx), Option::Some.(old), true);
        }
        last = cur;
        cur = nx;
    }
    (head, Option::None, false)
}

/// The chain `head` with `rest` linked after `last`, or `rest` itself when
/// `last` is null (`rest` then replaces the chain's start). Caller: `last`
/// is null or a live entry of the chain at `head`.
forall K, V.
unsafe fn link_after(head: *Entry[K, V], last: *Entry[K, V], rest: *Entry[K, V]) -> *Entry[K, V] {
    if is_null(last) {
        return rest;
    }
    let { key, val, next } = unsafe *last;
    unsafe *last = Entry.{ key, val, next: rest };
    head
}

/// `rehash_bucket_hashed` for domain keys, hashed through `cx`. Caller: as
/// for `rehash_bucket_hashed`. Used by `resize_in`; not meant for direct
/// use.
forall K, V, C where Copy[K], HashIn[K, C], Sized[K].
unsafe fn rehash_bucket_in(&cx: C, seed: Seed, head: *Entry[K, V], new_base: *(*Entry[K, V]), new_bc: usize) -> () {
    var cur = head;
    while unsafe (cur as usize) != 0usize {
        let e = unsafe *cur;
        let { key: k, val: vp, next: nx } = e;
        let h = hash_key_in[K, C](&cx, seed, unsafe *k);
        let idx = (h as usize) % new_bc;
        let slot = unsafe offset(new_base, idx);
        let old_head = unsafe *slot;
        unsafe *cur = Entry.{ key: k, val: vp, next: old_head };
        unsafe *slot = cur;
        cur = nx;
    }
}

/// `resize_hashed` for domain keys, hashed through `cx`. Caller: as for
/// `resize_hashed`. Used by `HashMap!::insert_in`; not meant for direct use.
forall K, V, C where Copy[K], HashIn[K, C], Sized[K].
unsafe fn resize_in(&cx: C, seed: Seed, u_old: Uninit!, base: *(*Entry[K, V]), old_bc: usize) -> (Uninit!, usize) {
    let new_bc = checked_mul(old_bc, 2usize);
    let (u_new, new_base) = unsafe alloc_buckets[K, V](new_bc);
    var i = 0usize;
    while i < old_bc {
        let head = unsafe *(unsafe offset(base, i));
        unsafe rehash_bucket_in[K, V, C](&cx, seed, head, new_base, new_bc);
        i = i + 1usize;
    }
    let u2 = HeapAllocator::drop(u_old);
    (u_new, new_bc)
}

forall K, V, 'k where Copy[K], Sized[K], Sized[V].
impl HashMap![K, V, 'k] {
    /// The value stored under a domain key, if any. This is `get` for a
    /// `Copy` key that points into a domain, hashed and compared through
    /// that domain's capability `cx` (lent by place).
    forall C where HashIn[K, C].
    fn get_in(&self, &tag: Exclusive!['k], &cx: C, key: K) -> Option[Ref[V, 'k]] {
        let { alloc: a, back: bk, buckets: r, bucket_count: bc, len: n, seed } = self;
        let (base, m) = r.into_parts();
        let h = hash_key_in[K, C](&cx, seed, key);
        let head = unsafe *(unsafe offset(base, (h as usize) % bc));
        let found_vp = unsafe find_chain_in[K, V, C](&cx, head, key);
        let found: Option[Ref[V, 'k]] = match found_vp {
            Some(vp) => Option::Some.(unsafe Ref::from_raw(vp, m)),
            None => Option::None,
        };
        self = HashMap!.{ alloc: a, back: bk, buckets: r, bucket_count: bc, len: n, seed };
        found
    }

    /// Whether a domain key is in the map.
    forall C where HashIn[K, C].
    fn contains_in(&self, &tag: Exclusive!['k], &cx: C, key: K) -> bool {
        (&self.get_in(&tag, &cx, key)).is_some()
    }

    /// Stores `val` under the domain key `key`, handing back the value it
    /// replaces: `insert` for a domain key. The map comes back freshly
    /// branded, as from `insert`.
    forall C where HashIn[K, C].
    fn insert_in(self, tag: Exclusive!['k], &cx: C, key: K, val: V) -> exists '2. (Exclusive!['2], HashMap![K, V, '2], Option[V]) {
        let { alloc: a, back: bk, buckets: r, bucket_count: bc, len: n, seed } = self;
        let (base, m) = r.into_parts();
        let h = hash_key_in[K, C](&cx, seed, key);
        let s = unsafe offset(base, (h as usize) % bc);
        let head = unsafe *s;
        let (new_head, found, is_new) = unsafe put_chain_in[K, V, C](&cx, head, key, val);
        unsafe *s = new_head;
        let new_len = if is_new { n + 1usize } else { n };
        let should_resize = is_new && new_len > bc * 3usize / 4usize;
        let rg = bk.resume(tag);
        let u0 = a.release(rg);
        let (u1, new_bc) = if should_resize {
            unsafe resize_in[K, V, C](&cx, seed, u0, base, bc)
        } else {
            (u0, bc)
        };
        // `adopt`'s obligation: `alloc_buckets` writes the null entry to every
        // one of the (at least 8) slots, so the block holds initialized `*Entry`s.
        let exists 'open1. (a2, rg2) = unsafe Allocation!::adopt[*Entry[K, V]](u1);
        let (tag2, r2, bk2) = rg2.share();
        pack 'open1. (tag2, HashMap!.{ alloc: a2, back: bk2, buckets: r2, bucket_count: new_bc, len: new_len, seed }, found)
    }

    /// Removes a domain key's entry, handing back its value: `remove` for a
    /// domain key. The entry's
    /// storage is freed, so the map comes back freshly branded, as from
    /// `remove`, and no `Ref` from `get_in` survives the call.
    forall C where HashIn[K, C].
    fn remove_in(self, tag: Exclusive!['k], &cx: C, key: K) -> exists '2. (Exclusive!['2], HashMap![K, V, '2], Option[V]) {
        let { alloc: a, back: bk, buckets: r, bucket_count: bc, len: n, seed } = self;
        let (base, m) = r.into_parts();
        let h = hash_key_in[K, C](&cx, seed, key);
        let s = unsafe offset(base, (h as usize) % bc);
        let head = unsafe *s;
        let (new_head, found, removed) = unsafe take_chain_in[K, V, C](&cx, head, key);
        unsafe *s = new_head;
        let new_len = if removed { n - 1usize } else { n };
        let rg = bk.resume(tag);
        let u0 = a.release(rg);
        // `adopt`'s obligation: `alloc_buckets` writes the null entry to every
        // one of the (at least 8) slots, so the block holds initialized `*Entry`s.
        let exists 'open1. (a2, rg2) = unsafe Allocation!::adopt[*Entry[K, V]](u0);
        let (tag2, r2, bk2) = rg2.share();
        pack 'open1. (tag2, HashMap!.{ alloc: a2, back: bk2, buckets: r2, bucket_count: bc, len: new_len, seed }, found)
    }
}

forall K, V, 'k where Hash[K], Eq[K, K], Sized[K], Sized[V].
impl HashMap![K, V, 'k] {
    /// Whether `key` is in the map.
    fn contains(&self, &tag: Exclusive!['k], &key: K) -> bool {
        (&self.get(&tag, &key)).is_some()
    }

    /// The value stored under `key`, if any.
    fn get(&self, &tag: Exclusive!['k], &key: K) -> Option[Ref[V, 'k]] {
        let { alloc: a, back: bk, buckets: r, bucket_count: bc, len: n, seed } = self;
        let (base, m) = r.into_parts();
        let idx = (hash_key[K](seed, &key) as usize) % bc;
        let head = unsafe *(unsafe offset(base, idx));
        let found_vp = unsafe find_chain[K, V](head, &key);
        let found: Option[Ref[V, 'k]] = match found_vp {
            Some(vp) => Option::Some.(unsafe Ref::from_raw(vp, m)),
            None => Option::None,
        };
        self = HashMap!.{ alloc: a, back: bk, buckets: r, bucket_count: bc, len: n, seed };
        found
    }

    /// Stores `val` under `key`. When `key` was already present, the entry
    /// takes `key` and `val`, and the stored key and value come back. The
    /// bucket array may move, so the map comes back freshly branded.
    fn insert(self, tag: Exclusive!['k], key: K, val: V) -> exists '2. (Exclusive!['2], HashMap![K, V, '2], Option[(K, V)]) {
        let { alloc: a, back: bk, buckets: r, bucket_count: bc, len: n, seed } = self;
        let (base, m) = r.into_parts();
        var key = key;
        let idx = (hash_key[K](seed, &key) as usize) % bc;
        let key_ptr = unsafe alloc_one[K](key);
        let s = unsafe offset(base, idx);
        let head = unsafe *s;
        let (new_head, found, is_new) = unsafe put_chain[K, V](head, key_ptr, val);
        unsafe *s = new_head;
        let new_len = if is_new { n + 1usize } else { n };
        let should_resize = is_new && new_len > bc * 3usize / 4usize;
        let rg = bk.resume(tag);
        let u0 = a.release(rg);
        let (u1, new_bc) = if should_resize {
            unsafe resize_hashed[K, V](seed, u0, base, bc)
        } else {
            (u0, bc)
        };
        // `adopt`'s obligation: `alloc_buckets` writes the null entry to every
        // one of the (at least 8) slots, so the block holds initialized `*Entry`s.
        let exists 'open1. (a2, rg2) = unsafe Allocation!::adopt[*Entry[K, V]](u1);
        let (tag2, r2, bk2) = rg2.share();
        pack 'open1. (tag2, HashMap!.{ alloc: a2, back: bk2, buckets: r2, bucket_count: new_bc, len: new_len, seed }, found)
    }

    /// Removes the entry stored under `key`, handing back its stored key and
    /// value.
    fn remove(self, tag: Exclusive!['k], &key: K) -> exists '2. (Exclusive!['2], HashMap![K, V, '2], Option[(K, V)]) {
        let { alloc: a, back: bk, buckets: r, bucket_count: bc, len: n, seed } = self;
        let (base, m) = r.into_parts();
        let idx = (hash_key[K](seed, &key) as usize) % bc;
        let s = unsafe offset(base, idx);
        let head = unsafe *s;
        let (new_head, found, removed) = unsafe take_chain[K, V](head, &key);
        unsafe *s = new_head;
        let new_len = if removed { n - 1usize } else { n };
        let rg = bk.resume(tag);
        let u0 = a.release(rg);
        // `adopt`'s obligation: `alloc_buckets` writes the null entry to every
        // one of the (at least 8) slots, so the block holds initialized `*Entry`s.
        let exists 'open1. (a2, rg2) = unsafe Allocation!::adopt[*Entry[K, V]](u0);
        let (tag2, r2, bk2) = rg2.share();
        pack 'open1. (tag2, HashMap!.{ alloc: a2, back: bk2, buckets: r2, bucket_count: bc, len: new_len, seed }, found)
    }
}

/// Whether the stored key at `k` equals the probe `q`; both are put back.
/// Caller: `k` is a live key block nothing else touches during the call.
forall K, Q where Eq[K, Q], Sized[K].
unsafe fn key_matches(k: *K, &q: Q) -> bool {
    let x = unsafe *k;
    let (x, y, same) = Eq[K, Q]::eq(x, q);
    unsafe *k = x;
    q = y;
    same
}

/// `find_chain` by a probe of another type (`Eq[K, Q]`). Caller: `head` is null or the first entry of a chain of live entries the map owns, which nothing else touches during the call.
/// Used by `HashMap!::find`; not meant for direct use.
forall K, V, Q where Eq[K, Q], Sized[K].
unsafe fn find_chain_by(head: *Entry[K, V], &probe: Q) -> Option[*V] {
    var cur = head;
    var found: Option[*V] = Option::None;
    while unsafe (cur as usize) != 0usize {
        let e = unsafe *cur;
        let { key: k, val: vp, next: nx } = e;
        cur = if unsafe key_matches[K, Q](k, &probe) {
            found = Option::Some.(vp);
            null()
        } else {
            nx
        };
    }
    found
}

forall K, V, 'k where Sized[K], Sized[V].
impl HashMap![K, V, 'k] {
    /// Looks up by a probe of another type that hashes like the stored keys
    /// and compares equal to the one it stands for -- typically a borrowed
    /// view of an owned key (`Readable` for `Buffer!`, see `core::borrow`),
    /// so a lookup needs no owned key. The probe comes back.
    forall Q where Hash[Q], Eq[K, Q].
    fn find(&self, &tag: Exclusive!['k], &probe: Q) -> Option[Ref[V, 'k]] {
        let { alloc: a, back: bk, buckets: r, bucket_count: bc, len: n, seed } = self;
        let (base, m) = r.into_parts();
        let idx = (hash_key[Q](seed, &probe) as usize) % bc;
        let head = unsafe *(unsafe offset(base, idx));
        let found_vp = unsafe find_chain_by[K, V, Q](head, &probe);
        let found: Option[Ref[V, 'k]] = match found_vp {
            Some(vp) => Option::Some.(unsafe Ref::from_raw(vp, m)),
            None => Option::None,
        };
        self = HashMap!.{ alloc: a, back: bk, buckets: r, bucket_count: bc, len: n, seed };
        found
    }
}

// ---------------------------------------------------------------------
// Visiting: every entry, lent where it lives, the map kept.

forall K, V, 'k where Sized[K], Sized[V].
impl HashMap![K, V, 'k] {
    /// Calls `f` on each key and its value where they live, in no
    /// particular order: `f` gets both through `&`, and nothing is copied
    /// out or back. The map stays as it is, apart from what `f` does to the
    /// values. A key `f` changes stays in the bucket of its old hash, so a
    /// lookup may then miss it; nothing worse comes of it.
    forall Env where Copy[Env].
    fn each(&self, &tag: Exclusive!['k], f: closure[Env](&_: K, &_: V) -> ()) {
        let { alloc: a, back: bk, buckets: r, bucket_count: bc, len: n, seed } = self;
        let (base, m) = r.into_parts();
        var i = 0usize;
        while i < bc {
            var cur = unsafe *(unsafe offset(base, i));
            while !is_null(cur) {
                let { key: kp, val: vp, next: nx } = unsafe *cur;
                // The entry's key and value blocks, which only the entry
                // reaches, and nothing else runs while `f` does.
                f(unsafe &*kp, unsafe &*vp);
                cur = nx;
            }
            i = i + 1usize;
        }
        self = HashMap!.{ alloc: a, back: bk, buckets: r, bucket_count: bc, len: n, seed };
    }

    /// `each`, with a context `cx` lent to `f` beside each key and value:
    /// the linear values `f` works on, which it cannot capture (an output
    /// to write the entries to, say).
    forall C, Env where Copy[Env].
    fn each_in(&self, &tag: Exclusive!['k], &cx: C, f: closure[Env](&_: K, &_: V, &_: C) -> ()) {
        let { alloc: a, back: bk, buckets: r, bucket_count: bc, len: n, seed } = self;
        let (base, m) = r.into_parts();
        var i = 0usize;
        while i < bc {
            var cur = unsafe *(unsafe offset(base, i));
            while !is_null(cur) {
                let { key: kp, val: vp, next: nx } = unsafe *cur;
                // As in `each`; `cx` is the caller's own place.
                f(unsafe &*kp, unsafe &*vp, &cx);
                cur = nx;
            }
            i = i + 1usize;
        }
        self = HashMap!.{ alloc: a, back: bk, buckets: r, bucket_count: bc, len: n, seed };
    }

    /// Removes every entry, handing each to `f`, and keeps the bucket array,
    /// so the map holds as many again without growing. The entries' storage
    /// is freed, so the map comes back freshly branded, as from `remove`.
    fn clear_with(self, tag: Exclusive!['k], f: fn(K, V) -> ()) -> exists '2. (Exclusive!['2], HashMap![K, V, '2]) {
        let { alloc: a, back: bk, buckets: r, bucket_count: bc, len: n, seed } = self;
        let (base, m) = r.into_parts();
        var i = 0usize;
        while i < bc {
            let s = unsafe offset(base, i);
            unsafe destroy_chain[K, V](unsafe *s, f);
            unsafe *s = null();
            i = i + 1usize;
        }
        let rg = bk.resume(tag);
        let u0 = a.release(rg);
        // `adopt`'s obligation: every one of the (at least 8) slots holds the
        // null entry, an initialized `*Entry`.
        let exists 'open1. (a2, rg2) = unsafe Allocation!::adopt[*Entry[K, V]](u0);
        let (tag2, r2, bk2) = rg2.share();
        pack 'open1. (tag2, HashMap!.{ alloc: a2, back: bk2, buckets: r2, bucket_count: bc, len: 0usize, seed })
    }
}

/// Lets a `Copy` key and value go: the callback `destroy` and `clear` pass
/// to `destroy_with` and `clear_with`. Not meant for direct use.
forall K, V where Copy[K], Copy[V].
fn forget_entry(key: K, value: V) -> () {
    ()
}

forall K, V, 'k where Copy[K], Copy[V], Sized[K], Sized[V].
impl HashMap![K, V, 'k] {
    /// Frees a map of `Copy` keys and values, which need no per-entry callback.
    fn destroy(self, tag: Exclusive!['k]) -> () {
        self.destroy_with(tag, forget_entry[K, V])
    }
}

// ---------------------------------------------------------------------
// Draining: the map's entries, moved out one at a time.

/// The map being taken apart: the bucket being walked, and the entry in it
/// that comes next. Holds the map's capability, so nothing else can touch
/// the entries meanwhile.
forall K, V, 'k.
struct Drain! {
    alloc: Allocation![*Entry[K, V], 'k],
    back: RegionResume![*Entry[K, V], 'k],
    tag: Exclusive!['k],
    base: *(*Entry[K, V]),
    bucket_count: usize,
    next_bucket: usize,
    cur: *Entry[K, V],
}

forall K, V, 'k where Sized[K], Sized[V].
impl HashMap![K, V, 'k] {
    /// Every entry, as an `Iterator` of owned `(key, value)` pairs, in no
    /// particular order. `Drain!::finish` frees what is left.
    fn drain(self, tag: Exclusive!['k]) -> Drain![K, V, 'k] {
        let { alloc: a, back: bk, buckets: r, bucket_count: bc, len: n, seed } = self;
        let (base, m) = r.into_parts();
        Drain!.{ alloc: a, back: bk, tag, base, bucket_count: bc, next_bucket: 0usize, cur: null() }
    }
}

forall K, V, 'k where Sized[K], Sized[V].
impl Drain![K, V, 'k] {
    /// The next entry, moved out of the map and freed from it.
    fn take(&self) -> Option[(K, V)] {
        var { alloc, back, tag, base, bucket_count, next_bucket, cur } = self;
        // The drain holds the map's capability, so `base` and every entry
        // reached from it are still the map's own.
        while is_null(cur) && next_bucket < bucket_count {
            cur = unsafe *(unsafe offset(base, next_bucket));
            unsafe *(unsafe offset(base, next_bucket)) = null();
            next_bucket = next_bucket + 1usize;
        }
        if is_null(cur) {
            self = Drain!.{ alloc, back, tag, base, bucket_count, next_bucket, cur };
            return Option::None;
        }
        let e = unsafe *cur;
        let { key: kp, val: vp, next: nx } = e;
        let k = unsafe *kp;
        let v = unsafe *vp;
        let u1 = unsafe free_one[K](kp);
        let u2 = unsafe free_one[V](vp);
        let u3 = HeapAllocator::drop(unsafe HeapAllocator::adopt_raw(unsafe (cur as *u8)));
        self = Drain!.{ alloc, back, tag, base, bucket_count, next_bucket, cur: nx };
        Option::Some.((k, v))
    }

    /// Ends the drain: `f` disposes of every entry not yet taken, and the
    /// bucket array is freed.
    fn finish(self, f: fn(K, V) -> ()) -> () {
        let { alloc, back, tag, base, bucket_count, next_bucket, cur } = self;
        let u = unsafe destroy_chain[K, V](cur, f);
        var i = next_bucket;
        while i < bucket_count {
            let head = unsafe *(unsafe offset(base, i));
            let u = unsafe destroy_chain[K, V](head, f);
            i = i + 1usize;
        }
        let rg = back.resume(tag);
        HeapAllocator::drop(alloc.release(rg))
    }
}

// As an `Iterator`, each entry is a `Pair { a: key, b: value }`, the item
// type `core::iter::zip` uses.
/// The drained entries, each moved out as `Pair { a: key, b: value }`.
forall K, V, 'k where Sized[K], Sized[V].
instance Iterator[Drain![K, V, 'k] -> Pair[K, V]] {
    fn next(&it: Drain![K, V, 'k]) -> Option[Pair[K, V]] {
        let taken = &it.take();
        match taken {
            Some(entry) => {
                let (k, v) = entry;
                Option::Some.(Pair.{ a: k, b: v })
            },
            None => Option::None,
        }
    }
}

// ------------------------------------------------------------ OwnedMap! --
/// A `HashMap!` packaged with its capability, for a map kept across calls or
/// in a loop variable without naming its brand. Each method opens the
/// package, calls the `HashMap!` method and repacks the result under
/// whatever brand it returned. `inner` is the package itself: open it for
/// the branded API and pack it back afterwards.
forall K, V.
exposed struct OwnedMap! {
    inner: exists 'm. (Exclusive!['m], HashMap![K, V, 'm]),
}

forall K, V where Sized[K], Sized[V].
impl OwnedMap![K, V] {
    /// An empty map that hashes its keys under `seed`, aborting when
    /// allocation fails.
    fn new(seed: Seed) -> OwnedMap![K, V] {
        OwnedMap!.{ inner: HashMap!::new[K, V](seed) }
    }

    /// An empty map that hashes its keys under `seed`, or the allocation
    /// failure: `HashMap!::try_new`'s map, packaged.
    fn try_new(seed: Seed) -> Result[OwnedMap![K, V], AllocError] {
        match HashMap!::try_new[K, V](seed) {
            Ok(inner) => Result::Ok.(OwnedMap!.{ inner }),
            Err(e) => Result::Err.(e),
        }
    }

    /// How many entries the map holds.
    fn len(&self) -> usize {
        var exists 'm. (tag, map) = self.inner;
        let n = &map.len();
        self = OwnedMap!.{ inner: pack 'm. (tag, map) };
        n
    }

    /// Whether the map holds no entries.
    fn is_empty(&self) -> bool {
        &self.len() == 0usize
    }

    /// Every entry, moved out, in no particular order (see `HashMap!::drain`).
    fn drain(self) -> exists 'm. Drain![K, V, 'm] {
        let exists 'm. (tag, map) = self.inner;
        pack 'm. map.drain(tag)
    }

    /// Frees the map, handing each entry to `f` first.
    fn destroy_with(self, f: fn(K, V) -> ()) -> () {
        let exists 'm. (tag, map) = self.inner;
        map.destroy_with(tag, f)
    }

    /// Calls `f` on each key and its value where they live, in no
    /// particular order, keeping the map (`HashMap!::each`).
    forall Env where Copy[Env].
    fn each(&self, f: closure[Env](&_: K, &_: V) -> ()) {
        var exists 'm. (tag, map) = self.inner;
        &map.each(&tag, f);
        self = OwnedMap!.{ inner: pack 'm. (tag, map) };
    }

    /// `each`, with a context `cx` lent to `f` beside each key and value
    /// (`HashMap!::each_in`).
    forall C, Env where Copy[Env].
    fn each_in(&self, &cx: C, f: closure[Env](&_: K, &_: V, &_: C) -> ()) {
        var exists 'm. (tag, map) = self.inner;
        &map.each_in(&tag, &cx, f);
        self = OwnedMap!.{ inner: pack 'm. (tag, map) };
    }

    /// Removes every entry, handing each to `f`, and keeps the room the map
    /// has (`HashMap!::clear_with`).
    fn clear_with(&self, f: fn(K, V) -> ()) {
        let exists 'm. (tag, map) = self.inner;
        let exists '2. (tag, map) = map.clear_with(tag, f);
        self = OwnedMap!.{ inner: pack '2. (tag, map) };
    }
}

forall K, V where Hash[K], Eq[K, K], Sized[K], Sized[V].
impl OwnedMap![K, V] {
    /// Stores `val` under `key`, handing back the key and value it
    /// replaces.
    fn insert(&self, key: K, val: V) -> Option[(K, V)] {
        let exists 'm. (tag, map) = self.inner;
        let exists '2. (tag, map, old) = map.insert(tag, key, val);
        self = OwnedMap!.{ inner: pack '2. (tag, map) };
        old
    }

    /// Removes `key`'s entry, handing back its stored key and value.
    fn remove(&self, &key: K) -> Option[(K, V)] {
        let exists 'm. (tag, map) = self.inner;
        let exists '2. (tag, map, old) = map.remove(tag, &key);
        self = OwnedMap!.{ inner: pack '2. (tag, map) };
        old
    }

    /// Whether `key` is in the map.
    fn contains(&self, &key: K) -> bool {
        var exists 'm. (tag, map) = self.inner;
        let found = &map.contains(&tag, &key);
        self = OwnedMap!.{ inner: pack 'm. (tag, map) };
        found
    }

    /// Calls `f` on `key`'s value in place: `f` takes the value and hands it
    /// back with a result. When the key is absent `f` is dropped uncalled,
    /// so what it captures must be `Copy`.
    forall Ret, Env where Copy[Env].
    fn with(&self, &key: K, f: closure[Env](V) -> (V, Ret)) -> Option[Ret] {
        var exists 'm. (tag, map) = self.inner;
        let slot = &map.get(&tag, &key);
        let (tag, result) = match slot {
            Some(r) => {
                let ret = r.with(&tag, f);
                (tag, Option::Some.(ret))
            },
            None => (tag, Option::None),
        };
        self = OwnedMap!.{ inner: pack 'm. (tag, map) };
        result
    }

    /// Calls `f` on `key`'s value where it lives: `f` gets it through `&`,
    /// and nothing is copied out or back. When the key is absent `f` is
    /// dropped uncalled, so what it captures must be `Copy`.
    forall Ret, Env where Copy[Env].
    fn update(&self, &key: K, f: closure[Env](&_: V) -> Ret) -> Option[Ret] {
        var exists 'm. (tag, map) = self.inner;
        let slot = &map.get(&tag, &key);
        let (tag, result) = match slot {
            Some(r) => {
                let ret = r.update(&tag, f);
                (tag, Option::Some.(ret))
            },
            None => (tag, Option::None),
        };
        self = OwnedMap!.{ inner: pack 'm. (tag, map) };
        result
    }

    /// Calls `f` on `key`'s value where it lives, with a context `cx` lent
    /// beside it: `update`, with the linear values `f` works on, which it
    /// cannot capture.
    forall C, Ret, Env where Copy[Env].
    fn update_in(&self, &key: K, &cx: C, f: closure[Env](&_: V, &_: C) -> Ret) -> Option[Ret] {
        var exists 'm. (tag, map) = self.inner;
        let slot = &map.get(&tag, &key);
        let (tag, result) = match slot {
            Some(r) => {
                let ret = r.update_in(&tag, &cx, f);
                (tag, Option::Some.(ret))
            },
            None => (tag, Option::None),
        };
        self = OwnedMap!.{ inner: pack 'm. (tag, map) };
        result
    }
}

forall K, V where Sized[K], Sized[V].
impl OwnedMap![K, V] {
    /// Calls `f` on the value of the key `probe` stands for, in place:
    /// `with`, looked up by a probe of another type that hashes like the
    /// keys and compares equal to the one it stands for (`HashMap!::find`),
    /// such as a `core::slice::Readable` view for a `Buffer!` key, so that
    /// no owned key is built for the lookup. The probe comes back.
    forall Q, Ret, Env where Hash[Q], Eq[K, Q], Copy[Env].
    fn find_with(&self, &probe: Q, f: closure[Env](V) -> (V, Ret)) -> Option[Ret] {
        var exists 'm. (tag, map) = self.inner;
        let slot = &map.find(&tag, &probe);
        let (tag, result) = match slot {
            Some(r) => {
                let ret = r.with(&tag, f);
                (tag, Option::Some.(ret))
            },
            None => (tag, Option::None),
        };
        self = OwnedMap!.{ inner: pack 'm. (tag, map) };
        result
    }

    /// Calls `f` on the value of the key `probe` stands for, where it
    /// lives: `update`, looked up by a probe as `find_with` is.
    forall Q, Ret, Env where Hash[Q], Eq[K, Q], Copy[Env].
    fn find_update(&self, &probe: Q, f: closure[Env](&_: V) -> Ret) -> Option[Ret] {
        var exists 'm. (tag, map) = self.inner;
        let slot = &map.find(&tag, &probe);
        let (tag, result) = match slot {
            Some(r) => {
                let ret = r.update(&tag, f);
                (tag, Option::Some.(ret))
            },
            None => (tag, Option::None),
        };
        self = OwnedMap!.{ inner: pack 'm. (tag, map) };
        result
    }
}

forall K, V where Copy[V], Sized[K], Sized[V].
impl OwnedMap![K, V] {
    /// A copy of the value of the key `probe` stands for, or `None`: `get`,
    /// looked up by a probe as `find_with` is.
    forall Q where Hash[Q], Eq[K, Q].
    fn find(&self, &probe: Q) -> Option[V] {
        var exists 'm. (tag, map) = self.inner;
        let slot = &map.find(&tag, &probe);
        let (tag, value) = match slot {
            Some(r) => {
                let value = r.copy(&tag);
                (tag, Option::Some.(value))
            },
            None => (tag, Option::None),
        };
        self = OwnedMap!.{ inner: pack 'm. (tag, map) };
        value
    }
}

forall K, V where Hash[K], Eq[K, K], Copy[V], Sized[K], Sized[V].
impl OwnedMap![K, V] {
    /// A copy of `key`'s value, or `None` when it is absent.
    fn get(&self, &key: K) -> Option[V] {
        var exists 'm. (tag, map) = self.inner;
        let slot = &map.get(&tag, &key);
        let (tag, value) = match slot {
            Some(r) => {
                let value = r.copy(&tag);
                (tag, Option::Some.(value))
            },
            None => (tag, Option::None),
        };
        self = OwnedMap!.{ inner: pack 'm. (tag, map) };
        value
    }

    /// A copy of the value of a key that must be in the map; without it, the
    /// program stops (`core::process::trap`).
    fn at(&self, &key: K) -> V {
        match &self.get(&key) {
            Some(v) => v,
            None => trap(),
        }
    }
}

forall K, V where Copy[K], Sized[K], Sized[V].
impl OwnedMap![K, V] {
    /// Stores `val` under the domain key `key`, handing back the value it
    /// replaces. This is `insert` for a `Copy` key that points into a
    /// domain, hashed and compared through that domain's capability `cx`.
    forall C where HashIn[K, C].
    fn insert_in(&self, &cx: C, key: K, val: V) -> Option[V] {
        let exists 'm. (tag, map) = self.inner;
        let exists '2. (tag, map, old) = map.insert_in(tag, &cx, key, val);
        self = OwnedMap!.{ inner: pack '2. (tag, map) };
        old
    }

    /// Removes a domain key's entry, handing back its value: `remove` for a
    /// domain key.
    forall C where HashIn[K, C].
    fn remove_in(&self, &cx: C, key: K) -> Option[V] {
        let exists 'm. (tag, map) = self.inner;
        let exists '2. (tag, map, old) = map.remove_in(tag, &cx, key);
        self = OwnedMap!.{ inner: pack '2. (tag, map) };
        old
    }

    /// Whether a domain key is in the map: `contains` for a domain key.
    forall C where HashIn[K, C].
    fn contains_in(&self, &cx: C, key: K) -> bool {
        var exists 'm. (tag, map) = self.inner;
        let found = &map.contains_in(&tag, &cx, key);
        self = OwnedMap!.{ inner: pack 'm. (tag, map) };
        found
    }

    /// Calls `f` on a domain key's value in place: `with` for a domain key.
    forall C, Ret, Env where HashIn[K, C], Copy[Env].
    fn with_in(&self, &cx: C, key: K, f: closure[Env](V) -> (V, Ret)) -> Option[Ret] {
        var exists 'm. (tag, map) = self.inner;
        let slot = &map.get_in(&tag, &cx, key);
        let (tag, result) = match slot {
            Some(r) => {
                let ret = r.with(&tag, f);
                (tag, Option::Some.(ret))
            },
            None => (tag, Option::None),
        };
        self = OwnedMap!.{ inner: pack 'm. (tag, map) };
        result
    }
}

forall K, V where Copy[K], Copy[V], Sized[K], Sized[V].
impl OwnedMap![K, V] {
    /// A copy of a domain key's value, or `None` when it is absent: `get`
    /// for a domain key.
    forall C where HashIn[K, C].
    fn get_in(&self, &cx: C, key: K) -> Option[V] {
        var exists 'm. (tag, map) = self.inner;
        let slot = &map.get_in(&tag, &cx, key);
        let (tag, value) = match slot {
            Some(r) => {
                let value = r.copy(&tag);
                (tag, Option::Some.(value))
            },
            None => (tag, Option::None),
        };
        self = OwnedMap!.{ inner: pack 'm. (tag, map) };
        value
    }

    /// Removes every entry, keeping the room the map has.
    fn clear(&self) {
        &self.clear_with(forget_entry[K, V]);
    }

    /// Frees a map of `Copy` keys and values, which need no per-entry callback.
    fn destroy(self) -> () {
        let exists 'm. (tag, map) = self.inner;
        map.destroy(tag)
    }
}