summaryrefslogtreecommitdiff
path: root/core/walk.zig
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-24 02:56:05 -0300
committerGabriel Schneider <[email protected]>2026-11-24 04:15:45 -0300
commit2645734806155dac927967289b0f11683eb3a1d0 (patch)
tree069a7d03c2e481d2c232cd26b53ee122a6c09be3 /core/walk.zig
parentf0f2a5125fd4b034ebcd424afd4a55c3185191ab (diff)
downloadpardes-2645734806155dac927967289b0f11683eb3a1d0.tar.gz
pardes-2645734806155dac927967289b0f11683eb3a1d0.zip
walk: a loaded index is held to what it names, and a place to its thing, by a declaration beside the field, read by the comptime walk and checked where `pastHeld` is (the end of a struct's fields in all three decoders: a tape's `decode`, a byte dump's `Loader.fields`, an image's `Get.fields`, through `holdTo`): `replica.index` says what a field names (a field's slots, a predicate's things, or, with a third word, the things of the struct holding it, held where ITS fields end over every value of the type it holds (`heldIn`, `visit`); a fourth word: a span counted from it), and one that names none is REFUSED, the field named, in the words `fromDump` and a Restore say (`Core.live says 9, which names none of Core.openViews: refused`); `replica.place` gives a field's last place (or its first and last) and one past it is that place (the session is there, its view a line off); `replica.left_out` is what a load that left a thing out (another build's pane) does to what named it before the indexes are held (`Pardes.dropMissing`, now every view's); a field that names a slot by its type (`Pane.Id`, `View.Id`) with no declaration is a compile error (`checkSlots`). RUN FIRST, each the dump fuzz with every loaded core drawn at its size, 40x12 and 200x60 and given keys and a wheel notch (core/fuzz.zig `use`), each a panic or an allocation past the fuzz's cap on the tree before: join seed 1761, `Pardes.multi_count` read as 2^30 sized a yank's register array at 17 GB (`d`, Registers.put): a step's own, now not dumped, with `multi_*`, `exec_depth`, `exec_column` (root.zig `kept_out`); join 3682, `File.State.scroll` past its text: `@intCast` into `wrap_line` (File.zig fillBody): clamped to its last line (`lastLine`; a slim dump's file, read again at its revival, to its saved bytes' lines), `scroll_row` to the top line's bytes; join 77, `Messages.head` past its ring (logMessage): clamped (`head`, `len`); restore 1211, `View.screen_h` 0, drawn (draw.zig paintHeaders: surface.zig `at`), and join 24086/28218 a screen sizing a 111 GB frame: a view's screen side is a grid a frontend sizes or the dump is refused: a cell at least (a zero refused, not clamped, as abi/wire.zig `getCols` refuses one), at most 4096 (`View.max_grid`: past any display's; the wire's 512x128 is a client's, and a session's own frontend is wider: a replica test's view is 500 rows); join 14189, `Pane.tag_lead` past i32 (Core.sync): held to the room its prefix is made in (`Pane.prefix_room`); join 18926, an undo's `Journal.done` past its steps (Text.zig `mark`): clamped, `Step.first..n` a span of the journal's entries (refused past them), and join 35489 `Journal.bytes` overflowing (`record`): held to what its entries hold. And a bitset a load made is freed with the rest when the load fails or what held it is let go (`Bits`, on `customs`): the 40,000-seed run's leak (16 KB, `Loader.value` `.bitset`), reached once a refusal came after one was read. Declared beside them, by the brief and by reading: `Pardes.live` (an open view), `theme_file_pane`; `View.active` (a pane there, or any slot in a window with none), `window_pick`, `kind_grab`, `kind_hover`; `Column.panes` (panes there, held as far as `n` now says: a `len` pair, so a digest and a dump take that far); `Pane.sized_by`, `prompt_view`, `search_pane`; `Jump.cur` (place), `Jump.Loc.pane`; the language server's awaited `pane`. TESTS (each site was a failing run first, above): walk.zig "an index read back that names none of its things is refused, its field named, in a tape, a dump and an image; a place past its thing's last is that last", "a thing another build's dump left out takes what named it with it (`left_out`), before the indexes are held"; dump.zig "a dump whose index names no view or pane there is refused, the field named; a top past its text is its last line; a key's replay is not dumped"
Co-Authored-By: Claude Opus <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'core/walk.zig')
-rw-r--r--core/walk.zig445
1 files changed, 427 insertions, 18 deletions
diff --git a/core/walk.zig b/core/walk.zig
index f6a9c088..25e4bdc3 100644
--- a/core/walk.zig
+++ b/core/walk.zig
@@ -259,14 +259,255 @@ fn pastHeld(comptime T: type, v: *const T, held: ?*const [pairs(T)]usize) ?Past
return null;
}
-/// Every name an annotation gives is a field: a rename cannot quietly put
-/// a field back in the digest.
+// ---- an index read back is held to what it names ----
+//
+// A field that NAMES one of the things a session holds (a view by its slot,
+// a pane by its) says what, beside it, as a length says its buffer; a field
+// that says WHERE in a thing it is (a scroll, a row), the thing's last place:
+//
+// pub const replica = .{
+// // One of the slots field `views` has (as many as it holds), or one
+// // a predicate of the struct says is there (`fn (*const T, usize)
+// // bool`); a third word, one of the things of the struct named
+// // second that holds this one (held where ITS fields end, every
+// // value of this type it holds); a fourth, the field counting a
+// // span of them from it (all within the field named third).
+// .index = .{ .{ "sized_by", Pardes, "views" }, .{ "live", "openViews" }, .{ "first", Journal, "entries", "n" } },
+// // Its last place, a function of the struct (`fn (*const T) usize`),
+// // or its first and last (`[2]usize`).
+// .place = .{ .{ "scroll", "lastLine" } },
+// // What a load that left one of its things out (another build's
+// // pane) does to what names it (`fn (*T) void`), before its indexes
+// // are held.
+// .left_out = "dropMissing",
+// };
+//
+// A value read back (a tape, a dump, an image: bytes from another process or
+// the disk) is held to them where its fields end, beside its lengths
+// (`pastHeld`), every declaration of every type at once: an index that names
+// none is REFUSED, its field named (the dump is not the session: the view,
+// the pane it names is not there); a place past its thing's last is that
+// LAST (the session is there, its view a line off). A field that names a
+// slot by its type (`Pane.Id`, `View.Id`) and says nothing is a compile
+// error (`checkSlots`); a bare integer that does is found by reading, as
+// the lengths' were, until it is typed as its slot.
+
+fn declared(comptime T: type, comptime kind: []const u8) usize {
+ return if (@hasDecl(T, "replica") and @hasField(@TypeOf(T.replica), kind)) @field(T.replica, kind).len else 0;
+}
+
+/// An index read back that names none of what it says it indexes.
+const Unnamed = struct { holder: []const u8, name: []const u8, says: usize, of: []const u8 };
+
+/// What an index field says, as a number: an integer, an optional one's (null
+/// names nothing), a slot's enum's (`Pane.Id`).
+fn number(comptime F: type, v: F) ?usize {
+ return switch (@typeInfo(F)) {
+ .int => std.math.cast(usize, v) orelse std.math.maxInt(usize),
+ .optional => |o| if (v) |x| number(o.child, x) else null,
+ .@"enum" => |e| number(e.tag_type, @backingInt(v)),
+ else => @compileError("walk: an `index` names a thing by a number, not " ++ @typeName(F)),
+ };
+}
+
+/// How many of field `name`'s elements `v` holds: as far as its length says.
+fn heldOf(comptime T: type, v: *const T, comptime name: []const u8) usize {
+ const all = &@field(v, name);
+ if (comptime isList(@TypeOf(all.*))) return all.items.len;
+ return if (comptime lengthOf(T, name)) |len| @min(lengthIn(v, len), all.len) else all.len;
+}
+
+/// Whether `h` has the thing `i` names by `what`: a field of it (one of its
+/// slots), or a predicate of it.
+fn hasThing(comptime H: type, h: *const H, comptime what: []const u8, i: usize) bool {
+ if (comptime @hasField(H, what)) {
+ return i < heldOf(H, h, what);
+ } else return @field(H, what)(h, i);
+}
+
+/// The first number field `name` of `u` says (each of an array as far as its
+/// length says) that names no thing of `h`'s by `what`.
+fn firstUnnamed(comptime U: type, u: *const U, comptime name: []const u8, comptime H: type, h: *const H, comptime what: []const u8) ?usize {
+ const F = @FieldType(U, name);
+ if (comptime @typeInfo(F) == .array) {
+ for (@field(u, name)[0..heldOf(U, u, name)]) |e| if (number(@typeInfo(F).array.child, e)) |i| if (!hasThing(H, h, what, i)) return i;
+ return null;
+ }
+ const i = number(F, @field(u, name)) orelse return null;
+ return if (hasThing(H, h, what, i)) null else i;
+}
+
+/// `at` held to `[first, last]`: a place past its thing's last is that last.
+fn clampTo(comptime F: type, at: *F, first: usize, last: usize) void {
+ switch (@typeInfo(F)) {
+ .int => if (at.* > last) {
+ at.* = @intCast(last);
+ } else if (at.* < first) {
+ at.* = @intCast(first);
+ },
+ .optional => |o| if (at.*) |*x| clampTo(o.child, x, first, last),
+ else => @compileError("walk: a `place` is a number, not " ++ @typeName(F)),
+ }
+}
+
+/// The types `T`'s value holds whose indexes name `T`'s things (a third word
+/// `T`): held where `T`'s fields end.
+fn heldIn(comptime T: type) []const type {
+ comptime {
+ if (!@hasDecl(T, "replica")) return &.{};
+ var out: []const type = &.{};
+ for (graph(&.{T})) |U| if (@typeInfo(U) == .@"struct") for (0..declared(U, "index")) |k| {
+ const d = U.replica.index[k];
+ if (d.len >= 3) if (d[1] == T) {
+ out = out ++ .{U};
+ break;
+ };
+ };
+ return out;
+ }
+}
+
+/// Whether a value of `X` can hold a `U`, as a dump walks it.
+fn reaches(comptime X: type, comptime U: type) bool {
+ comptime {
+ @setEvalBranchQuota(100_000_000);
+ return switch (kindOf(Canon(X))) {
+ .@"struct", .optional, .one, .slice, .array, .@"union" => for (graph(&.{Canon(X)})) |Y| {
+ if (Y == U) break true;
+ } else false,
+ else => false,
+ };
+ }
+}
+
+/// `v`'s places held to their things' last, then the first of its indexes,
+/// and of every value it holds whose indexes name its things, that names
+/// none (see above).
+fn heldIndexes(comptime T: type, v: *T) ?Unnamed {
+ inline for (0..comptime declared(T, "place")) |k| {
+ const d = T.replica.place[k];
+ const held = @field(T, d[1])(v);
+ const span: [2]usize = if (@TypeOf(held) == usize) .{ 0, held } else held;
+ clampTo(@FieldType(T, d[0]), &@field(v, d[0]), span[0], span[1]);
+ }
+ inline for (0..comptime declared(T, "index")) |k| {
+ const d = T.replica.index[k];
+ if (comptime d.len == 2) if (firstUnnamed(T, v, d[0], T, v, d[1])) |i|
+ return .{ .holder = @typeName(T), .name = d[0], .says = i, .of = @typeName(T) ++ "." ++ d[1] };
+ }
+ inline for (comptime heldIn(T)) |U| if (visit(T, v, U, T, v, 0)) |bad| return bad;
+ return null;
+}
+
+/// Every `U` that `x` holds (its fields as a dump walks them, as far as each
+/// length says; optionals, arrays, slices, lists, unions and pointers
+/// followed), its indexes into `h`'s things held; the first that names none.
+/// A value nested past `max_depth` (a pointer that is its own holder: a
+/// damaged dump's) is refused too.
+fn visit(comptime X: type, x: *const X, comptime U: type, comptime H: type, h: *const H, depth: u16) ?Unnamed {
+ if (comptime !reaches(X, U)) return null;
+ if (depth == max_depth) return .{ .holder = @typeName(X), .name = "", .says = depth, .of = "a depth a session's values nest to" };
+ if (X == U) inline for (0..comptime declared(U, "index")) |k| {
+ const d = U.replica.index[k];
+ if (comptime d.len >= 3) if (comptime d[1] == H) {
+ const of = @typeName(H) ++ "." ++ d[2];
+ if (comptime d.len == 3) {
+ if (firstUnnamed(U, x, d[0], H, h, d[2])) |i| return .{ .holder = @typeName(U), .name = d[0], .says = i, .of = of };
+ } else {
+ // A span: as many as its count says from it, all there (an
+ // empty one may stand at their end).
+ const end = @as(usize, @field(x, d[0])) +| @field(x, d[3]);
+ if (end > heldOf(H, h, d[2])) return .{ .holder = @typeName(U), .name = d[0], .says = @field(x, d[0]), .of = of };
+ }
+ };
+ };
+ switch (@typeInfo(X)) {
+ .optional => |o| if (x.*) |*c| return visit(o.child, c, U, H, h, depth + 1),
+ .array => |a| for (x) |*e| if (visit(a.child, e, U, H, h, depth + 1)) |bad| return bad,
+ .pointer => |p| switch (p.size) {
+ .one => return visit(p.child, x.*, U, H, h, depth + 1),
+ .slice => for (x.*) |*e| if (visit(p.child, e, U, H, h, depth + 1)) |bad| return bad,
+ else => {},
+ },
+ .@"struct" => {
+ if (comptime isAtomic(X)) return visit(@FieldType(X, "raw"), &x.raw, U, H, h, depth + 1);
+ if (comptime isList(X)) return visit(@FieldType(X, "items"), &x.items, U, H, h, depth + 1);
+ inline for (comptime dumpFields(X)) |name| {
+ const F = @FieldType(X, name);
+ if (comptime reaches(F, U)) {
+ if (comptime lengthOf(X, name) != null) {
+ for (@field(x, name)[0..heldOf(X, x, name)]) |*e| if (visit(Element(F), e, U, H, h, depth + 1)) |bad| return bad;
+ } else if (visit(F, &@field(x, name), U, H, h, depth + 1)) |bad| return bad;
+ }
+ }
+ },
+ .@"union" => switch (x.*) {
+ inline else => |*payload| return visit(@TypeOf(payload.*), payload, U, H, h, depth + 1),
+ },
+ else => {},
+ }
+ return null;
+}
+
+/// `out`'s lengths held to what their buffers hold as read (`pastHeld`), and
+/// its indexes to what they name (`heldIndexes`), where a reader (`Loader`,
+/// `Get`) has read its fields: the dump refused, the field named. One that
+/// left a thing out since `dropped` (another build's pane) first has `T`'s
+/// `left_out` take out what names it.
+fn holdTo(l: anytype, comptime T: type, out: *T, held: *const [pairs(T)]usize, dropped: usize) error{BadDump}!void {
+ if (pastHeld(T, out, held)) |past| {
+ l.note("{s}.{s} says {d}, past the {d} its buffer holds: refused", .{ @typeName(T), past.name, past.says, past.holds });
+ return error.BadDump;
+ }
+ if (comptime @hasDecl(T, "replica")) if (comptime @hasField(@TypeOf(T.replica), "left_out")) if (l.dropped != dropped) @field(T, T.replica.left_out)(out);
+ if (heldIndexes(T, out)) |bad| {
+ l.note("{s}.{s} says {d}, which names none of {s}: refused", .{ bad.holder, bad.name, bad.says, bad.of });
+ return error.BadDump;
+ }
+}
+
+/// A slot's type (`Pane.Id`, `View.Id`: an enum that is `at` a slot and
+/// gives its `index`), bare, optional or in an array.
+fn isSlot(comptime F: type) bool {
+ return switch (@typeInfo(F)) {
+ .optional => |o| isSlot(o.child),
+ .array => |a| isSlot(a.child),
+ .@"enum" => @hasDecl(F, "at") and @hasDecl(F, "index"),
+ else => false,
+ };
+}
+
+/// A field a dump carries that names a slot by its type says what it
+/// indexes (`.index`): a compile error otherwise, so that one added later
+/// is held where it is read back.
+fn checkSlots(comptime T: type) void {
+ for (dumpFields(T)) |name| if (isSlot(@FieldType(T, name))) {
+ for (0..declared(T, "index")) |k| {
+ if (std.mem.eql(u8, T.replica.index[k][0], name)) break;
+ } else @compileError("walk: " ++ @typeName(T) ++ "." ++ name ++ " names a slot: say what it indexes (`replica.index`)");
+ };
+}
+
+/// Every name an annotation gives is a field (and what an index or a place
+/// says it is held to, a field or a function): a rename cannot quietly put a
+/// field back in the digest, nor take one out of its rule.
fn checkAnnotations(comptime T: type) void {
if (!@hasDecl(T, "replica")) return;
inline for (@typeInfo(@TypeOf(T.replica)).@"struct".field_names) |kind| {
+ if (comptime std.mem.eql(u8, kind, "left_out")) {
+ if (!@hasDecl(T, T.replica.left_out)) @compileError("walk: " ++ @typeName(T) ++ " has no " ++ T.replica.left_out ++ " for what a load left out");
+ continue;
+ }
inline for (@field(T.replica, kind)) |entry| {
- const name = if (comptime std.mem.eql(u8, kind, "len") or std.mem.eql(u8, kind, "alloc")) entry[0] else entry;
+ const pair = comptime std.mem.eql(u8, kind, "len") or std.mem.eql(u8, kind, "alloc") or std.mem.eql(u8, kind, "index") or std.mem.eql(u8, kind, "place");
+ const name = if (pair) entry[0] else entry;
if (!@hasField(T, name)) @compileError("walk: " ++ @typeName(T) ++ " annotates no field " ++ name);
+ if (comptime std.mem.eql(u8, kind, "index") or std.mem.eql(u8, kind, "place")) {
+ const H = if (entry.len >= 3) entry[1] else T;
+ const what = if (entry.len >= 3) entry[2] else entry[1];
+ if (entry.len == 4) if (!@hasField(T, entry[3])) @compileError("walk: " ++ @typeName(T) ++ " counts its span by no field " ++ entry[3]);
+ if (!@hasField(H, what) and !@hasDecl(H, what)) @compileError("walk: " ++ @typeName(T) ++ "." ++ name ++ " is held to " ++ what ++ ", which " ++ @typeName(H) ++ " has not");
+ }
}
}
}
@@ -634,7 +875,7 @@ pub fn decode(comptime T: type, r: *Reader, a: std.mem.Allocator) TapeError!T {
try decodeError(F, r, &@field(out, name));
} else @field(out, name) = try decode(F, r, a);
}
- if (pastHeld(T, &out, null) != null) return error.BadTape;
+ if (pastHeld(T, &out, null) != null or heldIndexes(T, &out) != null) return error.BadTape;
return out;
},
.@"union" => |u| {
@@ -818,7 +1059,10 @@ fn collect(comptime T: type, comptime list: []const type) []const type {
comptime {
for (list) |U| if (U == T) return list;
var out: []const type = list ++ .{T};
- if (kindOf(T) == .@"struct") checkAnnotations(T);
+ if (kindOf(T) == .@"struct") {
+ checkAnnotations(T);
+ checkSlots(T);
+ }
for (children(T)) |C| out = collect(C, out);
return out;
}
@@ -1205,6 +1449,8 @@ pub const Loader = struct {
filled: usize = 0,
/// How deep `skip` is in the dump's own types.
depth: u16 = 0,
+ /// How many things (a session's panes) it left out (`holdTo`).
+ dropped: usize = 0,
pub fn init(gpa: std.mem.Allocator, bytes: []const u8, table: []const u8) DecodeError!Self {
var l: Self = .{ .gpa = gpa, .own = gpa, .bytes = bytes, .arena = .init(gpa) };
@@ -1550,6 +1796,10 @@ pub const Loader = struct {
.bitset => {
const bits = try l.bitCount();
out.* = try .initEmpty(l.gpa, bits);
+ l.customs.append(l.own, .{ .ptr = out, .gpa = l.gpa, .free = @ptrCast(&Bits(T).free) }) catch |err| {
+ out.deinit(l.gpa);
+ return err;
+ };
const words = (bits + @bitSizeOf(usize) - 1) / @bitSizeOf(usize);
if (words > 0) @memcpy(std.mem.sliceAsBytes(out.masks[0..words]), try l.take(words * @sizeOf(usize)));
},
@@ -1618,6 +1868,7 @@ pub const Loader = struct {
if (droppable) {
l.letGo(before);
out[i] = null;
+ l.dropped += 1;
l.note("{s}[{d}] left out", .{ l.field, i });
} else failed = true;
};
@@ -1630,6 +1881,7 @@ pub const Loader = struct {
const packed_struct = comptime @typeInfo(T).@"struct".layout == .@"packed";
const outer = l.field;
defer l.field = outer;
+ const dropped = l.dropped;
// How far each array a length cuts was read: none yet (one read in
// place holds what it held).
var held: [pairs(T)]usize = @splat(if (existing) std.math.maxInt(usize) else 0);
@@ -1640,7 +1892,7 @@ pub const Loader = struct {
try l.oneField(T, field, s.fields[k].ty, out, packed_struct, existing);
if (comptime pairAt(T, field)) |i| held[i] = l.filled;
}
- return l.heldTo(T, out, &held);
+ return holdTo(l, T, out, &held, dropped);
}
var found: std.StaticBitSet(@max(1, names.len)) = .empty;
var failed = false;
@@ -1684,15 +1936,7 @@ pub const Loader = struct {
}
};
if (failed) return error.Incompatible;
- return l.heldTo(T, out, &held);
- }
-
- /// `out`'s lengths held to what their buffers hold as read (`pastHeld`):
- /// the dump refused, the length named.
- fn heldTo(l: *Self, comptime T: type, out: *const T, held: *const [pairs(T)]usize) DecodeError!void {
- const past = pastHeld(T, out, held) orelse return;
- l.note("{s}.{s} says {d}, past the {d} its buffer holds: refused", .{ @typeName(T), past.name, past.says, past.holds });
- return error.BadDump;
+ return holdTo(l, T, out, &held, dropped);
}
fn oneField(l: *Self, comptime T: type, comptime field: []const u8, ty: u32, out: *T, comptime packed_struct: bool, existing: bool) DecodeError!void {
@@ -1779,6 +2023,16 @@ pub const Loader = struct {
}
};
+/// A bitset a load made, freed as a `dumpRead`'s value is (`customs`) when
+/// the load fails or what held it is let go: its words are no `made` slice.
+fn Bits(comptime T: type) type {
+ return struct {
+ fn free(b: *T, gpa: std.mem.Allocator) void {
+ b.deinit(gpa);
+ }
+ };
+}
+
/// `out` as a new `T` is before a load reads its fields: each field's
/// default, an allocator `gpa`.
fn freshOf(comptime T: type, out: *T, gpa: std.mem.Allocator) void {
@@ -2069,6 +2323,8 @@ pub const Get = struct {
allocs: Allocators = .{},
/// How many elements the last array read holds (`pastHeld`).
filled: usize = 0,
+ /// How many things (a session's panes) it left out (`holdTo`).
+ dropped: usize = 0,
const Cursor = Mem.Cursor(.read_only);
pub const Error = error{ BadDump, Incompatible, OutOfMemory };
@@ -2330,6 +2586,10 @@ pub const Get = struct {
const words = (bits + @bitSizeOf(usize) - 1) / @bitSizeOf(usize);
if (got.value.len != 8 + words * @sizeOf(usize)) return error.BadDump;
out.* = try .initEmpty(l.gpa, bits);
+ l.customs.append(l.own, .{ .ptr = out, .gpa = l.gpa, .free = @ptrCast(&Bits(T).free) }) catch |err| {
+ out.deinit(l.gpa);
+ return err;
+ };
if (words > 0) @memcpy(std.mem.sliceAsBytes(out.masks[0..words]), got.value[8..]);
},
}
@@ -2510,6 +2770,7 @@ pub const Get = struct {
if (droppable) {
l.letGo(before);
out[i] = null;
+ l.dropped += 1;
l.note("{s}[{d}] left out", .{ l.field, i });
} else failed = true;
};
@@ -2521,6 +2782,7 @@ pub const Get = struct {
const names = comptime dumpFields(T);
const outer = l.field;
defer l.field = outer;
+ const dropped = l.dropped;
const map = Mem.HashMap(.read_only).init(c) catch return error.Incompatible;
var found: std.StaticBitSet(@max(1, names.len)) = .empty;
var failed = false;
@@ -2572,9 +2834,7 @@ pub const Get = struct {
};
};
if (failed) return error.Incompatible;
- const past = pastHeld(T, out, &held) orelse return;
- l.note("{s}.{s} says {d}, past the {d} its buffer holds: refused", .{ @typeName(T), past.name, past.says, past.holds });
- return error.BadDump;
+ return holdTo(l, T, out, &held, dropped);
}
fn oneField(l: *Get, comptime T: type, comptime field: []const u8, c: Cursor, out: *T, existing: bool) Error!void {
@@ -2886,6 +3146,155 @@ test "a length past what its buffer holds is refused where it is read back (a ta
try std.testing.expectError(error.BadDump, get.get(Room, (try Get.member(root, "room")).?));
}
+test "an index read back that names none of its things is refused, its field named, in a tape, a dump and an image; a place past its thing's last is that last" {
+ const S = struct {
+ const Self = @This();
+ const Inner = struct {
+ at: u8 = 0,
+ list: [3]u8 = @splat(0),
+ n: u8 = 0,
+ // Indexes into the struct holding it, held where its fields end.
+ pub const replica = .{ .len = .{.{ "list", "n" }}, .index = .{ .{ "at", Self, "there" }, .{ "list", Self, "there" } } };
+ };
+ things: [4]?u8 = @splat(null),
+ live: u8 = 0,
+ slot: ?u16 = null,
+ scroll: u32 = 0,
+ inner: [2]?*Inner = @splat(null),
+ pub const replica = .{ .index = .{ .{ "live", "there" }, .{ "slot", "things" } }, .place = .{.{ "scroll", "last" }} };
+ pub fn there(s: *const Self, i: usize) bool {
+ return i < s.things.len and s.things[i] != null;
+ }
+ pub fn last(_: *const Self) usize {
+ return 9;
+ }
+ };
+ const gpa = std.testing.allocator;
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var inner: S.Inner = .{ .at = 2, .list = .{ 0, 2, 1 }, .n = 2 };
+ const good: S = .{ .things = .{ 1, null, 3, null }, .live = 2, .slot = 3, .scroll = 50, .inner = .{ &inner, null } };
+ // Each a value no session has: the field it names.
+ const Bad = struct { []const u8, S };
+ var bad_at: S.Inner = .{ .at = 1 };
+ var bad_list: S.Inner = .{ .list = .{ 0, 3, 0 }, .n = 2 };
+ const bad = [_]Bad{
+ .{ "S.live says 1", blk: {
+ var v = good;
+ v.live = 1;
+ break :blk v;
+ } },
+ .{ "S.slot says 4", blk: {
+ var v = good;
+ v.slot = 4;
+ break :blk v;
+ } },
+ .{ "Inner.at says 1", blk: {
+ var v = good;
+ v.inner[1] = &bad_at;
+ break :blk v;
+ } },
+ .{ "Inner.list says 3", blk: {
+ var v = good;
+ v.inner[1] = &bad_list;
+ break :blk v;
+ } },
+ };
+ var notes: std.ArrayList(u8) = .empty;
+
+ // A dump.
+ const bytes = try save(S, gpa, &good);
+ defer gpa.free(bytes);
+ const back = try load(S, a, bytes, null);
+ try std.testing.expectEqual(@as(u32, 9), back.scroll);
+ try std.testing.expectEqual(@as(?u16, 3), back.slot);
+ for (bad) |b| {
+ const dumped = try save(S, gpa, &b[1]);
+ defer gpa.free(dumped);
+ notes.clearRetainingCapacity();
+ try std.testing.expectError(error.BadDump, load(S, a, dumped, &notes));
+ try std.testing.expect(std.mem.indexOf(u8, notes.items, b[0]) != null);
+ }
+
+ // A tape.
+ var buf: [256]u8 = undefined;
+ var w: std.Io.Writer = .fixed(&buf);
+ try encode(S, &good, &w);
+ for (bad) |b| try encode(S, &b[1], &w);
+ var r: Reader = .{ .bytes = w.buffered() };
+ try std.testing.expectEqual(@as(u32, 9), (try decode(S, &r, a)).scroll);
+ for (bad) |_| try std.testing.expectError(error.BadTape, decode(S, &r, a));
+
+ // An image.
+ var image: std.Io.Writer.Allocating = .init(gpa);
+ defer image.deinit();
+ var db = try Mem.init(std.Io.failing, .{ .buffer = &image, .file_id = 0 });
+ var put: Put = .{ .gpa = gpa };
+ defer put.deinit();
+ try db.runContext(struct {
+ put: *Put,
+ good: *const S,
+ bad: []const Bad,
+ pub fn run(ctx: @This(), cursor: *Mem.Cursor(.read_write)) !void {
+ const map = try Mem.HashMap(.read_write).init(cursor.*);
+ try ctx.put.member(map, "good", S, ctx.good);
+ inline for (0..4) |i| try ctx.put.member(map, std.fmt.comptimePrint("bad{d}", .{i}), S, &ctx.bad[i][1]);
+ }
+ }{ .put = &put, .good = &good, .bad = &bad });
+ var get: Get = .init(a);
+ defer get.deinit();
+ const root = db.rootCursor().readOnly();
+ try std.testing.expectEqual(@as(u32, 9), (try get.get(S, (try Get.member(root, "good")).?)).scroll);
+ inline for (0..4) |i| {
+ get.notes.clearRetainingCapacity();
+ try std.testing.expectError(error.BadDump, get.get(S, (try Get.member(root, std.fmt.comptimePrint("bad{d}", .{i}))).?));
+ try std.testing.expect(std.mem.indexOf(u8, get.notes.items, bad[i][0]) != null);
+ }
+}
+
+test "a thing another build's dump left out takes what named it with it (`left_out`), before the indexes are held" {
+ const Old = struct {
+ const Thing = struct { n: u32 = 0 };
+ things: [2]?*Thing = @splat(null),
+ at: ?u8 = null,
+ };
+ // A thing whose `n` changed kind, no default: it is left out.
+ const New = struct {
+ const Self = @This();
+ const Thing = struct { n: struct { a: u8 } };
+ things: [2]?*Thing = @splat(null),
+ at: ?u8 = null,
+ pub const replica = .{ .index = .{.{ "at", "there" }}, .left_out = "forget" };
+ pub fn there(s: *const Self, i: usize) bool {
+ return i < s.things.len and s.things[i] != null;
+ }
+ pub fn forget(s: *Self) void {
+ if (s.at) |i| if (!s.there(i)) {
+ s.at = null;
+ };
+ }
+ };
+ const Unforgiving = struct {
+ const Self = @This();
+ things: [2]?*New.Thing = @splat(null),
+ at: ?u8 = null,
+ pub const replica = .{ .index = .{.{ "at", "there" }} };
+ pub fn there(s: *const Self, i: usize) bool {
+ return i < s.things.len and s.things[i] != null;
+ }
+ };
+ const gpa = std.testing.allocator;
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ var one: Old.Thing = .{ .n = 1 };
+ const bytes = try save(Old, gpa, &.{ .things = .{ &one, null }, .at = 0 });
+ defer gpa.free(bytes);
+ const new = try load(New, arena.allocator(), bytes, null);
+ try std.testing.expect(new.things[0] == null and new.at == null);
+ try std.testing.expectError(error.BadDump, load(Unforgiving, arena.allocator(), bytes, null));
+}
+
test "a bitset's count read back is held to the bytes left, read or passed over, in a dump and an image: never a size that overflows" {
const gpa = std.testing.allocator;
const B = struct { bits: std.DynamicBitSetUnmanaged = .{}, after: []const u8 = "" };