← alloc

alloc/collections/vec.kur

//! Growable owning sequences of values.
// A growable array. `Vec!` owns its heap block through two records:
//
//   alloc: Allocation![T,'k]   the right to free the block: base address
//                              and extent, recorded by `Allocation!::adopt`
//                              from the allocator, never from a caller.
//   back:  RegionResume![T,'k] the receipt `Region!::share` kept back, the
//                              only route from the caller's `Exclusive!['k]`
//                              back to a `Region!`.
//
// Every operation that may change the storage runs the same cycle:
// `back.resume(tag)` to recover the region, `alloc.release_storage(region)`
// to retire the domain into raw `Uninit!` storage, an optional
// `HeapAllocator::grow`, then `Allocation!::adopt` and `Region!::share` to
// re-enter under a fresh brand. `push` and `pop` therefore
// always return a new brand, invalidating every outstanding `Ref` or
// `Slice` into the vec whether or not the storage moved: the policy is
// "mutation invalidates", not "the address moved".
//
// The address `destroy_with` frees comes from `alloc`, never from a `Ref`, so
// no pointer this module frees is one a caller chose.
//
// Adopting the block. `Allocation!::adopt` asks for an initialized `T` in
// at least `sizeof[T]()` bytes, because its region lets safe code read and
// write the block as a `T`. The block holds `cap` slots, and `cap` starts
// at 4 and only doubles, so the size holds. `T` is `Sized`: a raw read or
// write is never at a zero-size type.
// Only the first `len` slots are initialized, and an empty vec has none. That is sound here because the
// region never leaves this module and is never read as a `T`: `share`'s
// `Ref` is taken apart into the base address at once, elements are read
// only below `len`, and the region is resumed only to be released.
//
// Releasing the block. `Allocation!::release_storage` asks that every `T`
// in the block be accounted for, because it gives the block up without
// reading it. `push` and `pop` release only to adopt the same storage again
// (grown or not) at once: the elements below `len` stay in it, and the
// function goes on to track them (`pop` moves the last one out of the
// adopted block). `destroy_with` moves every element out to its callback before
// it releases.
//
// `Vec!` is not `exposed`: a foreign module cannot build or destructure
// it. A forged `Vec!` could pair an arbitrary `buf` with an arbitrary
// `len` or `cap`, which the element operations index through; it could
// not supply an `Allocation!`, whose only producers are `Allocation!::adopt`
// and `adopt_value`.

use package as alloc;

use alloc::heap::Uninit!;
use alloc::heap::{AllocError, HeapAllocator, Storage, abort};
use alloc::heap::checked_add;
use alloc::heap::checked_mul;
use core::cap::Exclusive!;
use core::mem::{Ref, sizeof};
use core::ptr::offset;
use core::option::{Option, Result};
use alloc::owned::Allocation!;
use core::mem::Region!;
use core::mem::RegionResume!;
use core::slice::Slice;
use core::cmp::{Ord, Order};
use core::hash::Eq;
use core::iter::Iterator;
use core::process::trap;
use alloc::collections::arena_vec::merge_runs;

