Phase 2: I/O intrinsics, linear resources, deterministic profile (RFC 0007)

- air: resource types file<read|write|append>, listener, stream; io_error;
  intrinsic registry (19 intrinsics) synced with reference/intrinsics.md;
  fallible intrinsics as ok/err terminators; fs prefix narrowing;
  linear_aggregates gating
- verifier: intrinsic form, operand, result and capability-kind checks
  (E1001, E3201, E5002); intrinsic effects (E3101); resource linearity
  in the borrow walker with per-edge moves: E3002 leaks and join
  mismatches, E3001, E2001, E2002, E2101 for close while borrowed;
  resources as borrow roots
- interp: deterministic world (captured console, VFS, loopback TCP,
  instruction clock, pinned xoshiro256 PRNG), blocked outcome, run
  record with stdout/stderr/files
- CLI: --stdin, --vfs, --seed, --result-file, --profile (hosted: exit 3),
  exit code 7; runner: stdin/vfs/seed/stdout/stderr/file/blocked headers
- conformance: hello, file copy and TCP echo exit programs; 37 new tests;
  4000 mutants without a crash
This commit is contained in:
dev committed 2026-10-04 14:02:17 +03:00
1 parent 571cc6e362
commit d405d4ea50
49 files changed
+2325 -81

No files matched your search

