alloc/buffer.kur
//! Growable byte buffers with explicit ownership and initialized length.
// alloc::buffer -- `Buffer!`, the growable, heap-owned byte buffer. Always
// `u8`. Linear, so a buffer that is built but never consumed is a compile
// error rather than a leak.
//
// It serves two roles: a growable accumulator (`new`, its `Writer`
// instance, `reserve`/`tail_ptr`/`commit`, `as_ptr`, `len`) and, through
// `open` and `BufferRestore!`, a checked, branded view of its bytes that can
// be turned back into a growable buffer.
//
// It is written through `core::fmt::Writer` and the methods every writer
// has: `Buffer!::new().put("n = ").put(n).write(&cx, name)`. It is also
// the default writer for `f"..."` interpolation.
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::{Brand, Exclusive!};
use core::mem::Ref;
use core::ptr::offset;
use alloc::owned::Allocation!;
use core::mem::Region!;
use core::mem::RegionResume!;
use core::slice::Slice;
use core::str::Str;
use core::slice::{ReadBytes, Readable, hash_bytes, bytes_eq, bytes_cmp};
use core::cmp::{Ord, Order};
use core::hash::{Hash, Eq, HashState};
use core::option::Result;
use core::iter::Iterator;
use core::fmt::Writer;
/// Growable byte buffer with an explicit owner and initialized length.
///
/// Restricted: no other module can write the literal, which would otherwise
/// let it wrap any pointer (say, one read off a live `Slice`) and `destroy`
/// it -- an arbitrary `free` with no `unsafe`. Adopting storage requires
/// an owned `Uninit!` and an explicit claim about which bytes are initialized.
struct Buffer! {
ptr: *u8,
len: usize,
cap: usize,
}
/// The way back from `Buffer!::open` to a growable `Buffer!`. Carries `cap`
/// as well as `len`, so a restored buffer keeps growing as before.
///
/// Restricted: `restore` turns one of these plus a matching `Exclusive!['k]`
/// into an owning `Buffer!`, so forging one would yield a freeable buffer
/// over an arbitrary pointer.
///
/// The address and the brand travel inside the two linear `core::mem`
/// records that `Allocation!::adopt` and `Region!::share` mint over the
/// buffer's storage:
///
/// * `store: Allocation![u8,'k]` -- the right to retire the block, and the
/// only thing that remembers its base. Restricted, linear and
/// unprojectable, so it cannot be offset.
/// * `back: RegionResume![u8,'k]` -- the receipt for the `Exclusive!['k]`
/// that `open` handed out. `resume` demands that exact witness back and
/// returns the complete `Region![u8,'k]` that `Allocation!::release`
/// requires.
///
/// No separate `Brand['k]` field: everything `restore` builds is brandless,
/// so the brand is never needed as a value.
forall 'k.
struct BufferRestore! {
store: Allocation![u8, 'k],
back: RegionResume![u8, 'k],
len: usize,
cap: usize,
}
// `with_capacity` aborts when its allocation fails, and `commit` when asked
// for a `len` past `cap`, matching `alloc::heap`'s aborting API: a
// `Buffer!`-returning method has no error channel, so an unsatisfiable
// request is a hard stop.
impl Buffer! {
/// Takes ownership of an allocation whose first `len` bytes are initialized.
/// The allocation's recorded extent becomes the buffer's capacity.
/// Aborts if `len` exceeds that extent.
///
/// Caller: `storage` records the allocation's capacity, and its prefix of
/// `len` bytes has already been written.
unsafe fn from_initialized_allocation(storage: Uninit!, len: usize) -> Buffer! {
let (ptr, cap) = storage.into_parts();
let buffer = Buffer!.{ ptr, len: 0usize, cap };
unsafe buffer.commit(len)
}
/// A new, empty buffer with room for `cap` bytes before the first grow,
/// or the allocation failure. Growing it later aborts as `reserve` does.
fn try_with_capacity(cap: usize) -> Result[Buffer!, AllocError] {
match Storage::try_alloc(cap) {
Ok(u) => Result::Ok.(Buffer!.{ ptr: u.into_raw(), len: 0usize, cap }),
Err(e) => Result::Err.(e),
}
}
/// A new, empty buffer with room for `cap` bytes, aborting when the
/// allocation fails.
///
/// `try_with_capacity`, aborting on failure. `new` is this with a starting
/// capacity of 64.
fn with_capacity(cap: usize) -> Buffer! {
match Buffer!::try_with_capacity(cap) {
Ok(b) => b,
Err(e) => unsafe abort(),
}
}
/// A new, empty buffer with room for 64 bytes.
fn new() -> Buffer! {
Buffer!::with_capacity(64usize)
}
/// A buffer of exactly `n` zero bytes: `len == cap == n`, every byte
/// initialized, so it is safe and carries no obligation.
///
/// For a caller that wants a fixed-size buffer whose every index is
/// addressable after `open` (so `get_ref` admits it), and then writes
/// through the brand. Zeroing costs one pass over `n` bytes and means no
/// uninitialized byte is ever inside `len`.
fn new_zeroed(n: usize) -> Buffer! {
let b = Buffer!::with_capacity(n);
let { ptr: p, len: len_, cap: c } = b;
var i = 0usize;
while i < n {
let d = unsafe offset(p, i);
unsafe *d = 0u8;
i = i + 1usize;
}
Buffer!.{ ptr: p, len: n, cap: c }
}
/// Grows (doubling) until at least `extra` more bytes fit; a no-op
/// otherwise. Aborts if the size overflows `usize`. Room reserved this
/// way is what `tail_ptr` hands out, for a caller that writes into it
/// directly (a system call filling the buffer in place) and `commit`s.
fn reserve(self, extra: usize) -> Buffer! {
let { ptr: p, len: n, cap: c } = self;
let needed = checked_add(n, extra);
let has_room = needed <= c;
if has_room {
Buffer!.{ ptr: p, len: n, cap: c }
} else {
// Double, but never to less than `needed` or 16 bytes, so a
// buffer of capacity 0 grows too.
let doubled = checked_mul(c, 2usize);
let at_least = if needed > 16usize { needed } else { 16usize };
let new_cap = if doubled > at_least { doubled } else { at_least };
let u2 = HeapAllocator::grow(unsafe HeapAllocator::adopt_raw(p), new_cap);
let newp = u2.into_raw();
Buffer!.{ ptr: newp, len: n, cap: new_cap }
}
}
/// The first `len` bytes, or all of them when there are fewer; the
/// room stays for what is written next.
fn truncate(self, len: usize) -> Buffer! {
let { ptr: p, len: n, cap: c } = self;
Buffer!.{ ptr: p, len: if len < n { len } else { n }, cap: c }
}
/// No bytes, with the room kept.
fn clear(self) -> Buffer! {
self.truncate(0usize)
}
/// A new buffer holding the same bytes; `self` comes back unchanged.
fn clone(&self) -> Buffer! {
let p = unsafe &self.as_ptr();
let n = &self.len();
// `p` points at the `n` initialized bytes of `self`, which stays
// alive until the copy is made.
unsafe Writer[Buffer!]::write_raw(Buffer!::with_capacity(n), p, n)
}
/// Number of initialized bytes.
///
/// `&self`: `self` is linear, so even a query hands the buffer back
/// first, as `&b.len()` at the call site.
fn len(&self) -> usize {
let { ptr: p, len: n, cap: c } = self;
self = Buffer!.{ ptr: p, len: n, cap: c };
n
}
/// How many more bytes fit before the next grow: `cap - len`.
fn remaining_capacity(&self) -> usize {
let { ptr: p, len: n, cap: c } = self;
self = Buffer!.{ ptr: p, len: n, cap: c };
c - n
}
/// Address of the first byte, valid until the next grow. Caller: uses it
/// only for the buffer's first `len` bytes, and not after the next grow
/// or `destroy`.
unsafe fn as_ptr(&self) -> *u8 {
let { ptr: p, len: n, cap: c } = self;
self = Buffer!.{ ptr: p, len: n, cap: c };
p
}
/// Address of the first unused byte, writable up to the room `reserve`
/// most recently guaranteed. Pairs with `commit`. The pointer is valid
/// only until the next grow. Takes `&self` because a linear buffer must
/// survive the call so the caller can `commit` afterwards. Caller: writes
/// no further than the room `reserve` guaranteed, and stops using the
/// pointer at the next grow or `destroy`.
unsafe fn tail_ptr(&self) -> *u8 {
let { ptr: p, len: n, cap: c } = self;
let addr = unsafe offset(p, n);
self = Buffer!.{ ptr: p, len: n, cap: c };
addr
}
/// Advances `len` by `n` without writing anything. Pairs with
/// `reserve`/`tail_ptr`.
///
/// Capacity is checked: if the new length would exceed `cap`, this
/// aborts. Without the check, `open` would hand out a `Slice` longer than
/// the block, and `Slice::get_ref`'s bounds check (against the slice's
/// length) would admit out-of-bounds indices.
///
/// Caller: all `n` bytes at `p[len .. len+n)` have been written since the
/// last `reserve`/grow, so the new `len` describes initialized storage;
/// initialization cannot be checked.
///
/// A caller that only wants a fixed-size, fully addressable buffer should
/// use `Buffer!::new_zeroed`, which carries no obligation.
unsafe fn commit(self, n: usize) -> Buffer! {
let { ptr: p, len: len_, cap: c } = self;
let new_len = checked_add(len_, n);
let past_cap = new_len > c;
let g: () = if past_cap { unsafe abort() } else { () };
Buffer!.{ ptr: p, len: new_len, cap: c }
}
/// Frees the buffer. Every `Buffer!` must reach this, or be handed on,
/// before its function returns.
fn destroy(self) -> () {
let { ptr: p, len: n, cap: c } = self;
HeapAllocator::drop(unsafe HeapAllocator::adopt_raw(p))
}
/// A branded view of the buffer's bytes, with its capability and the
/// record that restores the buffer.
///
/// Mints a fresh brand over this buffer's storage and returns a
/// `Slice[u8,'1]` to read and write through, plus `BufferRestore!`, the
/// only way back to a growable `Buffer!`. The address the way back uses
/// is captured here from `self`, never from the `Slice` (which
/// `Slice::sub` can offset).
///
/// `Allocation!::adopt` keeps the base in a linear, restricted,
/// unprojectable `Allocation![u8,'1]`; `Region!::share` hands out the
/// `Exclusive!`/`Ref` access pair plus the `RegionResume![u8,'1]` receipt
/// that `restore` needs.
///
/// Uses `adopt_raw`, not `adopt_raw_sized(p, c)`: the allocation record
/// holds extent `0usize` ("not recorded") and `BufferRestore!` carries
/// `cap` itself. Nothing reads the
/// record's extent: `restore` discards it via `into_raw`.
fn open(self) -> exists '1. (Exclusive!['1], Slice[u8, '1], BufferRestore!['1]) {
let { ptr: p, len: n, cap: c } = self;
// `adopt`'s obligation, at `u8`: the block is a `malloc` result of at
// least one byte (`alloc` asks for one where 0 were requested). Its
// bytes past `len` may be uninitialized, but the region never leaves
// this module and is never read: `share`'s `Ref` is taken apart into
// the base address at once, the `Slice` reads only the first `len`
// bytes, and `restore` resumes the region only to release it.
let exists 'open1. (a, rg) = unsafe Allocation!::adopt[u8](unsafe HeapAllocator::adopt_raw(p));
let (tag, r, back) = rg.share();
let (p2, m) = r.into_parts();
// `Slice::from_raw_parts`: `n` is this buffer's maintained length
// invariant (the initialized prefix), not a caller-supplied value.
let slice = unsafe Slice::from_raw_parts(p2, n, m);
let restore = BufferRestore!.{ store: a, back: back, len: n, cap: c };
pack 'open1. (tag, slice, restore)
}
}
/// A buffer as a writer: every write appends, growing first if needed.
///
/// Infallible: `Buffer!` aborts on out-of-memory.
instance Writer[Buffer!] {
fn write_byte(self: Buffer!, byte: u8) -> Buffer! {
let { ptr: p, len: n, cap: c } = self.reserve(1usize);
let dest = unsafe offset(p, n);
unsafe *dest = byte;
Buffer!.{ ptr: p, len: checked_add(n, 1usize), cap: c }
}
/// Copies the bytes in one step: `'static` text is permanent and
/// immutable (`core::str::StaticRead`), so reading it needs no
/// capability.
fn write_static(self: Buffer!, bytes: Str['static]) -> Buffer! {
let (p, n) = bytes.into_parts();
unsafe Writer[Buffer!]::write_raw(self, p, n)
}
/// Caller: as for `Writer::write_raw`, `ptr[0..len)` is readable for the
/// whole call; and it is not inside this buffer's own storage, which the
/// grow may free.
unsafe fn write_raw(self: Buffer!, ptr: *u8, len: usize) -> Buffer! {
let { ptr: p, len: n, cap: c } = self.reserve(len);
var i = 0usize;
while i < len {
let v = unsafe *(unsafe offset(ptr, i));
unsafe *(unsafe offset(p, n + i)) = v;
i = i + 1usize;
}
Buffer!.{ ptr: p, len: checked_add(n, len), cap: c }
}
}
forall 'k.
impl BufferRestore!['k] {
/// Rebuilds the growable `Buffer!` from this record and the capability
/// `open` handed out.
///
/// The only way back to a growable `Buffer!`. Sound however the `Slice`
/// from the same `open` was sub-sliced or used, since the address rebuilt
/// here never came from it.
///
/// `resume` demands the exact `Exclusive!['k]` that `open`'s `share`
/// handed out and rebuilds the complete `Region![u8,'k]`; `release`
/// demands that complete region -- proof that every access capability of
/// this brand has come back -- and returns the `Uninit!` whose base
/// `Allocation!::adopt` recorded. No `Ref` is constructed, and no address
/// is read out of a field this module wrote. `'k` is sealed fresh per
/// `open`, and `BufferRestore!` is restricted and linear, so the only
/// `Exclusive!['k]` that exists for this brand is the one passed here.
fn restore(self, tag: Exclusive!['k]) -> Buffer! {
let { store: a, back: bk, len: n, cap: c } = self;
let rg = bk.resume(tag);
let uninit = a.release(rg);
let raw = uninit.into_raw();
Buffer!.{ ptr: raw, len: n, cap: c }
}
}
/// Hashes the buffer's bytes in order.
///
/// A buffer hashes and compares by its contents, so it can key a map.
instance Hash[Buffer!] {
fn hash(self: Buffer!, state: HashState) -> (Buffer!, HashState) {
var exists 'b. (tag, bytes, restore) = self.open();
let state = hash_bytes(&tag, bytes, state);
(restore.restore(tag), state)
}
}
/// Byte equality of two buffers.
instance Eq[Buffer!, Buffer!] {
fn eq(a: Buffer!, b: Buffer!) -> (Buffer!, Buffer!, bool) {
var exists 'x. (xtag, xs, xback) = a.open();
var exists 'y. (ytag, ys, yback) = b.open();
let same = bytes_eq(&xtag, xs, &ytag, ys);
(xback.restore(xtag), yback.restore(ytag), same)
}
}
/// A buffer equals a borrowed view with the same bytes, which lets a map
/// keyed by `Buffer!` be searched with a view (`HashMap!::find`). The two
/// `Hash` instances agree: both hash the bytes in order.
forall C, S where ReadBytes[C, S], Copy[S].
instance Eq[Buffer!, Readable[C, S]] {
fn eq(a: Buffer!, b: Readable[C, S]) -> (Buffer!, Readable[C, S], bool) {
var exists 'x. (xtag, xs, xback) = a.open();
var { cap, bytes } = b;
let same = bytes_eq(&xtag, xs, &cap, bytes);
(xback.restore(xtag), Readable.{ cap, bytes }, same)
}
}
/// Buffers order by their bytes, as unsigned values, a shorter prefix first.
instance Ord[Buffer!, Buffer!] {
fn cmp(a: Buffer!, b: Buffer!) -> (Buffer!, Buffer!, Order) {
var exists 'x. (xtag, xs, xback) = a.open();
var exists 'y. (ytag, ys, yback) = b.open();
let order = bytes_cmp(&xtag, xs, &ytag, ys);
(xback.restore(xtag), yback.restore(ytag), order)
}
}
// An iterator's remaining bytes, in order, in a new buffer.
forall I where Iterator[I -> u8].
impl I {
/// The iterator's remaining bytes, in order, in a new buffer.
fn collect_bytes(self) -> (I, Buffer!) {
var it = self;
var out = Buffer!::new();
for b in &it {
out = out.write_byte(b);
}
(it, out)
}
}