← core

core/slice.kur

//! Checked contiguous views over borrowed storage.
// core::slice -- a checked view of a contiguous run of `T`.
//
// `Slice[T,'k]` is a Copy, restricted view of `len` elements. Its length
// must be honest, and every element access presents the domain's
// capability, lent by a context (`core::cap::Access`): `get_ref` hands back
// an `Option[Ref[T,'k]]` of the same brand, through which `Ref::with`
// reads or writes; `get` and `at` copy a `Copy` element out. Byte views
// are also read through `ReadBytes`, below, whose readers need not hold
// the `Exclusive!`.
//
// The brand and the bounds are two independent checks: the brand proves
// the allocation this view names is still live, and says nothing about
// whether an index is inside it. `get_ref`, `get` and `sub` check both,
// and return `Option` for an out-of-range request; `at` stops the program,
// and `byte_or_zero` below returns a `0u8` sentinel instead.
//
// There is deliberately no unbranded `get`/`set`: a view such
// as a `Vec!::as_slice` result would silently go stale after the next
// `push`, with nothing catching it. Scoping a raw view to a closure does
// not help either, since a Copy value can simply be returned out of the
// closure. Only a brand comparison against a live `Exclusive!` catches
// "used after the owner moved on", so `Slice` carries a brand, like `Ref`.
//
// A fresh, single-owner byte buffer is viewed through
// `alloc::buffer::Buffer!::open`, which mints a brand and hands back a
// `Slice[u8,'k]` plus a `BufferRestore!['k]` receipt as the only way back
// to the buffer. Reconstruction cannot go through the `Slice` itself
// because `sub` can offset its pointer (the same reason
// `core::mem::RegionResume!` exists).

use package as core;

use core::cap::{Access, Brand, Exclusive!};
use core::mem::{Ref, sizeof};
use core::ptr::offset;
use core::cap::Shared!;
use core::hash::{Hash, Eq, HashState};
use core::option::Option;
use core::cmp::Order;
use core::iter::Iterator;
use core::process::trap;