+227 -5
View File
@@ -11,6 +11,9 @@
const std = @import("std");
const air = @import("../air.zig");
const diag = @import("../diag.zig");
const world_mod = @import("world.zig");
pub const WorldOptions = world_mod.Options;
pub const call_depth_limit = 1024;
@@ -30,6 +33,8 @@ pub const Value = union(enum) {
/// `cap<K>`: index into the host's authority table. Never observable
/// by the program (spec 05 §10.1).
cap: u32,
/// Linear resource: index into the world's handle table.
resource: u32,
/// Value of a built-in enum such as `cap_error`.
builtin: struct { which: air.authority.Builtin, variant: u32 },
@@ -64,8 +69,13 @@ pub const Outcome = union(enum) {
limit_exceeded: struct { limit: u64, steps: u64 },
/// The host did not start the program (spec 05 §10.2). Not a trap.
not_instantiated: NotInstantiated,
/// The deterministic runtime found no future event that could complete
/// a wait (spec 11 §8). Not a trap and not an I/O error.
blocked: Location,
};
pub const Location = struct { function: []const u8, block: []const u8, inst: u32 };
pub const NotInstantiated = struct {
reason: []const u8,
parameter: []const u8,
@@ -89,6 +99,18 @@ pub const Options = struct {
fuel: ?u64 = null,
/// Capability grants for the parameters of the entry function.
grants: []const Grant = &.{},
/// Inputs of the deterministic world (spec 11 §8).
world: WorldOptions = .{},
/// Receives the run's observable output.
output: ?*Output = null,
};
/// Observable output of a run in the deterministic profile.
pub const Output = struct {
stdout: []const u8,
stderr: []const u8,
/// Files written during the run, sorted by path.
files: []const struct { []const u8, []const u8 },
};
pub const Error = std.mem.Allocator.Error || error{ EntryNotFound, DuplicateGrant };
@@ -99,7 +121,10 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
const idx = module.functionIndex(entry) orelse return error.EntryNotFound;
const f = module.functions[idx];
for (f.params) |p| if (p.ty != .cap) return error.EntryNotFound;
var m: Machine = .{ .arena = arena, .module = module, .fuel = options.fuel };
var m: Machine = .{ .arena = arena, .module = module, .fuel = options.fuel, .world = try .init(arena, options.world) };
defer if (options.output) |o| {
o.* = m.output() catch .{ .stdout = "", .stderr = "", .files = &.{} };
};
// Instantiation (spec 05 §10.2): every capability parameter gets exactly
// one grant of its kind, and every grant names a parameter.
@@ -129,6 +154,7 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
.value => |v| .{ .returned = v },
.trap => |t| .{ .trapped = t },
.limit_exceeded => .{ .limit_exceeded = .{ .limit = m.fuel.?, .steps = m.steps } },
.blocked => |l| .{ .blocked = l },
};
}
@@ -168,7 +194,7 @@ fn kindOf(e: TrapError) TrapKind {
};
}
const CallResult = union(enum) { value: Value, trap: Trap, limit_exceeded };
const CallResult = union(enum) { value: Value, trap: Trap, limit_exceeded, blocked: Location };
const Machine = struct {
arena: std.mem.Allocator,
@@ -177,6 +203,7 @@ const Machine = struct {
fuel: ?u64,
/// Host authority table; capabilities index into it.
authorities: std.ArrayList(Authority) = .empty,
world: world_mod.World,
/// Instructions executed so far.
steps: u64 = 0,
@@ -211,6 +238,8 @@ const Machine = struct {
} },
.nested_trap => |t| return .{ .trap = t },
.limit_exceeded => return .limit_exceeded,
.blocked => return .{ .blocked = .{ .function = f.name, .block = b.name, .inst = @intCast(ii) } },
.nested_blocked => |l| return .{ .blocked = l },
}
} else unreachable; // verified blocks end with a terminator
}
@@ -224,6 +253,8 @@ const Machine = struct {
/// A trap raised inside a callee, already located.
nested_trap: Trap,
limit_exceeded,
blocked,
nested_blocked: Location,
};
fn exec(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) std.mem.Allocator.Error!Step {
@@ -291,6 +322,7 @@ const Machine = struct {
},
.trap => |t| return .{ .nested_trap = t },
.limit_exceeded => return .limit_exceeded,
.blocked => |l| return .{ .nested_blocked = l },
}
},
.br => |t| return m.jump(f, vals, t),
@@ -314,7 +346,8 @@ const Machine = struct {
},
// No narrowing form is registered yet, so verified AIR contains
// no reachable cap.narrow (spec 05 §10.4; forms arrive with RFC 0007/0008).
.cap_narrow => unreachable,
.cap_narrow => |x| return m.narrow(f, vals, x),
.intrinsic => |x| return m.intrinsic(f, vals, inst, x),
.ret => |v| return .{ .ret = if (v) |x| vals[x] else .void },
.trap => return .{ .trap = .explicit },
.local_alloc, .local_store, .local_zero, .local_load, .borrow_ref, .borrow_mut, .borrow_field, .borrow_end, .load, .store, .array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split, .slice_copy, .guard => return m.execMemory(vals, inst),
@@ -388,6 +421,143 @@ const Machine = struct {
};
}
// ------------------------------------------------------------ authority and I/O (spec 05 §10–§11, spec 06 §6)
fn output(m: *Machine) !Output {
const keys = try m.arena.dupe([]const u8, m.world.written.keys());
std.mem.sort([]const u8, keys, {}, struct {
fn lt(_: void, a: []const u8, b: []const u8) bool {
return std.mem.lessThan(u8, a, b);
}
}.lt);
const files = try m.arena.alloc(struct { []const u8, []const u8 }, keys.len);
for (keys, files) |k, *out| out.* = .{ k, m.world.files.get(k).?.items };
return .{ .stdout = m.world.stdout.items, .stderr = m.world.stderr.items, .files = files };
}
/// Bytes of a `slice<u8>` value.
fn bytesOf(m: *Machine, v: Value) ![]u8 {
const s = v.slice;
const items = placePtr(s.place).array[s.start..][0..s.len];
const out = try m.arena.alloc(u8, items.len);
for (items, out) |x, *o| o.* = @truncate(x.int.bits);
return out;
}
/// Writes `bytes` into the start of a `slice_mut<u8>` value.
fn fillSlice(v: Value, bytes: []const u8) void {
const s = v.slice;
const items = placePtr(s.place).array[s.start..][0..s.len];
for (bytes, items[0..bytes.len]) |b, *x| x.* = .{ .int = .{ .ty = .u8, .bits = b } };
}
fn resourceOf(v: Value) u32 {
return switch (v) {
.resource => |hd| hd,
.place => |p| p.cell.value.resource,
else => unreachable,
};
}
fn narrow(m: *Machine, f: air.Function, vals: []Value, x: @FieldType(air.Op, "cap_narrow")) !Step {
const a = m.authorities.items[vals[x.cap].cap];
// Only `prefix` is registered (reference/capabilities.md).
const path = try m.bytesOf(vals[x.args[0]]);
const reason: ?u32 = if (!world_mod.World.validPath(path)) 0 else if (!world_mod.World.within(a.scope, path)) 1 else null;
if (reason) |r| {
vals[f.blocks[x.err].params[0].value] = .{ .builtin = .{ .which = .cap_error, .variant = r } };
return .{ .jump = x.err };
}
try m.authorities.append(m.arena, .{ .kind = a.kind, .scope = path });
vals[f.blocks[x.ok].params[0].value] = .{ .cap = @intCast(m.authorities.items.len - 1) };
return .{ .jump = x.ok };
}
fn intrinsic(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst, x: @FieldType(air.Op, "intrinsic")) !Step {
const name = air.authority.intrinsics[x.index].name;
const arg = struct {
fn at(v: []Value, xx: @FieldType(air.Op, "intrinsic"), i: usize) Value {
return v[xx.args[i]];
}
}.at;
const W = world_mod.World;
var results: [1]Value = undefined;
var n_results: usize = 0;
var failure: ?world_mod.Error = null;
const is = struct {
fn eq(a: []const u8, b: []const u8) bool {
return std.mem.eql(u8, a, b);
}
}.eq;
if (is(name, "clock.monotonic")) {
return bind(vals, inst.result, .{ .int = .{ .ty = .u64, .bits = m.steps } });
} else if (is(name, "random.fill")) {
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
m.world.fill(buf);
fillSlice(arg(vals, x, 1), buf);
return .next;
} else if (is(name, "io.stdout_write") or is(name, "io.stderr_write")) {
try m.world.writeOut(is(name, "io.stderr_write"), try m.bytesOf(arg(vals, x, 1)));
} else if (is(name, "io.stdin_read")) {
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
const n = m.world.readIn(buf);
fillSlice(arg(vals, x, 1), buf[0..n]);
results[0] = .{ .int = .{ .ty = .usize, .bits = n } };
n_results = 1;
} else if (is(name, "fs.open_read") or is(name, "fs.create") or is(name, "fs.open_append")) {
const scope = m.authorities.items[arg(vals, x, 0).cap].scope;
const mode: air.authority.Resource = if (is(name, "fs.open_read")) .file_read else if (is(name, "fs.create")) .file_write else .file_append;
switch (try m.world.open(scope, try m.bytesOf(arg(vals, x, 1)), mode)) {
.ok => |hd| {
results[0] = .{ .resource = hd };
n_results = 1;
},
.err => |e| failure = e,
}
} else if (is(name, "fs.read")) {
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
const n = m.world.fileRead(resourceOf(arg(vals, x, 0)), buf);
fillSlice(arg(vals, x, 1), buf[0..n]);
results[0] = .{ .int = .{ .ty = .usize, .bits = n } };
n_results = 1;
} else if (is(name, "fs.write_all")) {
try m.world.fileWrite(resourceOf(arg(vals, x, 0)), try m.bytesOf(arg(vals, x, 1)));
} else if (is(name, "fs.sync")) {
// Durable by construction in the in-memory file system.
} else if (is(name, "fs.close") or is(name, "net.close_stream") or is(name, "net.close_listener")) {
m.world.close(arg(vals, x, 0).resource);
} else if (is(name, "net.listen") or is(name, "net.connect")) {
const addr = try m.bytesOf(arg(vals, x, 1));
switch (if (is(name, "net.listen")) try m.world.listen(addr) else try m.world.connect(addr)) {
.ok => |hd| {
results[0] = .{ .resource = hd };
n_results = 1;
},
.err => |e| failure = e,
}
} else if (is(name, "net.accept")) {
const s = m.world.accept(resourceOf(arg(vals, x, 0))) orelse return .blocked;
results[0] = .{ .resource = s };
n_results = 1;
} else if (is(name, "net.recv")) {
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
const n = m.world.recv(resourceOf(arg(vals, x, 0)), buf) orelse return .blocked;
fillSlice(arg(vals, x, 1), buf[0..n]);
results[0] = .{ .int = .{ .ty = .usize, .bits = n } };
n_results = 1;
} else if (is(name, "net.send_all")) {
failure = try m.world.send(resourceOf(arg(vals, x, 0)), try m.bytesOf(arg(vals, x, 1)));
} else unreachable; // every registered intrinsic is handled above
_ = W;
if (failure) |e| {
vals[f.blocks[x.err.?].params[0].value] = .{ .builtin = .{ .which = .io_error, .variant = @backingInt(e) } };
return .{ .jump = x.err.? };
}
for (f.blocks[x.ok.?].params, results[0..n_results]) |p, r| vals[p.value] = r;
return .{ .jump = x.ok.? };
}
fn usize_(v: Value) u64 {
return @truncate(v.int.bits);
}
@@ -411,6 +581,12 @@ const Machine = struct {
.local_load => |v| return bind(vals, inst.result, try m.deepCopy(vals[v].local.value)),
.borrow_ref, .borrow_mut => |v| return bind(vals, inst.result, switch (vals[v]) {
.local => |c| .{ .place = .{ .cell = c, .path = &.{} } },
// A borrowed resource: a place whose cell holds the handle.
.resource => |hd| blk: {
const cell = try m.arena.create(Value.Cell);
cell.* = .{ .value = .{ .resource = hd }, .ty = .void };
break :blk .{ .place = .{ .cell = cell, .path = &.{} } };
},
else => |x| x,
}),
.borrow_field => |x| return bind(vals, inst.result, .{ .place = try m.extend(asPlace(vals[x.borrow]), x.field) }),
@@ -611,6 +787,7 @@ pub fn writeValue(module: air.Module, v: Value, s: *std.json.Stringify) std.Io.W
},
// Storage and borrows cannot be returned from `@main` (spec 08 §11.3).
.local, .place, .slice => try s.write(null),
.resource => try s.write(null),
// A capability is opaque: only its kind is shown, never its identity.
.cap => {
try s.beginObject();
@@ -653,8 +830,23 @@ pub fn writeValue(module: air.Module, v: Value, s: *std.json.Stringify) std.Io.W
}
}
/// Writes bytes as a JSON string: printable ASCII as is, every other byte
/// as `\u00XX`, so arbitrary output is valid, deterministic JSON.
fn writeBytes(w: *std.Io.Writer, bytes: []const u8) std.Io.Writer.Error!void {
try w.writeByte('"');
for (bytes) |b| switch (b) {
'"' => try w.writeAll("\\\""),
'\\' => try w.writeAll("\\\\"),
'\n' => try w.writeAll("\\n"),
0x20...0x21, 0x23...0x5b, 0x5d...0x7e => try w.writeByte(b),
else => try w.print("\\u{x:0>4}", .{b}),
};
try w.writeByte('"');
}
/// Writes the run record for `outcome` as one JSON object (no newline).
pub fn writeOutcome(module: air.Module, outcome: Outcome, w: *std.Io.Writer) std.Io.Writer.Error!void {
/// `output` is added for modules that declare `capabilities` (spec 07a).
pub fn writeOutcome(module: air.Module, outcome: Outcome, out: ?Output, w: *std.Io.Writer) std.Io.Writer.Error!void {
var s: std.json.Stringify = .{ .writer = w };
try s.beginObject();
try s.objectField("status");
@@ -677,6 +869,17 @@ pub fn writeOutcome(module: air.Module, outcome: Outcome, w: *std.Io.Writer) std
try s.objectField("inst");
try s.write(t.inst);
},
.blocked => |l| {
try s.write("blocked");
try s.objectField("kind");
try s.write("no_future_event");
try s.objectField("function");
try s.write(l.function);
try s.objectField("block");
try s.write(l.block);
try s.objectField("inst");
try s.write(l.inst);
},
.not_instantiated => |n| {
try s.write("not_instantiated");
try s.objectField("reason");
@@ -706,6 +909,25 @@ pub fn writeOutcome(module: air.Module, outcome: Outcome, w: *std.Io.Writer) std
try s.write(l.steps);
},
}
if (out) |o| if (module.declares("capabilities") and outcome != .not_instantiated) {
try s.objectField("stdout");
try s.beginWriteRaw();
try writeBytes(w, o.stdout);
s.endWriteRaw();
try s.objectField("stderr");
try s.beginWriteRaw();
try writeBytes(w, o.stderr);
s.endWriteRaw();
try s.objectField("files");
try s.beginObject();
for (o.files) |file| {
try s.objectField(file[0]);
try s.beginWriteRaw();
try writeBytes(w, file[1]);
s.endWriteRaw();
}
try s.endObject();
};
try s.endObject();
}
@@ -728,7 +950,7 @@ fn expectRunFuel(src: []const u8, expected: []const u8, fuel: ?u64) !void {
}
const outcome = try run(arena, report.module.?, "main", .{ .fuel = fuel });
var out: std.Io.Writer.Allocating = .init(arena);
try writeOutcome(report.module.?, outcome, &out.writer);
try writeOutcome(report.module.?, outcome, null, &out.writer);
try std.testing.expectEqualStrings(expected, out.written());
}
+242
View File
@@ -0,0 +1,242 @@
//! The `deterministic` execution profile (spec 11 §8): captured console,
//! in-memory file system, in-process loopback TCP, logical clock and a
//! seeded PRNG. Every result is a function of the run's inputs.
const std = @import("std");
const air = @import("../air.zig");
const IoError = enum(u32) {
not_found,
permission_denied,
already_exists,
invalid_input,
no_space,
broken_pipe,
connection_refused,
connection_reset,
address_in_use,
address_unavailable,
timed_out,
other,
};
comptime {
// Variant indices must match the built-in enum `io_error`.
for (air.authority.Builtin.io_error.variants(), 0..) |name, i| {
std.debug.assert(std.mem.eql(u8, @tagName(@as(IoError, @fromBackingInt(@intCast(i)))), name));
}
}
pub const Error = IoError;
/// Result of an operation that creates a resource.
pub const Opened = union(enum) { ok: u32, err: IoError };
/// An open resource. Indices are never reused within a run.
pub const Handle = union(enum) {
file: struct { path: []const u8, mode: air.authority.Resource, pos: usize },
listener: struct { addr: []const u8, pending: std.ArrayList(u32) = .empty },
stream: struct { peer: ?u32, inbox: std.ArrayList(u8) = .empty, read_pos: usize = 0, peer_closed: bool = false },
closed,
};
pub const Options = struct {
stdin: []const u8 = "",
/// Initial files: path -> contents.
files: []const struct { []const u8, []const u8 } = &.{},
seed: u64 = 0,
};
pub const World = struct {
arena: std.mem.Allocator,
stdout: std.ArrayList(u8) = .empty,
stderr: std.ArrayList(u8) = .empty,
stdin: []const u8,
stdin_pos: usize = 0,
files: std.StringArrayHashMapUnmanaged(std.ArrayList(u8)) = .empty,
written: std.StringArrayHashMapUnmanaged(void) = .empty,
handles: std.ArrayList(Handle) = .empty,
listeners: std.StringHashMapUnmanaged(u32) = .empty,
/// xoshiro256** seeded by SplitMix64 from `--seed` (spec 11 §8); pinned
/// explicitly so a toolchain upgrade cannot change deterministic output.
prng: std.Random.Xoshiro256,
pub fn init(arena: std.mem.Allocator, o: Options) !World {
var w: World = .{ .arena = arena, .stdin = o.stdin, .prng = .init(o.seed) };
for (o.files) |entry| {
var contents: std.ArrayList(u8) = .empty;
try contents.appendSlice(arena, entry[1]);
try w.files.put(arena, entry[0], contents);
}
return w;
}
fn add(w: *World, h: Handle) !u32 {
try w.handles.append(w.arena, h);
return @intCast(w.handles.items.len - 1);
}
// ------------------------------------------------------------ paths
/// Absolute, no empty, `.` or `..` components (reference/intrinsics.md).
pub fn validPath(path: []const u8) bool {
if (path.len == 0 or path[0] != '/') return false;
if (path.len == 1) return true;
var it = std.mem.splitScalar(u8, path[1..], '/');
while (it.next()) |part| {
if (part.len == 0 or std.mem.eql(u8, part, ".") or std.mem.eql(u8, part, "..")) return false;
}
return true;
}
/// Whether `path` lies within `scope` (null scope = whole file system).
pub fn within(scope: ?[]const u8, path: []const u8) bool {
const s = scope orelse return true;
if (std.mem.eql(u8, s, "/")) return true;
if (!std.mem.startsWith(u8, path, s)) return false;
return path.len == s.len or path[s.len] == '/';
}
// ------------------------------------------------------------ console
pub fn writeOut(w: *World, err_stream: bool, bytes: []const u8) !void {
try (if (err_stream) &w.stderr else &w.stdout).appendSlice(w.arena, bytes);
}
pub fn readIn(w: *World, buf: []u8) usize {
const n = @min(buf.len, w.stdin.len - w.stdin_pos);
@memcpy(buf[0..n], w.stdin[w.stdin_pos..][0..n]);
w.stdin_pos += n;
return n;
}
// ------------------------------------------------------------ files
pub fn open(w: *World, scope: ?[]const u8, path: []const u8, mode: air.authority.Resource) !Opened {
if (!validPath(path)) return .{ .err = .invalid_input };
if (!within(scope, path)) return .{ .err = .permission_denied };
const owned = try w.arena.dupe(u8, path);
switch (mode) {
.file_read => if (!w.files.contains(owned)) return .{ .err = .not_found },
.file_write => {
try w.files.put(w.arena, owned, .empty);
try w.written.put(w.arena, owned, {});
},
.file_append => {
if (!w.files.contains(owned)) try w.files.put(w.arena, owned, .empty);
try w.written.put(w.arena, owned, {});
},
else => unreachable,
}
return .{ .ok = try w.add(.{ .file = .{ .path = owned, .mode = mode, .pos = 0 } }) };
}
pub fn fileRead(w: *World, h: u32, buf: []u8) usize {
const f = &w.handles.items[h].file;
const data = w.files.get(f.path).?.items;
const n = @min(buf.len, data.len -| f.pos);
@memcpy(buf[0..n], data[f.pos..][0..n]);
f.pos += n;
return n;
}
pub fn fileWrite(w: *World, h: u32, bytes: []const u8) !void {
const f = &w.handles.items[h].file;
try w.files.getPtr(f.path).?.appendSlice(w.arena, bytes);
}
pub fn close(w: *World, h: u32) void {
switch (w.handles.items[h]) {
.stream => |s| if (s.peer) |p| switch (w.handles.items[p]) {
.stream => |*ps| ps.peer_closed = true,
else => {},
},
.listener => |l| _ = w.listeners.remove(l.addr),
else => {},
}
w.handles.items[h] = .closed;
}
// ------------------------------------------------------------ loopback TCP
/// `host:port` with a numeric IPv4 host.
pub fn validAddr(addr: []const u8) bool {
const colon = std.mem.lastIndexOfScalar(u8, addr, ':') orelse return false;
_ = std.fmt.parseInt(u16, addr[colon + 1 ..], 10) catch return false;
var it = std.mem.splitScalar(u8, addr[0..colon], '.');
var n: usize = 0;
while (it.next()) |part| : (n += 1) {
_ = std.fmt.parseInt(u8, part, 10) catch return false;
}
return n == 4;
}
pub fn listen(w: *World, addr: []const u8) !Opened {
if (!validAddr(addr)) return .{ .err = .invalid_input };
const owned = try w.arena.dupe(u8, addr);
if (w.listeners.contains(owned)) return .{ .err = .address_in_use };
const h = try w.add(.{ .listener = .{ .addr = owned } });
try w.listeners.put(w.arena, owned, h);
return .{ .ok = h };
}
pub fn connect(w: *World, addr: []const u8) !Opened {
if (!validAddr(addr)) return .{ .err = .invalid_input };
const l = w.listeners.get(addr) orelse return .{ .err = .connection_refused };
const client = try w.add(.{ .stream = .{ .peer = null } });
const server = try w.add(.{ .stream = .{ .peer = client } });
w.handles.items[client].stream.peer = server;
try w.handles.items[l].listener.pending.append(w.arena, server);
return .{ .ok = client };
}
/// Null: nothing to accept, and nothing else can ever connect (the run
/// has a single execution unit): the caller reports `blocked`.
pub fn accept(w: *World, h: u32) ?u32 {
const l = &w.handles.items[h].listener;
if (l.pending.items.len == 0) return null;
return l.pending.orderedRemove(0);
}
pub fn send(w: *World, h: u32, bytes: []const u8) !?IoError {
const s = w.handles.items[h].stream;
if (s.peer_closed) return .broken_pipe;
const p = s.peer orelse return .broken_pipe;
try w.handles.items[p].stream.inbox.appendSlice(w.arena, bytes);
return null;
}
/// Null: no data and the peer is open; nothing else can ever send, so
/// the caller reports `blocked`.
pub fn recv(w: *World, h: u32, buf: []u8) ?usize {
const s = &w.handles.items[h].stream;
const avail = s.inbox.items.len - s.read_pos;
if (avail == 0) return if (s.peer_closed) 0 else null;
const n = @min(buf.len, avail);
@memcpy(buf[0..n], s.inbox.items[s.read_pos..][0..n]);
s.read_pos += n;
return n;
}
// ------------------------------------------------------------ random
pub fn fill(w: *World, buf: []u8) void {
w.prng.random().bytes(buf);
}
};
test "paths and scopes" {
try std.testing.expect(World.validPath("/data/a.txt"));
try std.testing.expect(!World.validPath("data/a.txt"));
try std.testing.expect(!World.validPath("/data/../etc"));
try std.testing.expect(!World.validPath("/data//a"));
try std.testing.expect(World.within("/data", "/data/a"));
try std.testing.expect(!World.within("/data", "/database"));
try std.testing.expect(World.within(null, "/x"));
}
test "addresses" {
try std.testing.expect(World.validAddr("127.0.0.1:8080"));
try std.testing.expect(!World.validAddr("localhost:80"));
try std.testing.expect(!World.validAddr("127.0.0.1:99999"));
}