332 lines
10 KiB
Plaintext
332 lines
10 KiB
Plaintext
// memio — in-memory io stream. Project #94 fold-eFinal.
|
|
//
|
|
// Hare's memio:: surface, drop underscores. Two flavours behind a
|
|
// single [[io.stream]] (= `*io.vtable`):
|
|
//
|
|
// fixed caller owns the buffer, writes stop when full.
|
|
// dynamic memio owns the buffer, writes grow it; close frees.
|
|
//
|
|
// Hare's memio::fixed/dynamic/dynamic_from return a `stream` whose
|
|
// FIRST field IS the `io::stream` (= `*vtable`). ww mirrors that
|
|
// intrusively: `stream`'s first field is `vt: io.vtable` (the vtable
|
|
// embedded INLINE) so a stack `stream` is castable to
|
|
// `io.stream = *vtable` via `&s.vt` — and the callbacks recover the
|
|
// outer `stream` by casting the dispatch arg back to `*stream`. Same
|
|
// intrusive shape as lib/bufio + lib/log over their embedded vtables.
|
|
//
|
|
// let s: memio.stream = memio.fixed(buf);
|
|
// io.write(&s.vt, bytes);
|
|
// let view: str = memio.string(&s);
|
|
//
|
|
// Constructors return the `stream` BY VALUE (Hare shape,
|
|
// ref/hare/memio/stream.ha:46,58,64): build the struct in a local,
|
|
// field-assign every slot, and `return r;` (the proven sret round-trip
|
|
// pinned by test/wcc/925 + 776). NO heap, NO `nomem`: the alloc that
|
|
// forced an earlier heap return is gone, so the constructor cannot
|
|
// fail. Caller owns the returned `stream` (stack ownership, no-GC) and
|
|
// passes `&s.vt` to the io dispatchers — exactly Hare's `&s` into
|
|
// io::write.
|
|
//
|
|
// Subset of Hare's surface: io's variants are {eof, error}, so memio
|
|
// drops Hare's NONBLOCK flag (would need an `again` variant in lib/io).
|
|
// string()'s utf8-validating constructor is omitted per CLAUDE.md
|
|
// rule 9 carve-out — see [[string]]. Hare's copy callback is absent:
|
|
// io's vtable has no copier slot yet (deferred with `handle`-typed
|
|
// io.copy, lib/io/stream.ww header). The seeker is wired — see
|
|
// [[seekfn]].
|
|
//
|
|
// Cast workaround per #206-payoff (ken: KEEP the explicit casts; they
|
|
// are cgen-neutral and sidestep the #214 over-acceptance surface). The
|
|
// `(&fn_name): *io.<role>` cast at each store site is the Hare-faithful
|
|
// minimum-touch route — the #206 cast-drop is a separate deferred
|
|
// payoff gated on #214.
|
|
//
|
|
// ptr/len/cap kept flat (no `buf: []u8`) per a historical cgen note:
|
|
// chained-dot writes through a state pointer into a slice subfield
|
|
// miscompile silently (#195 family); the flat shape sidesteps it.
|
|
// dynamicfrom uses the slice's `cap` (NOT `len`) to track the
|
|
// allocated-capacity-to-free on close — passing a half-filled append
|
|
// slice with len < cap and using only `buf.len` would under-free.
|
|
|
|
package memio;
|
|
|
|
import errors;
|
|
import io;
|
|
import os;
|
|
import rt;
|
|
import types;
|
|
|
|
// stream — Hare's memio::stream (ref/hare/memio/stream.ha:18). `vt` at
|
|
// offset 0 for the intrusive stream→io.stream cast (`&s.vt`) and the
|
|
// callbacks' reverse `s: *stream` cast. Unified across fixed/dynamic
|
|
// (Hare keeps a single `stream` over per-mode vtable singletons; ww
|
|
// wires the per-mode callbacks post-construction instead). ptr/len/cap
|
|
// flat per the header note.
|
|
export type stream = struct {
|
|
vt: io.vtable,
|
|
ptr: *u8,
|
|
len: i32,
|
|
cap: i32,
|
|
pos: i32,
|
|
};
|
|
|
|
// fixed — wire a stream over a caller-supplied buffer. Writes never
|
|
// grow; a write to a full buffer returns nomem, matching Hare
|
|
// (ref/hare/memio/stream.ha:44,161). A zero-length write always
|
|
// succeeds with 0 (the empty-input short-circuit, stream.ha:157).
|
|
//
|
|
// Mirrors ref/hare/memio/stream.ha:46.
|
|
export fn fixed(buf: []u8) stream = {
|
|
let r: stream;
|
|
r.vt.reader = (&readfn): *io.reader;
|
|
r.vt.writer = (&fixedwrite): *io.writer;
|
|
r.vt.seeker = (&seekfn): *io.seeker;
|
|
r.ptr = buf.ptr;
|
|
r.len = buf.len;
|
|
r.cap = buf.len;
|
|
r.pos = 0;
|
|
return r;
|
|
};
|
|
|
|
// dynamic — wire a stream with no initial buffer. Writes grow the
|
|
// backing allocation; [[io.close]] frees it.
|
|
//
|
|
// Mirrors ref/hare/memio/stream.ha:58.
|
|
export fn dynamic() stream = {
|
|
let r: stream;
|
|
r.vt.reader = (&readfn): *io.reader;
|
|
r.vt.writer = (&dynamicwrite): *io.writer;
|
|
r.vt.closer = (&dynamicclose): *io.closer;
|
|
r.vt.seeker = (&seekfn): *io.seeker;
|
|
r.ptr = nil;
|
|
r.len = 0;
|
|
r.cap = 0;
|
|
r.pos = 0;
|
|
return r;
|
|
};
|
|
|
|
// dynamicfrom — like [[dynamic]] but seeded with an existing slice.
|
|
// Ownership transfers; close frees `cap` bytes from the slice's
|
|
// allocated capacity (NOT logical length).
|
|
//
|
|
// Mirrors ref/hare/memio/stream.ha:64.
|
|
export fn dynamicfrom(buf: []u8) stream = {
|
|
let r: stream;
|
|
r.vt.reader = (&readfn): *io.reader;
|
|
r.vt.writer = (&dynamicwrite): *io.writer;
|
|
r.vt.closer = (&dynamicclose): *io.closer;
|
|
r.vt.seeker = (&seekfn): *io.seeker;
|
|
r.ptr = buf.ptr;
|
|
r.len = buf.len;
|
|
r.cap = buf.cap;
|
|
r.pos = 0;
|
|
return r;
|
|
};
|
|
|
|
// memiomove copies n bytes correctly for disjoint or overlapping regions.
|
|
// Copy backwards whenever the destination starts above the source; that is
|
|
// the only overlap direction a forward loop can corrupt.
|
|
fn memiomove(dst: *u8, src: *u8, n: i32) void = {
|
|
if (n <= 0 || dst == src) { return; };
|
|
let i: i32 = 0;
|
|
if ((dst: uintptr) > (src: uintptr)) {
|
|
i = n;
|
|
for (i > 0) {
|
|
i -= 1;
|
|
dst[i] = src[i];
|
|
};
|
|
} else {
|
|
for (i < n) {
|
|
dst[i] = src[i];
|
|
i += 1;
|
|
};
|
|
};
|
|
};
|
|
|
|
// readfn — recover the stream from the io.stream's `*vtable` via the
|
|
// intrusive offset-0 cast. Single fn over the common header (Hare's
|
|
// single `read` at ref/hare/memio/stream.ha:103); fixed and dynamic
|
|
// share it because the read path is buffer-flavour-agnostic.
|
|
fn readfn(s: io.stream, buf: []u8) (size | io.eof | io.error) = {
|
|
let m: *stream = s: *stream;
|
|
if (m.pos >= m.len) {
|
|
let e: io.eof;
|
|
return e;
|
|
};
|
|
let avail: i32 = m.len - m.pos;
|
|
let n: i32 = buf.len;
|
|
if (avail < n) { n = avail; };
|
|
memiomove(buf.ptr, m.ptr + (m.pos: u64), n);
|
|
m.pos += n;
|
|
return n: size;
|
|
};
|
|
|
|
// seekfn — SET/CUR/END cursor reposition over the common header;
|
|
// fixed and dynamic share it (Hare wires the same `seek` into both
|
|
// vtables, ref/hare/memio/stream.ha:26,34).
|
|
//
|
|
// Mirrors ref/hare/memio/stream.ha:122-140. len(s.buf) → m.len;
|
|
// `pos` is i32 while io.off is i64, so the arithmetic runs in i64 and
|
|
// narrows only after the bounds check. Hare's two-sided check works
|
|
// in unsigned `size` with a negation dance; the signed i64 spelling
|
|
// here is the same predicate without it.
|
|
fn seekfn(s: io.stream, off: io.off, w: io.whence) (io.off | io.error) = {
|
|
let m: *stream = s: *stream;
|
|
// cstage binop typing is nominal (no alias peel: `off` vs i64
|
|
// rejected, wwstage accepts — ww-core #54), so the arithmetic
|
|
// runs on an i64 copy.
|
|
let n: i64 = off: i64;
|
|
let start: i64 = 0;
|
|
switch (w) {
|
|
case io.whence.SET: start = 0;
|
|
case io.whence.CUR: start = m.pos: i64;
|
|
case io.whence.END: start = m.len: i64;
|
|
};
|
|
if (n < 0) {
|
|
if (n < -start) {
|
|
let v: errors.invalid;
|
|
let e: io.error = v;
|
|
return e;
|
|
};
|
|
} else {
|
|
if ((m.len: i64) - start < n) {
|
|
let v: errors.invalid;
|
|
let e: io.error = v;
|
|
return e;
|
|
};
|
|
};
|
|
m.pos = (start + n): i32;
|
|
return m.pos: io.off;
|
|
};
|
|
|
|
fn fixedwrite(s: io.stream, buf: []u8) (size | io.error) = {
|
|
let m: *stream = s: *stream;
|
|
if (buf.len == 0) { return 0: size; }; // ref/hare/memio/stream.ha:157
|
|
if (m.pos >= m.len) { // ref/hare/memio/stream.ha:161
|
|
let nm: nomem;
|
|
let e: io.error = nm;
|
|
return e;
|
|
};
|
|
let space: i32 = m.len - m.pos;
|
|
let n: i32 = buf.len;
|
|
if (space < n) { n = space; };
|
|
memiomove(m.ptr + (m.pos: u64), buf.ptr, n);
|
|
m.pos += n;
|
|
return n: size;
|
|
};
|
|
|
|
fn dynamicwrite(s: io.stream, buf: []u8) (size | io.error) = {
|
|
let m: *stream = s: *stream;
|
|
if (buf.len > types.I32_MAX - m.pos) {
|
|
let nm: nomem;
|
|
let e: io.error = nm;
|
|
return e;
|
|
};
|
|
let need: i32 = m.pos + buf.len;
|
|
let aliased: bool = false;
|
|
let srcoff: i32 = 0;
|
|
if (m.cap > 0 && (buf.ptr: uintptr) >= (m.ptr: uintptr)) {
|
|
let delta: uintptr = (buf.ptr: uintptr) - (m.ptr: uintptr);
|
|
if (delta < (m.cap: uintptr)) {
|
|
assert(buf.len <= m.cap - (delta: i32),
|
|
"memio.dynamicwrite: aliased source exceeds buffer");
|
|
aliased = true;
|
|
srcoff = delta: i32;
|
|
};
|
|
};
|
|
if (need > m.cap) {
|
|
dynamicgrow(m, need);
|
|
if (aliased) { buf.ptr = m.ptr + (srcoff: u64); };
|
|
};
|
|
memiomove(m.ptr + (m.pos: u64), buf.ptr, buf.len);
|
|
m.pos += buf.len;
|
|
if (m.pos > m.len) { m.len = m.pos; };
|
|
return buf.len: size;
|
|
};
|
|
|
|
fn dynamicclose(s: io.stream) (void | io.error) = {
|
|
let m: *stream = s: *stream;
|
|
if (m.cap > 0) { os.free(m.ptr: *void, m.cap: u64); };
|
|
m.ptr = nil;
|
|
m.len = 0;
|
|
m.cap = 0;
|
|
m.pos = 0;
|
|
return;
|
|
};
|
|
|
|
// Double-and-copy growth with floor at 8. `dynamicgrow`, not Hare's
|
|
// bare `grow`: cstage bundles all imported modules into a flat TU and
|
|
// resolves private fns by unqualified name (task #9), so the
|
|
// module-prefixed name keeps the symmetry with dynamicwrite/dynamicclose.
|
|
fn dynamicgrow(d: *stream, need: i32) void = {
|
|
let newcap: i32 = d.cap;
|
|
if (newcap < 8) { newcap = 8; };
|
|
for (newcap < need) {
|
|
if (newcap > types.I32_MAX / 2) {
|
|
newcap = need;
|
|
break;
|
|
};
|
|
newcap *= 2;
|
|
};
|
|
let nbuf: *u8 = rt.malloc(newcap: u64): *u8;
|
|
memiomove(nbuf, d.ptr, d.len);
|
|
if (d.cap > 0) { os.free(d.ptr: *void, d.cap: u64); };
|
|
d.ptr = nbuf;
|
|
d.cap = newcap;
|
|
};
|
|
|
|
// string — bytes written so far, as a str view (buf[0..pos]).
|
|
//
|
|
// Mirrors ref/hare/memio/stream.ha:81 string(in: *stream). Hare returns
|
|
// (str | utf8::invalid) — the validating constructor. ww returns a bare
|
|
// `str` per the CLAUDE.md rule-9 frombytes carve-out: utf8.validate at
|
|
// the IO source is opt-in, never wrapped per-construction; the honest
|
|
// name reserves a future validating helper.
|
|
export fn string(s: *stream) str = {
|
|
let r: str;
|
|
r.ptr = s.ptr;
|
|
r.len = s.pos;
|
|
r.cap = r.len;
|
|
return r;
|
|
};
|
|
|
|
// buffer — borrowed []u8 view of bytes written so far (buf[0..pos]).
|
|
//
|
|
// Mirrors ref/hare/memio/stream.ha:74 buffer(in: *stream).
|
|
export fn buffer(s: *stream) []u8 = {
|
|
let r: []u8;
|
|
r.ptr = s.ptr;
|
|
r.len = s.pos;
|
|
r.cap = r.len;
|
|
return r;
|
|
};
|
|
|
|
// reset — rewind the cursor and truncate the logical content to 0.
|
|
// Backing storage is preserved; subsequent writes (dynamic) re-fill
|
|
// from the start without reallocation.
|
|
//
|
|
// Mirrors ref/hare/memio/stream.ha:87 reset(in: *stream).
|
|
export fn reset(s: *stream) void = {
|
|
s.pos = 0;
|
|
s.len = 0;
|
|
};
|
|
|
|
// borrowedread — return an `amt`-byte view starting at `pos` without
|
|
// copying, advancing the cursor. eof if fewer bytes are available.
|
|
//
|
|
// Mirrors ref/hare/memio/stream.ha:94 borrowedread(st: *stream, amt).
|
|
// `amt: i32` (not Hare's `size`) per the i32-index convention.
|
|
export fn borrowedread(s: *stream, amt: i32) ([]u8 | io.eof) = {
|
|
assert(amt >= 0, "memio.borrowedread: amount must not be negative");
|
|
if (s.len - s.pos < amt) {
|
|
let e: io.eof;
|
|
return e;
|
|
};
|
|
let r: []u8;
|
|
r.ptr = s.ptr + (s.pos: u64);
|
|
r.len = amt;
|
|
r.cap = r.len;
|
|
s.pos += amt;
|
|
return r;
|
|
};
|