/// A checked view of `len` contiguous `T`s in domain `'k`.
///
/// As with `core::mem::Ref`, `Slice` stores `*T`, never `T` inline, so it
/// is Copy whatever `T` is.
///
/// Restricted because of `len`: a `Ref` has no field besides its pointer
/// to lie about, and fabricating a different pointer needs an `unsafe`
/// cast, but `Slice`'s `len` is independent of the pointer's honesty. If the literal were open, safe
/// code holding a live `Ref[u8,'k]` and its `Exclusive!['k]` could copy the
/// honest pointer and brand into a `Slice` with an enormous `len`, then
/// read and write far past the allocation through the safe `get_ref`/`sub`,
/// which trust `len` unconditionally. No module but this one can write the
/// struct literal or destructure a `Slice`; `from_raw_parts` is the sole,
/// `unsafe` way in, so every construction site names its obligation.
forall T, 'k.
struct Slice {
    ptr: *T,
    len: usize,
    marker: Brand['k],
}

forall T, 'k.
impl Slice[T, 'k] {
    /// A view of the `len` elements at `ptr`, in the domain `marker` names.
    ///
    /// The only way to build a `Slice` from outside this module. Caller:
    /// `ptr[0 .. len)` is live and readable and writable under `marker`'s
    /// brand, and `ptr` is not null, even when `len` is 0 or `T` is
    /// zero-size and nothing is read through it.
    /// `get_ref`/`sub` are safe methods that trust exactly this (a `Ref`
    /// from `get_ref` is never null), so an honest `ptr` and `len` here are
    /// the whole of `Slice`'s soundness boundary. Typical callers already hold a `Ref`
    /// of the same brand and assert that more elements are live starting
    /// there (`Vec!::as_slice`, `Buffer!::open`). String literals are not
    /// slices: they are read-only text, `core::str::Str['static]`.
    unsafe fn from_raw_parts(ptr: *T, len: usize, marker: Brand['k]) -> Slice[T, 'k] {
        Slice.{ ptr, len, marker }
    }

    /// The pointer, length and brand of this slice.
    ///
    /// The safe inverse of `from_raw_parts`: the `(ptr, len, marker)` the
    /// slice was built from, for code that must read through it directly
    /// or see it as another view (`Slice::as_str`). Safe because it grants no authority:
    /// rebuilding a `Slice` from the result still goes through the `unsafe`
    /// `from_raw_parts`, and the raw pointer can only be dereferenced
    /// under `unsafe`.
    fn into_parts(self) -> (*T, usize, Brand['k]) {
        let { ptr: p, len: n, marker: m } = self;
        (p, n, m)
    }

    /// A `Ref` of the same brand to element `i`, or `None` when `i` is out
    /// of range. Reads and writes then go through the `Ref`, under the
    /// capability its brand asks for: `Ref::with` and `copy` under the
    /// `Exclusive!` a context lends, `Ref::read` under a `Shared!` node.
    /// Mirrors `Vec!::get_ref`. Pure address projection with the same brand,
    /// like `sub`, so it needs no capability. The bounds check is what makes
    /// this sound: the brand only proves the allocation is live, not that
    /// `i` is inside it.
    ///
    /// `Option`, not an abort and not a sentinel: this is a fallible lookup,
    /// the same shape as `core::raw::raw_get` (`Option[T]`) and the map
    /// lookups (`HashMap!::get`, `Option[Ref[V,'k]]`).
    fn get_ref(self, i: usize) -> Option[Ref[T, 'k]] {
        let { ptr: p, len: n, marker: m } = self;
        if i < n {
            let ep = unsafe offset(p, i);
            // In bounds of this slice, whose extent is live under `m`.
            Option::Some.(unsafe Ref::from_raw(ep, m))
        } else {
            Option::None
        }
    }

    /// A copy of element `i`, read through the capability `cx` lends, or
    /// `None` when `i` is out of range.
    forall C, R where Copy[T], Access[C -> 'k, R], Sized[T].
    fn get(self, &cx: C, i: usize) -> Option[T] {
        match self.get_ref(i) {
            Some(r) => Option::Some.(r.copy(&cx)),
            None => Option::None,
        }
    }

    /// A copy of element `i`; stops the program (`core::process::trap`)
    /// when `i` is out of range. `get` is the form for an index that may
    /// miss.
    forall C, R where Copy[T], Access[C -> 'k, R], Sized[T].
    fn at(self, &cx: C, i: usize) -> T {
        match self.get_ref(i) {
            Some(r) => r.copy(&cx),
            None => trap(),
        }
    }

    /// The number of elements.
    fn len(self) -> usize {
        let { ptr: p, len: n, marker: m } = self;
        n
    }

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

    /// A sub-view starting `start` elements in, `count` elements long, or
    /// `None` if that range does not fit. Pure address projection with the
    /// same brand, so no capability is needed. There is no way back from a
    /// sub-view to a destroyable buffer: `alloc::buffer::BufferRestore!`
    /// exists so a sub-sliced `Slice` can never be used to reconstruct one.
    fn sub(self, start: usize, count: usize) -> Option[Slice[T, 'k]] {
        let { ptr: p, len: n, marker: m } = self;
        // The range check uses subtraction, as `alloc::arena::has_room`
        // does: the obvious `start + count <= n` wraps for a `count` near
        // `usize::MAX` and would then admit an arbitrarily long view.
        let out: Option[Slice[T, 'k]] = if start > n {
            Option::None
        } else {
            let remaining = n - start;
            if count > remaining {
                Option::None
            } else {
                let base = unsafe offset(p, start);
                Option::Some.(Slice.{ ptr: base, len: count, marker: m })
            }
        };
        out
    }

    /// The first `count` elements, or the whole slice if it is shorter.
    fn take(self, count: usize) -> Slice[T, 'k] {
        let { ptr: p, len: n, marker: m } = self;
        Slice.{ ptr: p, len: if count < n { count } else { n }, marker: m }
    }

    /// Everything after the first `count` elements, or an empty slice at the
    /// end.
    fn skip(self, count: usize) -> Slice[T, 'k] {
        let { ptr: p, len: n, marker: m } = self;
        let c = if count < n { count } else { n };
        Slice.{ ptr: unsafe offset(p, c), len: n - c, marker: m }
    }

    /// Elements `start` to `end`, each clamped to the slice (an empty slice
    /// when `start` is past `end`).
    fn slice(self, start: usize, end: usize) -> Slice[T, 'k] {
        let end = if end > self.len() { self.len() } else { end };
        let start = if start > end { end } else { start };
        self.skip(start).take(end - start)
    }
}

// ---------------------------------------------------------------------
// Read capabilities.
//
// A byte view (a `Slice[u8,'r]`, or text, a `core::str::Str['r]`) only
// describes bytes; reading them needs a capability for `'r`.
// `ReadBytes[C, S]` is the one protocol every safe byte reader goes
// through, with an instance per capability that can authorize the read:
// `Exclusive!['r]` (exclusive), `Shared!['r,'q]` (a shared-read node), and,
// for text only, `core::str::StaticRead` (permanent read access to
// `'static`). The brand relationship lives in the instance heads; the trait
// itself needs no brand parameter.
//
// Generic code carries `where ReadBytes[C, S], Copy[S]` with bare
// parameters (a premise may not nest a caller's parameter inside another
// type) and must read through the trait, never through the slice's raw
// pointer: a user-written instance can then only return wrong bytes, not
// read memory it has no authority over.

/// Reading the bytes of a view `S` through the capability `C`.
forall C, S.
trait ReadBytes {
    /// Byte `index` of `bytes`, or `None` when `index` is out of range;
    /// zero is an ordinary byte.
    fn get(&cx: C, bytes: S, index: usize) -> Option[u8];
    /// The number of bytes in `bytes`.
    ///
    /// Needs `cx` only so a call can select the instance: generic code
    /// holding just `S` has no other way to name the view's length.
    fn len(&cx: C, bytes: S) -> usize;
}

/// Byte `index` of `s`, or `None` past its end, read with no capability.
///
/// The shared body of the two instances below. Caller: holds a capability
/// of `s`'s brand for the call, since this reads its bytes with none of its
/// own.
forall 'k.
unsafe fn slice_byte_at(s: Slice[u8, 'k], index: usize) -> Option[u8] {
    let { ptr: p, len: n, marker: m } = s;
    if index < n {
        let b = unsafe *(unsafe offset(p, index));
        Option::Some.(b)
    } else {
        Option::None
    }
}

/// A byte slice is read through its domain's `Exclusive!`.
forall 'r.
instance ReadBytes[Exclusive!['r], Slice[u8, 'r]] {
    fn get(&cx: Exclusive!['r], bytes: Slice[u8, 'r], index: usize) -> Option[u8] {
        unsafe slice_byte_at(bytes, index)
    }
    fn len(&cx: Exclusive!['r], bytes: Slice[u8, 'r]) -> usize {
        bytes.len()
    }
}

/// A byte slice is read through any node of its domain's shared-read tree.
forall 'r, 'q.
instance ReadBytes[Shared!['r, 'q], Slice[u8, 'r]] {
    fn get(&cx: Shared!['r, 'q], bytes: Slice[u8, 'r], index: usize) -> Option[u8] {
        unsafe slice_byte_at(bytes, index)
    }
    fn len(&cx: Shared!['r, 'q], bytes: Slice[u8, 'r]) -> usize {
        bytes.len()
    }
}

/// A byte view together with the capability that permits reading it, as
/// one value: what `Eq`, `Hash`, and `Format` instances take, since an
/// instance head must be a named type. `core::borrow::Borrowed!` is the
/// same idea for a `Ref`. Copy exactly when `C` is (e.g.
/// `core::str::StaticRead`).
forall C, S.
exposed struct Readable {
    cap: C,
    bytes: S,
}

/// Byte `index` of a view read through its capability (`ReadBytes::get`),
/// with `0u8` for out of range: a sentinel for scanners whose
/// character-class tests already treat `0u8` as matching nothing.
forall C, S where ReadBytes[C, S].
fn byte_or_zero(&cx: C, bytes: S, index: usize) -> u8 {
    let b = ReadBytes[C, S]::get(&cx, bytes, index);
    let v = match b {
        Some(x) => x,
        None => 0u8,
    };
    v
}

/// Content equality of two byte views, of equal or different brands and
/// capabilities. Two views of one exclusively owned domain cannot both
/// take its single `Exclusive!`; split shared access first (`Exclusive!::share`,
/// `Shared!::split`). Compares the last byte first: names of one length
/// usually differ at the end (`t_17` and `t_18`, `a::b::x` and `a::b::y`).
forall C1, S1, C2, S2 where ReadBytes[C1, S1], ReadBytes[C2, S2], Copy[S1], Copy[S2].
fn bytes_eq(&left_cap: C1, left: S1, &right_cap: C2, right: S2) -> bool {
    let n = ReadBytes[C1, S1]::len(&left_cap, left);
    let m = ReadBytes[C2, S2]::len(&right_cap, right);
    var same = n == m;
    var i = n;
    while same && i > 0usize {
        i = i - 1usize;
        let a = ReadBytes[C1, S1]::get(&left_cap, left, i);
        let b = ReadBytes[C2, S2]::get(&right_cap, right, i);
        let equal = match a {
            Some(x) => {
                match b {
                    Some(y) => x == y,
                    None => false,
                }
            },
            None => false,
        };
        same = equal;
    }
    same
}

/// Byte views in byte order, as unsigned values, a shorter prefix first.
/// As with `bytes_eq`, each view is read through its own capability.
forall C1, S1, C2, S2 where ReadBytes[C1, S1], ReadBytes[C2, S2], Copy[S1], Copy[S2].
fn bytes_cmp(&left_cap: C1, left: S1, &right_cap: C2, right: S2) -> Order {
    let n = ReadBytes[C1, S1]::len(&left_cap, left);
    let m = ReadBytes[C2, S2]::len(&right_cap, right);
    var i = 0usize;
    while i < n && i < m {
        let x = byte_or_zero(&left_cap, left, i);
        let y = byte_or_zero(&right_cap, right, i);
        if x != y {
            let order = if x < y {
                Order::Less
            } else {
                Order::Greater
            };
            return order;
        }
        i = i + 1usize;
    }
    let order = if n < m {
        Order::Less
    } else if n > m {
        Order::Greater
    } else {
        Order::Equal
    };
    order
}

/// `bytes_eq` for two views of one domain, read through its one capability
/// (which cannot be passed twice when it is linear); the last byte first,
/// as `bytes_eq` compares.
forall C, S where ReadBytes[C, S], Copy[S].
fn bytes_eq_within(&cx: C, left: S, right: S) -> bool {
    let n = ReadBytes[C, S]::len(&cx, left);
    var same = n == ReadBytes[C, S]::len(&cx, right);
    var i = n;
    while same && i > 0usize {
        i = i - 1usize;
        same = byte_or_zero(&cx, left, i) == byte_or_zero(&cx, right, i);
    }
    same
}

/// `bytes_cmp` for two views of one domain, read through its one capability.
forall C, S where ReadBytes[C, S], Copy[S].
fn bytes_cmp_within(&cx: C, left: S, right: S) -> Order {
    let n = ReadBytes[C, S]::len(&cx, left);
    let m = ReadBytes[C, S]::len(&cx, right);
    var i = 0usize;
    while i < n && i < m {
        let x = byte_or_zero(&cx, left, i);
        let y = byte_or_zero(&cx, right, i);
        if x != y {
            let order = if x < y {
                Order::Less
            } else {
                Order::Greater
            };
            return order;
        }
        i = i + 1usize;
    }
    let order = if n < m {
        Order::Less
    } else if n > m {
        Order::Greater
    } else {
        Order::Equal
    };
    order
}

/// The first index at or after `start` holding `needle`. Every search
/// takes what it looks for before where it starts:
/// `find_byte(&cx, bytes, needle, start)`, as `Str::find` and `Str::find_byte` do.
forall C, S where ReadBytes[C, S], Copy[S].
fn find_byte(&cx: C, bytes: S, needle: u8, start: usize) -> Option[usize] {
    let n = ReadBytes[C, S]::len(&cx, bytes);
    var i = start;
    var found = Option::None;
    var searching = true;
    while searching && i < n {
        let b = ReadBytes[C, S]::get(&cx, bytes, i);
        let hit = match b {
            Some(x) => x == needle,
            None => false,
        };
        if hit {
            found = Option::Some.(i);
            searching = false;
        }
        i = i + 1usize;
    }
    found
}

/// The first index at or after `start` where `needle`'s bytes appear in
/// `bytes`, both views read through the one capability. An empty `needle`
/// is found at `start` itself, when `start` is within `bytes`.
forall C, S where ReadBytes[C, S], Copy[S].
fn find_bytes(&cx: C, bytes: S, needle: S, start: usize) -> Option[usize] {
    let n = ReadBytes[C, S]::len(&cx, bytes);
    let m = ReadBytes[C, S]::len(&cx, needle);
    var i = start;
    var found = Option::None;
    while found.is_none() && i <= n && m <= n - i {
        var j = 0usize;
        while j < m && byte_or_zero(&cx, bytes, i + j) == byte_or_zero(&cx, needle, j) {
            j = j + 1usize;
        }
        if j == m {
            found = Option::Some.(i);
        }
        i = i + 1usize;
    }
    found
}

/// The last index holding `needle`.
forall C, S where ReadBytes[C, S], Copy[S].
fn rfind_byte(&cx: C, bytes: S, needle: u8) -> Option[usize] {
    var i = ReadBytes[C, S]::len(&cx, bytes);
    var found = Option::None;
    while found.is_none() && i > 0usize {
        i = i - 1usize;
        if byte_or_zero(&cx, bytes, i) == needle {
            found = Option::Some.(i);
        }
    }
    found
}

/// Writes a byte view into `state` (`core::hash`'s encoding of a byte
/// string): its length, then its bytes eight to a word, little-endian, the
/// last word padded with zeros.
forall C, S where ReadBytes[C, S], Copy[S].
fn hash_bytes(&cx: C, bytes: S, state: HashState) -> HashState {
    let n = ReadBytes[C, S]::len(&cx, bytes);
    var s = state.write_u64(n as u64);
    var i = 0usize;
    while n - i >= 8usize {
        s = s.write_u64(word8(&cx, bytes, i));
        i = i + 8usize;
    }
    if i < n {
        var word = 0u64;
        var k = 0usize;
        while i + k < n {
            word = word | (byte_word(&cx, bytes, i + k) << ((k * 8usize) as u64));
            k = k + 1usize;
        }
        s = s.write_u64(word);
    }
    s
}

/// Byte `i` of a byte view as a word (`byte_or_zero`).
forall C, S where ReadBytes[C, S], Copy[S].
fn byte_word(&cx: C, bytes: S, i: usize) -> u64 {
    byte_or_zero(&cx, bytes, i) as u64
}

/// Bytes `i..i + 8` of a byte view as a little-endian word.
forall C, S where ReadBytes[C, S], Copy[S].
fn word8(&cx: C, bytes: S, i: usize) -> u64 {
    byte_word(&cx, bytes, i) | (byte_word(&cx, bytes, i + 1usize) << 8u64)
        | (byte_word(&cx, bytes, i + 2usize) << 16u64) | (byte_word(&cx, bytes, i + 3usize) << 24u64)
        | (byte_word(&cx, bytes, i + 4usize) << 32u64) | (byte_word(&cx, bytes, i + 5usize) << 40u64)
        | (byte_word(&cx, bytes, i + 6usize) << 48u64) | (byte_word(&cx, bytes, i + 7usize) << 56u64)
}

/// Readable views are equal when their bytes are (`bytes_eq`).
forall C1, S1, C2, S2 where ReadBytes[C1, S1], ReadBytes[C2, S2], Copy[S1], Copy[S2].
instance Eq[Readable[C1, S1], Readable[C2, S2]] {
    fn eq(a: Readable[C1, S1], b: Readable[C2, S2]) -> (Readable[C1, S1], Readable[C2, S2], bool) {
        var { cap: ca, bytes: sa } = a;
        var { cap: cb, bytes: sb } = b;
        let same = bytes_eq(&ca, sa, &cb, sb);
        (Readable.{ cap: ca, bytes: sa }, Readable.{ cap: cb, bytes: sb }, same)
    }
}

/// A readable view hashes its bytes (`hash_bytes`).
forall C, S where ReadBytes[C, S], Copy[S].
instance Hash[Readable[C, S]] {
    fn hash(self: Readable[C, S], state: HashState) -> (Readable[C, S], HashState) {
        var { cap: c, bytes: s } = self;
        let state2 = hash_bytes(&c, s, state);
        (Readable.{ cap: c, bytes: s }, state2)
    }
}

// ------------------------------------------------------------ iteration --
/// A slice's elements in order, read under the capability a context lends
/// (`Access`). `iter` opens the context and the iterator holds what it
/// opened while it runs; `finish` closes it and hands the context back:
/// `var it = bytes.iter(cx); for b in &it { .. } let cx = it.finish();`.
forall T, 'k, C, R.
exposed struct SliceIter! {
    tag: Exclusive!['k],
    rest: R,
    slice: Slice[T, 'k],
    index: usize,
}

forall T, 'k where Copy[T].
impl Slice[T, 'k] {
    /// The elements in order, read under the capability `cx` lends, which
    /// the iterator's `finish` hands back.
    forall C, R where Access[C -> 'k, R].
    fn iter(self, cx: C) -> SliceIter![T, 'k, C, R] {
        let (tag, rest) = Access[C -> 'k, R]::open(cx);
        SliceIter!.{ tag, rest, slice: self, index: 0usize }
    }
}

forall T, 'k, C, R where Access[C -> 'k, R].
impl SliceIter![T, 'k, C, R] {
    /// Ends the iteration, handing back the context.
    fn finish(self) -> C {
        let { tag, rest, slice: _slice, index: _index } = self;
        Access[C -> 'k, R]::close(tag, rest)
    }
}

/// The slice's elements in order, read under the capability the iterator holds.
forall T, 'k, C, R where Copy[T], Sized[T].
instance Iterator[SliceIter![T, 'k, C, R] -> T] {
    fn next(&it: SliceIter![T, 'k, C, R]) -> Option[T] {
        var { tag, rest, slice, index } = it;
        let item = slice.get(&tag, index);
        let next_index = if item.is_some() { index + 1usize } else { index };
        it = SliceIter!.{ tag, rest, slice, index: next_index };
        item
    }
}