/// A growable array that owns its heap block, under brand `'k`.
///
/// `alloc` and `back` are restricted records held as fields: only
/// `Allocation!::adopt` produces an `Allocation!` and only `Region!::share`
/// a `RegionResume!`, so a `Vec!` holding them holds genuine ones. Since
/// `Vec!` is not `exposed`, no foreign module can write the literal and
/// pair an honest `Ref` with a stale record.
forall T, 'k.
struct Vec! {
    alloc: Allocation![T, 'k],
    back: RegionResume![T, 'k],
    buf: Ref[T, 'k],
    len: usize,
    cap: usize,
}


forall T where Sized[T].
impl Vec![T] {
    /// An empty vec with capacity 4, under
    /// a fresh brand, or the allocation failure. `Allocation!::adopt` mints
    /// and seals the brand and records the block's base and extent; `share`
    /// trades the region for the `Exclusive!`/`Ref` pair this signature
    /// promises, plus the receipt that is the only route back. Growing it
    /// later aborts as `push` does.
    fn try_new() -> Result[exists '1. (Exclusive!['1], Vec![T, '1]), AllocError] {
        let initial_cap = 4usize;
        let bytes = checked_mul(initial_cap, sizeof[T]());
        match Storage::try_alloc(bytes) {
            Err(e) => Result::Err.(e),
            Ok(u) => {
                // `adopt`'s obligation: see "Adopting the block" in the header.
                let exists 'open1. (a, rg) = unsafe Allocation!::adopt[T](u);
                let (tag, r, bk) = rg.share();
                Result::Ok.(pack 'open1. (tag, Vec!.{ alloc: a, back: bk, buf: r, len: 0usize, cap: initial_cap }))
            },
        }
    }

    /// An empty vec under a fresh brand: `try_new`, aborting on failure.
    fn new() -> exists '1. (Exclusive!['1], Vec![T, '1]) {
        match Vec!::try_new[T]() {
            Ok(v) => v,
            Err(e) => unsafe abort(),
        }
    }
}

forall T, 'k where Sized[T].
impl Vec![T, 'k] {
    /// Appends `val`, doubling the capacity when the vec is full. The only
    /// operation here where the storage can move. Always
    /// returns under a fresh brand, invalidating every descriptor of the old
    /// domain by type equality, growth or no growth.
    ///
    /// The cycle, in the order the lines below run it:
    ///
    ///   back.resume(tag)      consumes the caller's `Exclusive!['k]` and
    ///                         rebuilds the `Region![T,'k]`. `resume` demands
    ///                         the exact witness, of which there is one, so no
    ///                         other access capability of 'k is outstanding.
    ///   alloc.release_storage(region)
    ///                         retires the domain into a raw `Uninit!`
    ///                         carrying the extent `adopt` recorded, so `grow`
    ///                         resizes a block whose size is the allocator's
    ///                         own number, never one re-derived here.
    ///   HeapAllocator::grow   only when full; otherwise the same `Uninit!`
    ///                         passes straight through.
    ///   Allocation::adopt/share   re-enter under a fresh brand, sealed by
    ///                         this function's `exists '2.`.
    ///
    /// On the non-growing path `release_storage` and `adopt` are `Uninit!`
    /// bookkeeping, with no `malloc`/`free` between them.
    fn push(self, tag: Exclusive!['k], val: T) -> exists '2. (Exclusive!['2], Vec![T, '2]) {
        let { alloc: a, back: bk, buf: r, len: n, cap: c } = self;
        let rg = bk.resume(tag);
        // `release_storage`'s obligation: see "Releasing the block" in the
        // header.
        let u = unsafe a.release_storage(rg);
        let new_cap = if n < c { c } else { checked_mul(c, 2usize) };
        let u = if n < c {
            u
        } else {
            let new_bytes = checked_mul(new_cap, sizeof[T]());
            HeapAllocator::grow(u, new_bytes)
        };
        // `adopt`'s obligation: see "Adopting the block" in the header.
        let exists 'open1. (a2, rg2) = unsafe Allocation!::adopt[T](u);
        let (tag, r2, bk2) = rg2.share();
        let (p, m) = r2.into_parts();
        let target = unsafe offset(p, n);
        unsafe *target = val;
        let n2 = n + 1usize;
        pack 'open1. (tag, Vec!.{ alloc: a2, back: bk2, buf: r2, len: n2, cap: new_cap })
    }

    /// How many elements the vec holds. The length is the vec's own field,
    /// not a read of its storage, so no capability is presented.
    fn len(&self) -> usize {
        let { alloc: a, back: bk, buf: r, len: n, cap: c } = self;
        self = Vec!.{ alloc: a, back: bk, buf: r, len: n, cap: c };
        n
    }

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

    /// A `Ref` to element `i`, or `None` when `i >= len`. Checked against
    /// `len`, not `cap`: the slots between them are allocated but
    /// uninitialized, and a `Ref` into one would let `Ref::copy` read an
    /// uninitialized `T`.
    fn get_ref(&self, &tag: Exclusive!['k], i: usize) -> Option[Ref[T, 'k]] {
        let { alloc: a, back: bk, buf: r, len: n, cap: c } = self;
        let (p, m) = r.into_parts();
        let out: Option[Ref[T, 'k]] = if i < n {
            // In bounds of this vec's initialized elements, which live
            // under `m`.
            Option::Some.(unsafe Ref::from_raw(unsafe offset(p, i), m))
        } else {
            Option::None
        };
        self = Vec!.{ alloc: a, back: bk, buf: r, len: n, cap: c };
        out
    }

    /// A checked view of every element, sharing the vec's live brand. `tag`
    /// is presented, never consumed: it proves the caller holds the current
    /// brand. A later `push`/`pop` returns a different brand, so the checker
    /// rejects any use of this `Slice`, or a `Ref` from it, against the vec's
    /// later state.
    fn as_slice(&self, &tag: Exclusive!['k]) -> Slice[T, 'k] {
        let { alloc: a, back: bk, buf: r, len: n, cap: c } = self;
        let (p, m) = r.into_parts();
        // `unsafe`: `n` is this vec's maintained length invariant, not a
        // caller-supplied value, which is exactly the obligation
        // `Slice::from_raw_parts` asks for.
        let view = unsafe Slice::from_raw_parts(p, n, m);
        self = Vec!.{ alloc: a, back: bk, buf: r, len: n, cap: c };
        view
    }

    /// Removes and returns the last element, or `None` if the vec is empty.
    /// Rebrands like `push`, but never resizes the allocation.
    fn pop(self, tag: Exclusive!['k]) -> exists '2. (Exclusive!['2], Vec![T, '2], Option[T]) {
        let { alloc: a, back: bk, buf: r, len: n, cap: c } = self;
        let rg = bk.resume(tag);
        // `release_storage`'s obligation: see "Releasing the block" in the
        // header.
        let u = unsafe a.release_storage(rg);
        // `adopt`'s obligation: see "Adopting the block" in the header.
        let exists 'open1. (a2, rg2) = unsafe Allocation!::adopt[T](u);
        let (tag, r2, bk2) = rg2.share();
        let (p, m) = r2.into_parts();
        let zero = 0usize;
        let is_empty = n == zero;
        let result: (usize, Option[T]) = if is_empty {
            (n, Option::None)
        } else {
            let one = 1usize;
            let n2 = n - one;
            let ep = unsafe offset(p, n2);
            let v = unsafe *ep;
            (n2, Option::Some.(v))
        };
        let (new_len, popped) = result;
        pack 'open1. (tag, Vec!.{ alloc: a2, back: bk2, buf: r2, len: new_len, cap: c }, popped)
    }

    /// Puts `val` at index `i`, moving the elements from `i` on one place
    /// up: `push` when `i` is the length. Stops the program
    /// (`core::process::trap`) when `i` is past the length. Rebrands as
    /// `push` does.
    fn insert(self, tag: Exclusive!['k], i: usize, val: T) -> exists '2. (Exclusive!['2], Vec![T, '2]) {
        var vec = self;
        if i > &vec.len() {
            trap();
        }
        let exists '2. (tag, v) = vec.push(tag, val);
        let { alloc: a, back: bk, buf: r, len: n, cap: c } = v;
        let (p, m) = r.into_parts();
        // Indices below `n` are this vector's initialized elements.
        var j = n - 1usize;
        while j > i {
            unsafe swap_at[T](p, j - 1usize, j);
            j = j - 1usize;
        }
        pack '2. (tag, Vec!.{ alloc: a, back: bk, buf: r, len: n, cap: c })
    }

    /// Takes the element at index `i` out, moving the ones after it one
    /// place down, or `None` when `i` is out of range. Rebrands as `pop`
    /// does.
    fn remove(self, tag: Exclusive!['k], i: usize) -> exists '2. (Exclusive!['2], Vec![T, '2], Option[T]) {
        let { alloc: a, back: bk, buf: r, len: n, cap: c } = self;
        let (p, m) = r.into_parts();
        // Indices below `n` are this vector's initialized elements.
        var j = i;
        while j + 1usize < n {
            unsafe swap_at[T](p, j, j + 1usize);
            j = j + 1usize;
        }
        let v = Vec!.{ alloc: a, back: bk, buf: r, len: n, cap: c };
        if i < n {
            v.pop(tag)
        } else {
            pack 'k. (tag, v, Option::None)
        }
    }

    /// Exchanges the elements at `i` and `j`; stops the program
    /// (`core::process::trap`) when either is out of range. Moves only, so
    /// any `T`, and no rebranding: a `Ref` to an index names what is there
    /// now.
    fn swap(&self, &tag: Exclusive!['k], i: usize, j: usize) {
        let { alloc: a, back: bk, buf: r, len: n, cap: c } = self;
        let (p, m) = r.into_parts();
        if i >= n || j >= n {
            trap();
        }
        // Both indices are below `n`, inside this vector's elements.
        unsafe swap_at[T](p, i, j);
        self = Vec!.{ alloc: a, back: bk, buf: r, len: n, cap: c };
    }

    /// Reverses the order of the elements, by moves, as `swap` does.
    fn reverse(&self, &tag: Exclusive!['k]) {
        let { alloc: a, back: bk, buf: r, len: n, cap: c } = self;
        let (p, m) = r.into_parts();
        var i = 0usize;
        var j = n;
        // `i < j - 1` keeps both indices below `n`, inside the elements.
        while i + 1usize < j {
            j = j - 1usize;
            unsafe swap_at[T](p, i, j);
            i = i + 1usize;
        }
        self = Vec!.{ alloc: a, back: bk, buf: r, len: n, cap: c };
    }

    /// Consumes the vec: calls `f` once per element (so a linear `T` can be
    /// consumed), then frees the buffer. `f` is a plain function pointer,
    /// not a capturing closure: it is called an unbounded number of times,
    /// and only a captureless `fn` is provably Copy generically. The address
    /// freed comes from `alloc`, recorded by `Allocation!::adopt`, not from
    /// `buf`.
    fn destroy_with(self, tag: Exclusive!['k], f: fn(T) -> ()) -> () {
        let { alloc: a, back: bk, buf: r, len: n, cap: c } = self;
        let (p, m) = r.into_parts();
        var i = 0usize;
        while i < n {
            let ep = unsafe offset(p, i);
            let v = unsafe *ep;
            let u = f(v);
            i = i + 1usize;
        }
        let rg = bk.resume(tag);
        // `release_storage`'s obligation: every element was moved out to `f`
        // above.
        let u2 = unsafe a.release_storage(rg);
        let u3 = HeapAllocator::drop(u2);
        u3
    }
}

// ---------------------------------------------------------------------
// Sorting. `sort_by` and `sort` are stable: a bottom-up merge sort through
// a scratch block (O(n log n) comparisons, O(n) extra space), for `Copy`
// elements, as `ArenaVec::sort_by`. `sort_unstable_by` and
// `sort_unstable` are a heapsort in place: O(n log n) comparisons and only
// moves, so linear elements sort as well as `Copy` ones, but equal
// elements may change order.

/// Whether the element at `i` orders before the one at `j`; both stay put.
/// Caller: both indices are below the number of initialized elements at
/// `p`, which nothing else touches during the call.
forall T, Env where Copy[Env], Sized[T].
unsafe fn before(p: *T, i: usize, j: usize, cmp: closure[Env](T, T) -> (T, T, Order)) -> bool {
    let a = unsafe *(unsafe offset(p, i));
    let b = unsafe *(unsafe offset(p, j));
    let (a, b, order) = cmp(a, b);
    unsafe *(unsafe offset(p, i)) = a;
    unsafe *(unsafe offset(p, j)) = b;
    match order {
        Less => true,
        _ => false,
    }
}

/// Exchanges the elements at `i` and `j` of the block at `p`, by moves.
/// Caller: both indices are below the number of initialized elements at
/// `p`, which nothing else touches during the call. Used by the `Vec!`
/// operations that move elements; not meant for direct use.
forall T where Sized[T].
unsafe fn swap_at(p: *T, i: usize, j: usize) -> () {
    let a = unsafe *(unsafe offset(p, i));
    let b = unsafe *(unsafe offset(p, j));
    unsafe *(unsafe offset(p, i)) = b;
    unsafe *(unsafe offset(p, j)) = a;
    ()
}

/// Restores the max-heap below `root` within the first `end` elements.
/// Caller: `end` is at most the number of initialized elements at `p`,
/// which nothing else touches during the call.
forall T, Env where Copy[Env], Sized[T].
unsafe fn sift_down(p: *T, root: usize, end: usize, cmp: closure[Env](T, T) -> (T, T, Order)) -> () {
    var at = root;
    var going = true;
    while going {
        let child = at * 2usize + 1usize;
        if child >= end {
            going = false;
        } else {
            let right = child + 1usize;
            let right_first = if right < end {
                unsafe before(p, child, right, cmp)
            } else {
                false
            };
            let pick = if right_first { right } else { child };
            let below = unsafe before(p, at, pick, cmp);
            if below {
                let u = unsafe swap_at[T](p, at, pick);
                at = pick;
            } else {
                going = false;
            }
        }
    }
}

forall T, 'k where Sized[T].
impl Vec![T, 'k] {
    /// Sorts the elements so `cmp` never says a later one orders before an
    /// earlier one. Not stable; any `T`.
    forall Env where Copy[Env].
    fn sort_unstable_by(&self, &tag: Exclusive!['k], cmp: closure[Env](T, T) -> (T, T, Order)) {
        let { alloc: a, back: bk, buf: r, len: n, cap: c } = self;
        let (p, m) = r.into_parts();
        // Indices below `n` are inside the elements this vector owns.
        var i = n / 2usize;
        while i > 0usize {
            i = i - 1usize;
            let u = unsafe sift_down(p, i, n, cmp);
        }
        var end = n;
        while end > 1usize {
            end = end - 1usize;
            let u1 = unsafe swap_at[T](p, 0usize, end);
            let u2 = unsafe sift_down(p, 0usize, end, cmp);
        }
        self = Vec!.{ alloc: a, back: bk, buf: r, len: n, cap: c };
    }
}

forall T, 'k where Ord[T, T], Sized[T].
impl Vec![T, 'k] {
    /// Sorts the elements in ascending `Ord` order. Not stable; any `T`.
    fn sort_unstable(&self, &tag: Exclusive!['k]) {
        &self.sort_unstable_by(&tag, |a: T, b: T| Ord[T, T]::cmp(a, b))
    }
}

forall T, 'k where Copy[T], Sized[T].
impl Vec![T, 'k] {
    /// Sorts, stably, by `cmp`, which is lent the context `cx` for each
    /// comparison, so the order may read a domain the elements point into.
    forall C, Env where Copy[Env].
    fn sort_by(&self, &tag: Exclusive!['k], &cx: C, cmp: closure[Env](&_: C, T, T) -> Order) {
        let { alloc: a, back: bk, buf: r, len: n, cap: c } = self;
        let (p, m) = r.into_parts();
        let size = sizeof[T]();
        if n < 2usize {
            self = Vec!.{ alloc: a, back: bk, buf: r, len: n, cap: c };
            return;
        }
        let (raw, extent) = HeapAllocator::alloc(checked_mul(n, size)).into_parts();
        let scratch = unsafe (raw as *T);
        // Indices below `n` are inside this vector's elements and inside
        // the scratch block, and the two do not overlap.
        var src = p;
        var dst = scratch;
        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;
        }
        // An odd number of passes left the sorted elements in the scratch.
        if unsafe (src as usize) != unsafe (p as usize) {
            var i = 0usize;
            while i < n {
                unsafe *(unsafe offset(p, i)) = unsafe *(unsafe offset(scratch, i));
                i = i + 1usize;
            }
        }
        let u = HeapAllocator::drop(unsafe HeapAllocator::adopt_raw_sized(raw, extent));
        self = Vec!.{ alloc: a, back: bk, buf: r, len: n, cap: c };
    }
}

forall T, 'k where Copy[T], Ord[T, T], Sized[T].
impl Vec![T, 'k] {
    /// Sorts the elements in ascending `Ord` order, stably.
    fn sort(&self, &tag: Exclusive!['k]) {
        var none = ();
        &self.sort_by(&tag, &none, |&none, a: T, b: T| {
            let (x, y, order) = Ord[T, T]::cmp(a, b);
            order
        })
    }
}

/// Lets a `Copy` element go: the callback `destroy` passes to
/// `destroy_with`. Not meant for direct use.
forall T where Copy[T].
fn forget_copy(value: T) -> () {
    ()
}

forall T, 'k where Copy[T], Sized[T].
impl Vec![T, 'k] {
    /// A copy of element `i`, or `None` when it is out of range.
    fn get(&self, &tag: Exclusive!['k], i: usize) -> Option[T] {
        match &self.get_ref(&tag, i) {
            Some(r) => Option::Some.(r.copy(&tag)),
            None => Option::None,
        }
    }

    /// A copy of element `i`; stops the program (`core::process::trap`)
    /// when it is out of range. `get` is the form for an index that may miss.
    fn at(&self, &tag: Exclusive!['k], i: usize) -> T {
        match &self.get(&tag, i) {
            Some(v) => v,
            None => trap(),
        }
    }
}

forall T, 'k where Copy[T], Sized[T].
impl Vec![T, 'k] {
    /// Frees a vector of `Copy` elements, which need no per-element callback.
    fn destroy(self, tag: Exclusive!['k]) -> () {
        self.destroy_with(tag, forget_copy[T])
    }
}

// ------------------------------------------------------------ OwnedVec! --
/// A `Vec!` packaged with its capability, for a vector kept across calls or
/// in a loop variable without naming its brand. Each method opens the
/// package, calls the `Vec!` method and repacks the result under whatever
/// brand it returned, so a growing vector needs no `let exists`/`pack` at
/// the call site. `inner` is the package itself: open it for the branded
/// API, such as `get_ref` or `as_slice`, and pack it back afterwards.
forall T.
exposed struct OwnedVec! {
    inner: exists 'k. (Exclusive!['k], Vec![T, 'k]),
}

forall T where Sized[T].
impl OwnedVec![T] {
    /// An empty vector, aborting when allocation fails.
    fn new() -> OwnedVec![T] {
        OwnedVec!.{ inner: Vec!::new[T]() }
    }

    /// An empty vector, or the allocation failure: `Vec!::try_new`'s vec,
    /// packaged.
    fn try_new() -> Result[OwnedVec![T], AllocError] {
        match Vec!::try_new[T]() {
            Ok(inner) => Result::Ok.(OwnedVec!.{ inner }),
            Err(e) => Result::Err.(e),
        }
    }

    /// How many elements the vector holds.
    fn len(&self) -> usize {
        var exists 'k. (tag, v) = self.inner;
        let n = &v.len();
        self = OwnedVec!.{ inner: pack 'k. (tag, v) };
        n
    }

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

    /// Adds `val` at the end.
    fn push(&self, val: T) {
        let exists 'k. (tag, v) = self.inner;
        let exists '2. (tag, v) = v.push(tag, val);
        self = OwnedVec!.{ inner: pack '2. (tag, v) };
    }

    /// Removes the last element and hands it back, or `None` when there is
    /// none.
    fn pop(&self) -> Option[T] {
        let exists 'k. (tag, v) = self.inner;
        let exists '2. (tag, v, popped) = v.pop(tag);
        self = OwnedVec!.{ inner: pack '2. (tag, v) };
        popped
    }

    /// Puts `val` at index `i`, moving the elements from `i` on one place
    /// up; stops the program when `i` is past the length
    /// (`Vec!::insert`).
    fn insert(&self, i: usize, val: T) {
        let exists 'k. (tag, v) = self.inner;
        let exists '2. (tag, v) = v.insert(tag, i, val);
        self = OwnedVec!.{ inner: pack '2. (tag, v) };
    }

    /// Takes the element at index `i` out, moving the ones after it one
    /// place down, or `None` when `i` is out of range (`Vec!::remove`).
    fn remove(&self, i: usize) -> Option[T] {
        let exists 'k. (tag, v) = self.inner;
        let exists '2. (tag, v, removed) = v.remove(tag, i);
        self = OwnedVec!.{ inner: pack '2. (tag, v) };
        removed
    }

    /// Exchanges the elements at `i` and `j`; stops the program when either
    /// is out of range (`Vec!::swap`).
    fn swap(&self, i: usize, j: usize) {
        var exists 'k. (tag, v) = self.inner;
        &v.swap(&tag, i, j);
        self = OwnedVec!.{ inner: pack 'k. (tag, v) };
    }

    /// Reverses the order of the elements (`Vec!::reverse`).
    fn reverse(&self) {
        var exists 'k. (tag, v) = self.inner;
        &v.reverse(&tag);
        self = OwnedVec!.{ inner: pack 'k. (tag, v) };
    }

    /// Calls `f` on element `i` in place: `f` takes the element and hands it
    /// back with a result. `None` when `i` is out of range, in which case `f`
    /// is dropped uncalled, so what it captures must be `Copy`.
    forall Ret, Env where Copy[Env].
    fn with(&self, i: usize, f: closure[Env](T) -> (T, Ret)) -> Option[Ret] {
        var exists 'k. (tag, v) = self.inner;
        let slot = &v.get_ref(&tag, i);
        let (tag, result) = match slot {
            Some(r) => {
                let ret = r.with(&tag, f);
                (tag, Option::Some.(ret))
            },
            None => (tag, Option::None),
        };
        self = OwnedVec!.{ inner: pack 'k. (tag, v) };
        result
    }

    /// Calls `f` on element `i` where it lives: `f` gets it through `&`,
    /// and nothing is copied out or back. `None` when `i` is out of range, in
    /// which case `f` is dropped uncalled, so what it captures must be `Copy`.
    forall Ret, Env where Copy[Env].
    fn update(&self, i: usize, f: closure[Env](&_: T) -> Ret) -> Option[Ret] {
        var exists 'k. (tag, v) = self.inner;
        let slot = &v.get_ref(&tag, i);
        let (tag, result) = match slot {
            Some(r) => {
                let ret = r.update(&tag, f);
                (tag, Option::Some.(ret))
            },
            None => (tag, Option::None),
        };
        self = OwnedVec!.{ inner: pack 'k. (tag, v) };
        result
    }

    /// Calls `f` on element `i` where it lives, with a context `cx` lent
    /// beside it: `update`, with the linear values `f` works on, which it
    /// cannot capture. Bundle several into one struct.
    forall C, Ret, Env where Copy[Env].
    fn update_in(&self, i: usize, &cx: C, f: closure[Env](&_: T, &_: C) -> Ret) -> Option[Ret] {
        var exists 'k. (tag, v) = self.inner;
        let slot = &v.get_ref(&tag, i);
        let (tag, result) = match slot {
            Some(r) => {
                let ret = r.update_in(&tag, &cx, f);
                (tag, Option::Some.(ret))
            },
            None => (tag, Option::None),
        };
        self = OwnedVec!.{ inner: pack 'k. (tag, v) };
        result
    }

    /// Sorts the elements so `cmp` never says a later one orders before an
    /// earlier one. Not stable; any `T`.
    forall Env where Copy[Env].
    fn sort_unstable_by(&self, cmp: closure[Env](T, T) -> (T, T, Order)) {
        var exists 'k. (tag, v) = self.inner;
        &v.sort_unstable_by(&tag, cmp);
        self = OwnedVec!.{ inner: pack 'k. (tag, v) };
    }

    /// Frees the vector, handing each element to `f` first.
    fn destroy_with(self, f: fn(T) -> ()) -> () {
        let exists 'k. (tag, v) = self.inner;
        v.destroy_with(tag, f)
    }
}

forall T where Ord[T, T], Sized[T].
impl OwnedVec![T] {
    /// Sorts the elements in ascending `Ord` order. Not stable; any `T`.
    fn sort_unstable(&self) {
        var exists 'k. (tag, v) = self.inner;
        &v.sort_unstable(&tag);
        self = OwnedVec!.{ inner: pack 'k. (tag, v) };
    }
}

forall T where Copy[T], Ord[T, T], Sized[T].
impl OwnedVec![T] {
    /// Sorts the elements in ascending `Ord` order, stably.
    fn sort(&self) {
        var exists 'k. (tag, v) = self.inner;
        &v.sort(&tag);
        self = OwnedVec!.{ inner: pack 'k. (tag, v) };
    }
}

forall T where Copy[T], Sized[T].
impl OwnedVec![T] {
    /// A copy of element `i`, or `None` when it is out of range.
    fn get(&self, i: usize) -> Option[T] {
        var exists 'k. (tag, v) = self.inner;
        let slot = &v.get_ref(&tag, i);
        let (tag, value) = match slot {
            Some(r) => {
                let value = r.copy(&tag);
                (tag, Option::Some.(value))
            },
            None => (tag, Option::None),
        };
        self = OwnedVec!.{ inner: pack 'k. (tag, v) };
        value
    }

    /// A copy of element `i`; stops the program (`core::process::trap`)
    /// when it is out of range. `get` is the form for an index that may miss.
    fn at(&self, i: usize) -> T {
        match &self.get(i) {
            Some(v) => v,
            None => trap(),
        }
    }

    /// A copy of the first element, or `None` when there is none.
    fn first(&self) -> Option[T] {
        &self.get(0usize)
    }

    /// A copy of the last element, or `None` when there is none.
    fn last(&self) -> Option[T] {
        let n = &self.len();
        if n == 0usize { Option::None } else { &self.get(n - 1usize) }
    }

    /// Puts `value` at `i`, dropping the element there; stops the program
    /// when `i` is out of range.
    fn set(&self, i: usize, value: T) {
        var exists 'k. (tag, v) = self.inner;
        let slot = &v.get_ref(&tag, i);
        let tag = match slot {
            Some(r) => {
                r.set(&tag, value);
                tag
            },
            None => trap(),
        };
        self = OwnedVec!.{ inner: pack 'k. (tag, v) };
    }

    /// Keeps the first `len` elements, dropping the rest; nothing changes
    /// when there are no more than `len`.
    fn truncate(&self, len: usize) {
        while &self.len() > len {
            let unit = match &self.pop() {
                Some(v) => (),
                None => (),
            };
        }
    }

    /// Drops every element, keeping the room.
    fn clear(&self) {
        &self.truncate(0usize);
    }

    /// Frees a vector of `Copy` elements, which need no per-element callback.
    fn destroy(self) -> () {
        let exists 'k. (tag, v) = self.inner;
        v.destroy(tag)
    }
}

forall T where Copy[T], Eq[T, T], Sized[T].
impl OwnedVec![T] {
    /// Whether some element equals `value` (`Eq`).
    fn contains(&self, value: T) -> bool {
        var i = 0usize;
        var found = false;
        while !found && i < &self.len() {
            let (a, b, same) = Eq[T, T]::eq(&self.at(i), value);
            found = same;
            i = i + 1usize;
        }
        found
    }
}

forall T where Copy[T], Sized[T].
impl OwnedVec![T] {
    /// Sorts, stably, by `cmp`, which is lent the context `cx` for each
    /// comparison (`Vec!::sort_by`).
    forall C, Env where Copy[Env].
    fn sort_by(&self, &cx: C, cmp: closure[Env](&_: C, T, T) -> Order) {
        var exists 'k. (tag, v) = self.inner;
        &v.sort_by(&tag, &cx, cmp);
        self = OwnedVec!.{ inner: pack 'k. (tag, v) };
    }
}

// ------------------------------------------------------------ iteration --
/// A vector's elements in order, read under its capability, which the
/// iterator holds with the vector while it runs; `finish` hands both back.
forall T, 'k.
exposed struct VecIter! {
    vec: Vec![T, 'k],
    tag: Exclusive!['k],
    index: usize,
}

forall T, 'k where Copy[T], Sized[T].
impl Vec![T, 'k] {
    /// An iterator over the elements, holding the vec and its capability
    /// until `VecIter!::finish` hands them back.
    fn iter(self, tag: Exclusive!['k]) -> VecIter![T, 'k] {
        VecIter!.{ vec: self, tag, index: 0usize }
    }
}

forall T, 'k where Copy[T], Sized[T].
impl VecIter![T, 'k] {
    /// Ends the iteration, handing back the capability and the vec.
    fn finish(self) -> (Exclusive!['k], Vec![T, 'k]) {
        let { vec, tag, index: _index } = self;
        (tag, vec)
    }
}

/// The vec's elements in order, copied out under its capability.
forall T, 'k where Copy[T], Sized[T].
instance Iterator[VecIter![T, 'k] -> T] {
    fn next(&it: VecIter![T, 'k]) -> Option[T] {
        var { vec, tag, index } = it;
        let slot = &vec.get_ref(&tag, index);
        let (tag, item) = match slot {
            Some(r) => {
                let value = r.copy(&tag);
                (tag, Option::Some.(value))
            },
            None => (tag, Option::None),
        };
        let next_index = match item {
            Some(_v) => index + 1usize,
            None => index,
        };
        it = VecIter!.{ vec, tag, index: next_index };
        item
    }
}

/// An `OwnedVec!`'s elements in order; `finish` hands the vector back.
forall T.
exposed struct OwnedVecIter! {
    vec: OwnedVec![T],
    index: usize,
}

forall T where Copy[T], Sized[T].
impl OwnedVec![T] {
    /// An iterator over the elements, holding the vector until
    /// `OwnedVecIter!::finish` hands it back.
    fn iter(self) -> OwnedVecIter![T] {
        OwnedVecIter!.{ vec: self, index: 0usize }
    }
}

forall T where Copy[T], Sized[T].
impl OwnedVecIter![T] {
    /// Ends the iteration, handing back the vector.
    fn finish(self) -> OwnedVec![T] {
        let { vec, index: _index } = self;
        vec
    }
}

/// The vector's elements in order, copied out.
forall T where Copy[T], Sized[T].
instance Iterator[OwnedVecIter![T] -> T] {
    fn next(&it: OwnedVecIter![T]) -> Option[T] {
        var { vec, index } = it;
        let item = &vec.get(index);
        let next_index = match item {
            Some(_v) => index + 1usize,
            None => index,
        };
        it = OwnedVecIter!.{ vec, index: next_index };
        item
    }
}

// Every iterator's remaining items, in order, in a new vector.
forall I, T where Iterator[I -> T], Sized[T].
impl I {
    /// The iterator's remaining items, in order, in a new vector.
    fn collect_vec(self) -> (I, OwnedVec![T]) {
        var it = self;
        var out = OwnedVec!::new[T]();
        for x in &it {
            &out.push(x);
        }
        (it, out)
    }
}