diff options
Diffstat (limited to 'src/detached/wire.zig')
| -rw-r--r-- | src/detached/wire.zig | 906 |
1 files changed, 405 insertions, 501 deletions
diff --git a/src/detached/wire.zig b/src/detached/wire.zig index d57a28be..2252ce3b 100644 --- a/src/detached/wire.zig +++ b/src/detached/wire.zig @@ -28,7 +28,10 @@ comptime { if (hash.final() != chrome_layout) @compileError(std.fmt.comptimePrint("pardes.Chrome changed (layout 0x{x}): bump wire.version, then chrome_layout", .{hash.final()})); } -pub const Error = error{ Truncated, Overlong, BadTag, BadValue, Trailing, NoSpace }; +/// EndOfStream: the message ends early; WriteFailed: no room for it. +/// ReadFailed is in only because std.Io.Reader says so: a fixed one never +/// fails a read. +pub const Error = error{ EndOfStream, ReadFailed, Overlong, BadTag, BadValue, Trailing, WriteFailed }; pub const max_cols: u16 = 512; pub const max_rows: u16 = 128; @@ -159,8 +162,8 @@ pub const Hello = struct { /// An error rather than a zero on a payload shorter than two bytes, so a /// truncated hello stays diagnosable too instead of reading as version 0. pub fn helloVersion(payload: []const u8) Error!u16 { - var r: Reader = .init(payload); - return r.getU16(); + var r: std.Io.Reader = .fixed(payload); + return r.takeInt(u16, .little); } pub const Welcome = struct { @@ -214,39 +217,39 @@ pub const Frame = struct { chrome.* = .{}; } if (f.layers.len == 0) return; - var r: Reader = .init(f.layers); - const count = try r.getU16(); + var r: std.Io.Reader = .fixed(f.layers); + const count = try r.takeInt(u16, .little); if (count > layers.len) return error.Overlong; for (layers[0..count]) |*layer| { layer.kind = .body; - layer.id = try r.getU16(); - layer.serial = try r.getU32(); - layer.viewport = .{ .x = try r.getU16(), .y = try r.getU16(), .w = try r.getU16(), .h = try r.getU16() }; - layer.cols = try r.getU16(); - layer.rows = try r.getU16(); - layer.context_rows = try r.getU16(); + layer.id = try r.takeInt(u16, .little); + layer.serial = try r.takeInt(u32, .little); + layer.viewport = .{ .x = try r.takeInt(u16, .little), .y = try r.takeInt(u16, .little), .w = try r.takeInt(u16, .little), .h = try r.takeInt(u16, .little) }; + layer.cols = try r.takeInt(u16, .little); + layer.rows = try r.takeInt(u16, .little); + layer.context_rows = try r.takeInt(u16, .little); if (layer.id >= pardes.MAX_PANES or layer.cols == 0 or layer.cols > f.cols or layer.rows == 0 or layer.rows > 2 * max_rows or layer.context_rows > layer.rows or layer.context_rows > limits.wrap_rows or layer.viewport.x > f.cols or layer.viewport.w > f.cols - layer.viewport.x or layer.viewport.y > f.rows or layer.viewport.h > f.rows - layer.viewport.y) return error.BadValue; for (0..layer.context_rows) |row| { - if (try r.getBool()) layer.context_separators.set(row); + if (try getBool(&r)) layer.context_separators.set(row); } const cursor = try getCursor(&r, layer.cols, layer.rows); layer.cursor = if (cursor) |c| .{ .x = c.x, .y = c.y, .bar = c.bar } else null; layer.cells = try gpa.alloc(pardes.Cell, @as(usize, layer.cols) * layer.rows); for (layer.cells) |*cell| cell.* = try decodeCell(&r); } - const tag_count = try r.getU16(); + const tag_count = try r.takeInt(u16, .little); if (tag_count > tags.len) return error.Overlong; for (tags[0..tag_count]) |*layer| { - layer.kind = try r.getTag(pardes.TagKind); - layer.id = try r.getU16(); - layer.serial = try r.getU32(); - layer.viewport = .{ .x = try r.getU16(), .y = try r.getU16(), .w = try r.getU16(), .h = try r.getU16() }; - layer.cols = try r.getU16(); - layer.rows = try r.getU16(); - for (&layer.bg) |*channel| channel.* = try r.getByte(); + layer.kind = try getTag(&r, pardes.TagKind); + layer.id = try r.takeInt(u16, .little); + layer.serial = try r.takeInt(u32, .little); + layer.viewport = .{ .x = try r.takeInt(u16, .little), .y = try r.takeInt(u16, .little), .w = try r.takeInt(u16, .little), .h = try r.takeInt(u16, .little) }; + layer.cols = try r.takeInt(u16, .little); + layer.rows = try r.takeInt(u16, .little); + for (&layer.bg) |*channel| channel.* = try r.takeByte(); if (layer.cols == 0 or layer.viewport.w == 0 or layer.rows == 0 or layer.rows > pardes.MAX_TAG_ROWS or layer.viewport.h != layer.rows or layer.viewport.x > f.cols or layer.viewport.w > f.cols - layer.viewport.x or @@ -261,24 +264,24 @@ pub const Frame = struct { layer.cells = try gpa.alloc(pardes.Cell, @as(usize, layer.cols) * layer.rows); for (layer.cells) |*cell| cell.* = try decodeCell(&r); } - const region_count = try r.getU16(); + const region_count = try r.takeInt(u16, .little); if (region_count > pardes.MAX_REGIONS) return error.Overlong; try regions.ensureTotalCapacity(gpa, region_count); for (0..region_count) |_| { - var region: pardes.Region = .{ .kind = try r.getTag(pardes.Region.Kind), .rect = undefined }; - region.owner = try r.getByte(); - region.serial = try r.getU32(); - region.rect = .{ .x = try r.getU16(), .y = try r.getU16(), .w = try r.getU16(), .h = try r.getU16() }; - const flags = try r.getByte(); + var region: pardes.Region = .{ .kind = try getTag(&r, pardes.Region.Kind), .rect = undefined }; + region.owner = try r.takeByte(); + region.serial = try r.takeInt(u32, .little); + region.rect = .{ .x = try r.takeInt(u16, .little), .y = try r.takeInt(u16, .little), .w = try r.takeInt(u16, .little), .h = try r.takeInt(u16, .little) }; + const flags = try r.takeByte(); if (flags > 3) return error.BadValue; region.active = flags & 1 != 0; region.dirty = flags & 2 != 0; - region.thumb_y = try r.getU16(); - region.thumb_h = try r.getU16(); - region.notice = try r.getByte(); - region.clip = try r.getU16(); - region.lift = @bitCast(try r.getU32()); - region.line = @bitCast(try r.getU32()); + region.thumb_y = try r.takeInt(u16, .little); + region.thumb_h = try r.takeInt(u16, .little); + region.notice = try r.takeByte(); + region.clip = try r.takeInt(u16, .little); + region.lift = @bitCast(try r.takeInt(u32, .little)); + region.line = @bitCast(try r.takeInt(u32, .little)); // A springy flavour overshoots, and a wind-up dips below. if (!(region.lift >= -1 and region.lift <= 2)) return error.BadValue; if (region.rect.x > f.cols or region.rect.w > f.cols - region.rect.x or @@ -290,25 +293,25 @@ pub const Frame = struct { inline for (info.field_names, info.field_types) |name, T| { const rgb = &@field(chrome, name); if (T == ?[3]u8) { - if (try r.getBool()) { + if (try getBool(&r)) { rgb.* = .{ 0, 0, 0 }; - for (&rgb.*.?) |*channel| channel.* = try r.getByte(); + for (&rgb.*.?) |*channel| channel.* = try r.takeByte(); } } else if (T == u8) { - rgb.* = try r.getByte(); + rgb.* = try r.takeByte(); } else if (T == u32) { - rgb.* = try r.getU32(); + rgb.* = try r.takeInt(u32, .little); } else if (T == f32) { - rgb.* = @bitCast(try r.getU32()); + rgb.* = @bitCast(try r.takeInt(u32, .little)); if (!std.math.isFinite(rgb.*)) return error.BadValue; } else if (T == [8]f32) { for (rgb) |*value| { - value.* = @bitCast(try r.getU32()); + value.* = @bitCast(try r.takeInt(u32, .little)); if (!std.math.isFinite(value.*)) return error.BadValue; } - } else for (rgb) |*channel| channel.* = try r.getByte(); + } else for (rgb) |*channel| channel.* = try r.takeByte(); } - try r.end(); + try end(&r); } /// Paint this frame into `grid`, which must be exactly `cols * rows` cells @@ -320,12 +323,12 @@ pub const Frame = struct { pub fn apply(f: Frame, grid: []pardes.Cell) Error!void { if (grid.len != @as(usize, f.cols) * @as(usize, f.rows)) return error.BadValue; if (f.kind == .full) @memset(grid, .{}); - var r: Reader = .init(f.runs); + var r: std.Io.Reader = .fixed(f.runs); var i: u32 = 0; while (i < f.nruns) : (i += 1) { - const start = try r.getU32(); - const count = try r.getU16(); - // A zero-length run is not something `encodeFrame` emits, and + const start = try r.takeInt(u32, .little); + const count = try r.takeInt(u16, .little); + // A zero-length run is not something `encodeFrameLayers` emits, and // accepting one would let a peer spend the run budget saying // nothing. if (count == 0) return error.BadValue; @@ -335,7 +338,7 @@ pub const Frame = struct { if (start > grid.len or count > grid.len - start) return error.Overlong; for (grid[start..][0..count]) |*c| c.* = try decodeCell(&r); } - try r.end(); + try end(&r); } }; @@ -384,169 +387,93 @@ pub const Post = struct { // primitives // --------------------------------------------------------------------------- -pub const Writer = struct { - buf: []u8, - n: usize = 0, - - pub fn init(buf: []u8) Writer { - return .{ .buf = buf }; - } - - pub fn written(w: *const Writer) []const u8 { - return w.buf[0..w.n]; - } - - fn room(w: *Writer, k: usize) Error![]u8 { - if (w.buf.len - w.n < k) return error.NoSpace; - defer w.n += k; - return w.buf[w.n..][0..k]; - } - - fn putByte(w: *Writer, v: u8) Error!void { - (try w.room(1))[0] = v; - } - - fn putU16(w: *Writer, v: u16) Error!void { - std.mem.writeInt(u16, (try w.room(2))[0..2], v, .little); - } - - fn putU32(w: *Writer, v: u32) Error!void { - std.mem.writeInt(u32, (try w.room(4))[0..4], v, .little); - } - - /// One byte, 0 or 1, never "nonzero". `getBool` refuses anything else. - fn putBool(w: *Writer, v: bool) Error!void { - try w.putByte(@intFromBool(v)); - } - - /// IEEE-754 binary32, as its bit pattern in an explicit u32. A scalar - /// bitcast and not a struct blit: the format is the one thing a riscv32 - /// and an x86_64 do agree about. - fn putF32(w: *Writer, v: f32) Error!void { - try w.putU32(@bitCast(v)); - } - - fn putBytes(w: *Writer, v: []const u8) Error!void { - @memcpy(try w.room(v.len), v); - } - - /// Length-prefixed, u16: paths, command lines, a key's text. Nothing here - /// is legitimately longer than 64 KiB and a u16 says so on the wire. - fn putSlice16(w: *Writer, v: []const u8) Error!void { - if (v.len > std.math.maxInt(u16)) return error.Overlong; - try w.putU16(@intCast(v.len)); - try w.putBytes(v); - } - - /// ...and u32 for the ones that are: pty output, a paste, a file. - fn putSlice32(w: *Writer, v: []const u8) Error!void { - if (v.len > max_payload) return error.Overlong; - try w.putU32(@intCast(v.len)); - try w.putBytes(v); - } -}; - -pub const Reader = struct { - bytes: []const u8, - i: usize = 0, - - pub fn init(bytes: []const u8) Reader { - return .{ .bytes = bytes }; - } - - /// `i <= bytes.len` is the invariant every getter below preserves, which is - /// what makes the subtraction here safe. - fn take(r: *Reader, n: usize) Error![]const u8 { - if (r.bytes.len - r.i < n) return error.Truncated; - defer r.i += n; - return r.bytes[r.i..][0..n]; - } - - fn getByte(r: *Reader) Error!u8 { - return (try r.take(1))[0]; - } - - fn getU16(r: *Reader) Error!u16 { - return std.mem.readInt(u16, (try r.take(2))[0..2], .little); - } - - fn getU32(r: *Reader) Error!u32 { - return std.mem.readInt(u32, (try r.take(4))[0..4], .little); - } +/// Length-prefixed, u16: paths, command lines, a key's text. Nothing here +/// is legitimately longer than 64 KiB and a u16 says so on the wire. +fn putSlice16(w: *std.Io.Writer, v: []const u8) Error!void { + if (v.len > std.math.maxInt(u16)) return error.Overlong; + try w.writeInt(u16, @intCast(v.len), .little); + try w.writeAll(v); +} - fn getBool(r: *Reader) Error!bool { - return switch (try r.getByte()) { - 0 => false, - 1 => true, - else => error.BadValue, - }; - } +/// ...and u32 for the ones that are: pty output, a paste, a file. +fn putSlice32(w: *std.Io.Writer, v: []const u8) Error!void { + if (v.len > max_payload) return error.Overlong; + try w.writeInt(u32, @intCast(v.len), .little); + try w.writeAll(v); +} - fn getF32(r: *Reader) Error!f32 { - const v: f32 = @bitCast(try r.getU32()); - // A NaN or an infinity here is not a scroll distance. `pinch` in - // particular multiplies into a zoom factor the pane keeps, so one bad - // value poisons that pane for the rest of the session. - if (!std.math.isFinite(v)) return error.BadValue; - return v; - } +/// One byte, 0 or 1, never "nonzero": the writer's `@intFromBool`. +fn getBool(r: *std.Io.Reader) Error!bool { + return switch (try r.takeByte()) { + 0 => false, + 1 => true, + else => error.BadValue, + }; +} - fn getSlice16(r: *Reader) Error![]const u8 { - return r.take(try r.getU16()); - } +/// IEEE-754 binary32, as its bit pattern in an explicit u32. A scalar +/// bitcast and not a struct blit: the format is the one thing a riscv32 +/// and an x86_64 do agree about. +fn getF32(r: *std.Io.Reader) Error!f32 { + const v: f32 = @bitCast(try r.takeInt(u32, .little)); + // A NaN or an infinity here is not a scroll distance. `pinch` in + // particular multiplies into a zoom factor the pane keeps, so one bad + // value poisons that pane for the rest of the session. + if (!std.math.isFinite(v)) return error.BadValue; + return v; +} - fn getSlice32(r: *Reader) Error![]const u8 { - const n = try r.getU32(); - if (n > max_payload) return error.Overlong; - return r.take(n); - } +fn getSlice32(r: *std.Io.Reader) Error![]const u8 { + const n = try r.takeInt(u32, .little); + if (n > max_payload) return error.Overlong; + return r.take(n); +} - /// A pane id the core can actually index. `Event.output{ .pane = 200 }` - /// would reach `p.panes[200]`. - fn getPane(r: *Reader) Error!u8 { - const pane = try r.getByte(); - if (pane >= pardes.MAX_PANES) return error.BadValue; - return pane; - } +/// A pane id the core can actually index. `Event.output{ .pane = 200 }` +/// would reach `p.panes[200]`. +fn getPane(r: *std.Io.Reader) Error!u8 { + const pane = try r.takeByte(); + if (pane >= pardes.MAX_PANES) return error.BadValue; + return pane; +} - /// A grid the core can render into. Zero is refused rather than clamped: a - /// frontend that has not been sized yet must not be allowed to collapse a - /// shared session to nothing (see server.zig `geometry`). - fn getCols(r: *Reader) Error!u16 { - const v = try r.getU16(); - if (v == 0 or v > max_cols) return error.BadValue; - return v; - } +/// A grid the core can render into. Zero is refused rather than clamped: a +/// frontend that has not been sized yet must not be allowed to collapse a +/// shared session to nothing (see server.zig `geometry`). +fn getCols(r: *std.Io.Reader) Error!u16 { + const v = try r.takeInt(u16, .little); + if (v == 0 or v > max_cols) return error.BadValue; + return v; +} - fn getRows(r: *Reader) Error!u16 { - const v = try r.getU16(); - if (v == 0 or v > max_rows) return error.BadValue; - return v; - } +fn getRows(r: *std.Io.Reader) Error!u16 { + const v = try r.takeInt(u16, .little); + if (v == 0 or v > max_rows) return error.BadValue; + return v; +} - fn getTag(r: *Reader, comptime T: type) Error!T { - return std.enums.fromInt(T, try r.getByte()) orelse error.BadTag; - } +fn getTag(r: *std.Io.Reader, comptime T: type) Error!T { + return std.enums.fromInt(T, try r.takeByte()) orelse error.BadTag; +} - fn end(r: *Reader) Error!void { - if (r.i != r.bytes.len) return error.Trailing; - } -}; +fn end(r: *std.Io.Reader) Error!void { + if (r.seek != r.end) return error.Trailing; +} /// Reserve a message header; `finishMessage` back-patches the length. Two /// passes would mean walking a frame's runs twice to find out how long they /// are, and the walk is the expensive half. -fn beginMessage(w: *Writer, tag: u8) Error!usize { - const at = w.n; - try w.putByte(tag); - try w.putU32(0); +fn beginMessage(w: *std.Io.Writer, tag: u8) Error!usize { + const at = w.end; + try w.writeByte(tag); + try w.writeInt(u32, 0, .little); return at; } -fn finishMessage(w: *Writer, at: usize) Error!void { - const len = w.n - at - header_len; +fn finishMessage(w: *std.Io.Writer, at: usize) Error!void { + const len = w.end - at - header_len; if (len > max_payload) return error.Overlong; - std.mem.writeInt(u32, w.buf[at + 1 ..][0..4], @intCast(len), .little); + std.mem.writeInt(u32, w.buffer[at + 1 ..][0..4], @intCast(len), .little); } /// One complete message at the front of a stream buffer, or null when the rest @@ -567,24 +494,24 @@ pub fn framed(buf: []const u8) Error!?Framed { // cells // --------------------------------------------------------------------------- -fn putColor(w: *Writer, c: pardes.Color) Error!void { +fn putColor(w: *std.Io.Writer, c: pardes.Color) Error!void { switch (c) { - .default => try w.putByte(@backingInt(ColorTag.default)), + .default => try w.writeByte(@backingInt(ColorTag.default)), .index => |i| { - try w.putByte(@backingInt(ColorTag.index)); - try w.putByte(i); + try w.writeByte(@backingInt(ColorTag.index)); + try w.writeByte(i); }, .rgb => |v| { - try w.putByte(@backingInt(ColorTag.rgb)); - try w.putBytes(&v); + try w.writeByte(@backingInt(ColorTag.rgb)); + try w.writeAll(&v); }, } } -fn getColor(r: *Reader) Error!pardes.Color { - return switch (try r.getTag(ColorTag)) { +fn getColor(r: *std.Io.Reader) Error!pardes.Color { + return switch (try getTag(r, ColorTag)) { .default => .default, - .index => .{ .index = try r.getByte() }, + .index => .{ .index = try r.takeByte() }, .rgb => .{ .rgb = (try r.take(3))[0..3].* }, }; } @@ -604,31 +531,31 @@ const Ul = @FieldType(pardes.CellStyle, "ul"); /// existed for, in a form that cannot fall out of step. A variant that has to /// travel under a DIFFERENT name than the core's gets an arm of its own before /// the `inline else`, exactly as `clientTag` keeps the machine-local reports. -fn putUl(w: *Writer, u: Ul) Error!void { - try w.putByte(switch (u) { +fn putUl(w: *std.Io.Writer, u: Ul) Error!void { + try w.writeByte(switch (u) { inline else => |t| @backingInt(@field(UlTag, @tagName(t))), }); } -fn getUl(r: *Reader) Error!Ul { - return switch (try r.getTag(UlTag)) { +fn getUl(r: *std.Io.Reader) Error!Ul { + return switch (try getTag(r, UlTag)) { inline else => |t| @field(Ul, @tagName(t)), }; } -fn putFont(w: *Writer, f: pardes.FontRole) Error!void { - try w.putByte(switch (f) { +fn putFont(w: *std.Io.Writer, f: pardes.FontRole) Error!void { + try w.writeByte(switch (f) { inline else => |t| @backingInt(@field(FontTag, @tagName(t))), }); } -fn getFont(r: *Reader) Error!pardes.FontRole { - return switch (try r.getTag(FontTag)) { +fn getFont(r: *std.Io.Reader) Error!pardes.FontRole { + return switch (try getTag(r, FontTag)) { inline else => |t| @field(pardes.FontRole, @tagName(t)), }; } -/// How many bytes `putCell` will write. Exact, because `encodeFrame` weighs it +/// How many bytes `putCell` will write. Exact, because `encodeFrameLayers` weighs it /// against `run_header` to decide whether to coalesce a run across it. fn cellSize(c: *const pardes.Cell) usize { if (c.default) return 1; @@ -646,11 +573,11 @@ fn colorSize(c: pardes.Color) usize { /// An unpainted cell is ONE byte: `default` means "the shell renders the /// terminal's default cell" (surface.zig `Cell`), so its text and style are not /// merely equal to the defaults, they are not part of the frame at all. -fn putCell(w: *Writer, c: *const pardes.Cell) Error!void { - try w.putBool(c.default); +fn putCell(w: *std.Io.Writer, c: *const pardes.Cell) Error!void { + try w.writeByte(@intFromBool(c.default)); if (c.default) return; - try w.putByte(c.len); - try w.putBytes(c.grapheme()); + try w.writeByte(c.len); + try w.writeAll(c.grapheme()); const s = c.style; try putColor(w, s.fg); try putColor(w, s.bg); @@ -662,15 +589,15 @@ fn putCell(w: *Writer, c: *const pardes.Cell) Error!void { if (s.reverse) attrs |= attr_reverse; if (s.invisible) attrs |= attr_invisible; if (s.strikethrough) attrs |= attr_strikethrough; - try w.putByte(attrs); + try w.writeByte(attrs); try putUl(w, s.ul); try putFont(w, s.font_role); } -fn decodeCell(r: *Reader) Error!pardes.Cell { - if (try r.getBool()) return .{}; +fn decodeCell(r: *std.Io.Reader) Error!pardes.Cell { + if (try getBool(r)) return .{}; var c: pardes.Cell = .{ .default = false }; - const len = try r.getByte(); + const len = try r.takeByte(); // `Cell.text` is 7 bytes and `grapheme()` slices to `len`. A zero-length // grapheme is a cell with nothing to draw and no way to advance a column. if (len == 0 or len > c.text.len) return error.BadValue; @@ -678,7 +605,7 @@ fn decodeCell(r: *Reader) Error!pardes.Cell { @memcpy(c.text[0..len], try r.take(len)); c.style.fg = try getColor(r); c.style.bg = try getColor(r); - const attrs = try r.getByte(); + const attrs = try r.takeByte(); if (attrs & attr_reserved != 0) return error.BadValue; c.style.bold = attrs & attr_bold != 0; c.style.dim = attrs & attr_dim != 0; @@ -696,24 +623,24 @@ fn decodeCell(r: *Reader) Error!pardes.Cell { // frames // --------------------------------------------------------------------------- -fn putCursor(w: *Writer, cursor: ?Cursor, cols: u16, rows: u16) Error!void { +fn putCursor(w: *std.Io.Writer, cursor: ?Cursor, cols: u16, rows: u16) Error!void { // Fixed six bytes whether or not there is a cursor. An optional field // would save five bytes on a message that is already hundreds, and cost a // branch on both sides of the wire. - try w.putBool(cursor != null); + try w.writeByte(@intFromBool(cursor != null)); const c = cursor orelse Cursor{ .x = 0, .y = 0, .bar = false }; // Refused here as well as on decode, so this side cannot build a frame its // own decoder rejects: a dropped frame (sendFrame logs it) leaves a stale // screen, and a refused one takes the frontend's connection with it. if (c.x >= cols or c.y >= rows) return error.BadValue; - try w.putU16(c.x); - try w.putU16(c.y); - try w.putBool(c.bar); + try w.writeInt(u16, c.x, .little); + try w.writeInt(u16, c.y, .little); + try w.writeByte(@intFromBool(c.bar)); } -fn getCursor(r: *Reader, cols: u16, rows: u16) Error!?Cursor { - const present = try r.getBool(); - const c: Cursor = .{ .x = try r.getU16(), .y = try r.getU16(), .bar = try r.getBool() }; +fn getCursor(r: *std.Io.Reader, cols: u16, rows: u16) Error!?Cursor { + const present = try getBool(r); + const c: Cursor = .{ .x = try r.takeInt(u16, .little), .y = try r.takeInt(u16, .little), .bar = try getBool(r) }; // THE cursor bounds check. Every other field of a frame is checked against // the grid and these two were not, and they are the two a frontend indexes // with directly — `Surface.at(cursor.x, cursor.y)` on a grid this frame @@ -725,6 +652,22 @@ fn getCursor(r: *Reader, cols: u16, rows: u16) Error!?Cursor { return if (present) c else null; } +pub fn layersBound(layers: []const pardes.Layer, tags: []const pardes.Layer, regions: []const pardes.Region) usize { + var n: usize = 6; + for (layers) |layer| if (layer.rows != 0) { + n += 26 + layer.context_rows + layer.cells.len * cell_max; + }; + for (tags) |layer| if (layer.rows != 0) { + n += 28 + layer.cells.len * cell_max; + }; + return n + regions.len * region_len + chrome_len; +} + +const region_len = 1 + 1 + 4 + 8 + 1 + 2 + 2 + 1 + 2 + 4 + 4; +/// The palette: each colour three bytes, a theme's optional ones a flag +/// before them. +const chrome_len = @typeInfo(pardes.Chrome).@"struct".field_names.len * 4 + 8 * 4; + /// Encode one frame of `cells`, as a DIFF against `prev` when `prev` is the /// same grid this receiver last acknowledged, and as a FULL frame otherwise. /// @@ -746,45 +689,6 @@ fn getCursor(r: *Reader, cols: u16, rows: u16) Error!?Cursor { /// own 56x14 grid with uncoloured cells, where it is exact: 6298 against 56. /// This transport exists for a frontend on the far end of a slow link, and /// shipping the Surface every frame would be 3 MiB/s at the animation tick. -pub fn encodeFrame( - out: []u8, - cols: u16, - rows: u16, - cursor: ?Cursor, - cells: []const pardes.Cell, - prev: []const pardes.Cell, -) Error![]const u8 { - return encodeFramePointer(out, cols, rows, cursor, .arrow, cells, prev); -} - -pub fn encodeFramePointer( - out: []u8, - cols: u16, - rows: u16, - cursor: ?Cursor, - pointer_shape: pardes.Surface.PointerShape, - cells: []const pardes.Cell, - prev: []const pardes.Cell, -) Error![]const u8 { - return encodeFrameLayers(out, cols, rows, cursor, pointer_shape, cells, prev, &.{}, &.{}, &.{}, .{}); -} - -pub fn layersBound(layers: []const pardes.Layer, tags: []const pardes.Layer, regions: []const pardes.Region) usize { - var n: usize = 6; - for (layers) |layer| if (layer.rows != 0) { - n += 26 + layer.context_rows + layer.cells.len * cell_max; - }; - for (tags) |layer| if (layer.rows != 0) { - n += 28 + layer.cells.len * cell_max; - }; - return n + regions.len * region_len + chrome_len; -} - -const region_len = 1 + 1 + 4 + 8 + 1 + 2 + 2 + 1 + 2 + 4 + 4; -/// The palette: each colour three bytes, a theme's optional ones a flag -/// before them. -const chrome_len = @typeInfo(pardes.Chrome).@"struct".field_names.len * 4 + 8 * 4; - pub fn encodeFrameLayers(out: []u8, cols: u16, rows: u16, cursor: ?Cursor, pointer_shape: pardes.Surface.PointerShape, cells: []const pardes.Cell, prev: []const pardes.Cell, layers: []const pardes.Layer, tags: []const pardes.Layer, regions: []const pardes.Region, chrome: pardes.Chrome) Error![]const u8 { // The protocol's ceiling, enforced by the ENCODER too, and BEFORE the // assert below so a caller can be told rather than tripped. `max_payload` @@ -794,38 +698,38 @@ pub fn encodeFrameLayers(out: []u8, cols: u16, rows: u16, cursor: ?Cursor, point if (cols == 0 or cols > max_cols or rows == 0 or rows > max_rows) return error.Overlong; std.debug.assert(cells.len == @as(usize, cols) * @as(usize, rows)); const full = prev.len != cells.len; - var w: Writer = .init(out); + var w: std.Io.Writer = .fixed(out); const at = try beginMessage(&w, @backingInt(ServerTag.frame)); const header: FrameHeader = if (pointer_shape == .link) (if (full) .full_link else .diff_link) else (if (full) .full else .diff); - try w.putByte(@backingInt(header)); - try w.putU16(cols); - try w.putU16(rows); + try w.writeByte(@backingInt(header)); + try w.writeInt(u16, cols, .little); + try w.writeInt(u16, rows, .little); try putCursor(&w, cursor, cols, rows); - const layers_len_at = w.n; - try w.putU32(0); - const layers_start = w.n; + const layers_len_at = w.end; + try w.writeInt(u32, 0, .little); + const layers_start = w.end; if (layers.len != 0 or tags.len != 0 or regions.len != 0) { var count: u16 = 0; for (layers) |layer| if (layer.rows != 0) { count += 1; }; - try w.putU16(count); + try w.writeInt(u16, count, .little); for (layers) |layer| { if (layer.rows == 0) continue; if (layer.context_rows > limits.wrap_rows or layer.context_rows > layer.rows) return error.BadValue; - try w.putU16(layer.id); - try w.putU32(layer.serial); - try w.putU16(layer.viewport.x); - try w.putU16(layer.viewport.y); - try w.putU16(layer.viewport.w); - try w.putU16(layer.viewport.h); - try w.putU16(layer.cols); - try w.putU16(layer.rows); - try w.putU16(layer.context_rows); - for (0..layer.context_rows) |row| try w.putBool(layer.context_separators.isSet(row)); + try w.writeInt(u16, layer.id, .little); + try w.writeInt(u32, layer.serial, .little); + try w.writeInt(u16, layer.viewport.x, .little); + try w.writeInt(u16, layer.viewport.y, .little); + try w.writeInt(u16, layer.viewport.w, .little); + try w.writeInt(u16, layer.viewport.h, .little); + try w.writeInt(u16, layer.cols, .little); + try w.writeInt(u16, layer.rows, .little); + try w.writeInt(u16, layer.context_rows, .little); + for (0..layer.context_rows) |row| try w.writeByte(@intFromBool(layer.context_separators.isSet(row))); try putCursor(&w, if (layer.cursor) |c| .{ .x = c.x, .y = c.y, .bar = c.bar } else null, layer.cols, layer.rows); for (layer.cells) |*cell| try putCell(&w, cell); } @@ -833,60 +737,60 @@ pub fn encodeFrameLayers(out: []u8, cols: u16, rows: u16, cursor: ?Cursor, point for (tags) |layer| if (layer.rows != 0) { tag_count += 1; }; - try w.putU16(tag_count); + try w.writeInt(u16, tag_count, .little); for (tags) |layer| { if (layer.rows == 0) continue; if (layer.cells.len != @as(usize, layer.cols) * layer.rows) return error.BadValue; - try w.putByte(@backingInt(layer.kind)); - try w.putU16(layer.id); - try w.putU32(layer.serial); - try w.putU16(layer.viewport.x); - try w.putU16(layer.viewport.y); - try w.putU16(layer.viewport.w); - try w.putU16(layer.viewport.h); - try w.putU16(layer.cols); - try w.putU16(layer.rows); - for (layer.bg) |channel| try w.putByte(channel); + try w.writeByte(@backingInt(layer.kind)); + try w.writeInt(u16, layer.id, .little); + try w.writeInt(u32, layer.serial, .little); + try w.writeInt(u16, layer.viewport.x, .little); + try w.writeInt(u16, layer.viewport.y, .little); + try w.writeInt(u16, layer.viewport.w, .little); + try w.writeInt(u16, layer.viewport.h, .little); + try w.writeInt(u16, layer.cols, .little); + try w.writeInt(u16, layer.rows, .little); + for (layer.bg) |channel| try w.writeByte(channel); try putCursor(&w, if (layer.cursor) |c| .{ .x = c.x, .y = c.y, .bar = c.bar } else null, layer.cols, layer.rows); for (layer.cells) |*cell| try putCell(&w, cell); } - try w.putU16(@intCast(regions.len)); + try w.writeInt(u16, @intCast(regions.len), .little); for (regions) |region| { - try w.putByte(@backingInt(region.kind)); - try w.putByte(region.owner); - try w.putU32(region.serial); - try w.putU16(region.rect.x); - try w.putU16(region.rect.y); - try w.putU16(region.rect.w); - try w.putU16(region.rect.h); - try w.putByte(@as(u8, @intFromBool(region.active)) | @as(u8, @intFromBool(region.dirty)) << 1); - try w.putU16(region.thumb_y); - try w.putU16(region.thumb_h); - try w.putByte(region.notice); - try w.putU16(region.clip); - try w.putU32(@bitCast(region.lift)); - try w.putU32(@bitCast(region.line)); + try w.writeByte(@backingInt(region.kind)); + try w.writeByte(region.owner); + try w.writeInt(u32, region.serial, .little); + try w.writeInt(u16, region.rect.x, .little); + try w.writeInt(u16, region.rect.y, .little); + try w.writeInt(u16, region.rect.w, .little); + try w.writeInt(u16, region.rect.h, .little); + try w.writeByte(@as(u8, @intFromBool(region.active)) | @as(u8, @intFromBool(region.dirty)) << 1); + try w.writeInt(u16, region.thumb_y, .little); + try w.writeInt(u16, region.thumb_h, .little); + try w.writeByte(region.notice); + try w.writeInt(u16, region.clip, .little); + try w.writeInt(u32, @bitCast(region.lift), .little); + try w.writeInt(u32, @bitCast(region.line), .little); } const info = @typeInfo(pardes.Chrome).@"struct"; inline for (info.field_names, info.field_types) |name, T| { const rgb = @field(chrome, name); if (T == ?[3]u8) { - try w.putBool(rgb != null); - if (rgb) |value| for (value) |channel| try w.putByte(channel); + try w.writeByte(@intFromBool(rgb != null)); + if (rgb) |value| for (value) |channel| try w.writeByte(channel); } else if (T == u8) { - try w.putByte(rgb); + try w.writeByte(rgb); } else if (T == u32) { - try w.putU32(rgb); + try w.writeInt(u32, rgb, .little); } else if (T == f32) { - try w.putU32(@bitCast(rgb)); + try w.writeInt(u32, @bitCast(rgb), .little); } else if (T == [8]f32) { - for (rgb) |value| try w.putU32(@bitCast(value)); - } else for (rgb) |channel| try w.putByte(channel); + for (rgb) |value| try w.writeInt(u32, @bitCast(value), .little); + } else for (rgb) |channel| try w.writeByte(channel); } } - std.mem.writeInt(u32, w.buf[layers_len_at..][0..4], @intCast(w.n - layers_start), .little); - const nruns_at = w.n; - try w.putU32(0); + std.mem.writeInt(u32, w.buffer[layers_len_at..][0..4], @intCast(w.end - layers_start), .little); + const nruns_at = w.end; + try w.writeInt(u32, 0, .little); var nruns: u32 = 0; var i: usize = 0; @@ -923,15 +827,15 @@ pub fn encodeFrameLayers(out: []u8, cols: u16, rows: u16, cursor: ?Cursor, point if (j >= cells.len or gap >= run_header) break; i = j; } - try w.putU32(@intCast(start)); - try w.putU16(@intCast(run_end - start)); + try w.writeInt(u32, @intCast(start), .little); + try w.writeInt(u16, @intCast(run_end - start), .little); for (cells[start..run_end]) |*c| try putCell(&w, c); nruns += 1; i = run_end; } - std.mem.writeInt(u32, w.buf[nruns_at..][0..4], nruns, .little); + std.mem.writeInt(u32, w.buffer[nruns_at..][0..4], nruns, .little); try finishMessage(&w, at); - return w.written(); + return w.buffered(); } fn sendCell(cells: []const pardes.Cell, prev: []const pardes.Cell, full: bool, i: usize) bool { @@ -964,64 +868,64 @@ fn clientTag(msg: ClientMsg) ClientTag { /// WIRE is not. const has_cell_pixels = @hasField(pardes.CellPixels, "w"); -fn putMetrics(w: *Writer, metrics: ?pardes.RowMetrics) Error!void { - try w.putBool(metrics != null); +fn putMetrics(w: *std.Io.Writer, metrics: ?pardes.RowMetrics) Error!void { + try w.writeByte(@intFromBool(metrics != null)); if (metrics) |m| { - try w.putU16(m.body_w); - try w.putU16(m.body_h); - try w.putU16(m.tagline_w); - try w.putU16(m.tagline_h); + try w.writeInt(u16, m.body_w, .little); + try w.writeInt(u16, m.body_h, .little); + try w.writeInt(u16, m.tagline_w, .little); + try w.writeInt(u16, m.tagline_h, .little); } } -fn getMetrics(r: *Reader) Error!?pardes.RowMetrics { - if (!try r.getBool()) return null; - const m: pardes.RowMetrics = .{ .body_w = try r.getU16(), .body_h = try r.getU16(), .tagline_w = try r.getU16(), .tagline_h = try r.getU16() }; +fn getMetrics(r: *std.Io.Reader) Error!?pardes.RowMetrics { + if (!try getBool(r)) return null; + const m: pardes.RowMetrics = .{ .body_w = try r.takeInt(u16, .little), .body_h = try r.takeInt(u16, .little), .tagline_w = try r.takeInt(u16, .little), .tagline_h = try r.takeInt(u16, .little) }; if (m.body_w == 0 or m.body_h == 0 or m.tagline_w == 0 or m.tagline_h == 0) return error.BadValue; return m; } -fn putBodyHit(w: *Writer, hit: ?pardes.Mouse.BodyHit) Error!void { - try w.putBool(hit != null); +fn putBodyHit(w: *std.Io.Writer, hit: ?pardes.Mouse.BodyHit) Error!void { + try w.writeByte(@intFromBool(hit != null)); if (hit) |h| { - try w.putU32(h.serial); - try w.putU16(h.row); - try w.putU16(h.col); - try w.putF32(h.pixel_x); - try w.putF32(h.pixel_y); + try w.writeInt(u32, h.serial, .little); + try w.writeInt(u16, h.row, .little); + try w.writeInt(u16, h.col, .little); + try w.writeInt(u32, @bitCast(h.pixel_x), .little); + try w.writeInt(u32, @bitCast(h.pixel_y), .little); try putMetrics(w, h.metrics); } } -fn getBodyHit(r: *Reader) Error!?pardes.Mouse.BodyHit { - if (!try r.getBool()) return null; - const hit: pardes.Mouse.BodyHit = .{ .serial = try r.getU32(), .row = try r.getU16(), .col = try r.getU16(), .pixel_x = try r.getF32(), .pixel_y = try r.getF32(), .metrics = (try getMetrics(r)) orelse return error.BadValue }; +fn getBodyHit(r: *std.Io.Reader) Error!?pardes.Mouse.BodyHit { + if (!try getBool(r)) return null; + const hit: pardes.Mouse.BodyHit = .{ .serial = try r.takeInt(u32, .little), .row = try r.takeInt(u16, .little), .col = try r.takeInt(u16, .little), .pixel_x = try getF32(r), .pixel_y = try getF32(r), .metrics = (try getMetrics(r)) orelse return error.BadValue }; if (!std.math.isFinite(hit.pixel_x) or !std.math.isFinite(hit.pixel_y)) return error.BadValue; return hit; } -fn putTagHit(w: *Writer, hit: ?pardes.TagHit) Error!void { - try w.putBool(hit != null); +fn putTagHit(w: *std.Io.Writer, hit: ?pardes.TagHit) Error!void { + try w.writeByte(@intFromBool(hit != null)); if (hit) |h| { - try w.putByte(@backingInt(h.kind)); - try w.putU16(h.id); - try w.putU32(h.serial); - try w.putU16(h.col); - try w.putF32(h.pixel_x); - try w.putF32(h.pixel_y); + try w.writeByte(@backingInt(h.kind)); + try w.writeInt(u16, h.id, .little); + try w.writeInt(u32, h.serial, .little); + try w.writeInt(u16, h.col, .little); + try w.writeInt(u32, @bitCast(h.pixel_x), .little); + try w.writeInt(u32, @bitCast(h.pixel_y), .little); try putMetrics(w, h.metrics); } } -fn getTagHit(r: *Reader) Error!?pardes.TagHit { - if (!try r.getBool()) return null; +fn getTagHit(r: *std.Io.Reader) Error!?pardes.TagHit { + if (!try getBool(r)) return null; const hit: pardes.TagHit = .{ - .kind = try r.getTag(pardes.TagKind), - .id = try r.getU16(), - .serial = try r.getU32(), - .col = try r.getU16(), - .pixel_x = try r.getF32(), - .pixel_y = try r.getF32(), + .kind = try getTag(r, pardes.TagKind), + .id = try r.takeInt(u16, .little), + .serial = try r.takeInt(u32, .little), + .col = try r.takeInt(u16, .little), + .pixel_x = try getF32(r), + .pixel_y = try getF32(r), .metrics = (try getMetrics(r)) orelse return error.BadValue, }; if (!std.math.isFinite(hit.pixel_x) or !std.math.isFinite(hit.pixel_y)) return error.BadValue; @@ -1029,123 +933,123 @@ fn getTagHit(r: *Reader) Error!?pardes.TagHit { } pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 { - var w: Writer = .init(out); + var w: std.Io.Writer = .fixed(out); const at = try beginMessage(&w, @backingInt(clientTag(msg))); switch (msg) { .hello => |h| { - try w.putU16(h.version); - try w.putU16(h.cols); - try w.putU16(h.rows); + try w.writeInt(u16, h.version, .little); + try w.writeInt(u16, h.cols, .little); + try w.writeInt(u16, h.rows, .little); }, .bye => {}, .event => |ev| switch (ev) { .key => |k| { - try w.putU32(k.cp); - try w.putSlice16(k.text); - try w.putBool(k.ctrl); - try w.putBool(k.alt); - try w.putBool(k.shift); + try w.writeInt(u32, k.cp, .little); + try putSlice16(&w, k.text); + try w.writeByte(@intFromBool(k.ctrl)); + try w.writeByte(@intFromBool(k.alt)); + try w.writeByte(@intFromBool(k.shift)); }, .mouse => |m| { - try w.putByte(switch (m.button) { + try w.writeByte(switch (m.button) { inline else => |t| @backingInt(@field(ButtonTag, @tagName(t))), }); - try w.putByte(switch (m.kind) { + try w.writeByte(switch (m.kind) { inline else => |t| @backingInt(@field(KindTag, @tagName(t))), }); - try w.putU16(m.col); - try w.putU16(m.row); - try w.putBool(m.ctrl); - try w.putBool(m.shift); - try w.putBool(m.alt); + try w.writeInt(u16, m.col, .little); + try w.writeInt(u16, m.row, .little); + try w.writeByte(@intFromBool(m.ctrl)); + try w.writeByte(@intFromBool(m.shift)); + try w.writeByte(@intFromBool(m.alt)); try putBodyHit(&w, m.body_hit); try putTagHit(&w, m.tag_hit); }, .resize => |rs| { - try w.putU16(rs.cols); - try w.putU16(rs.rows); + try w.writeInt(u16, rs.cols, .little); + try w.writeInt(u16, rs.rows, .little); // The conventional 1:2 cell aspect when this build has no // pixels of its own, which is the same default the field // carries where it exists. - try w.putU16(if (comptime has_cell_pixels) rs.cell_pixels.w else 8); - try w.putU16(if (comptime has_cell_pixels) rs.cell_pixels.h else 16); + try w.writeInt(u16, if (comptime has_cell_pixels) rs.cell_pixels.w else 8, .little); + try w.writeInt(u16, if (comptime has_cell_pixels) rs.cell_pixels.h else 16, .little); try putMetrics(&w, rs.row_metrics); }, - .paste => |b| try w.putSlice32(b), - .command => |line| try w.putSlice16(line), + .paste => |b| try putSlice32(&w, b), + .command => |line| try putSlice16(&w, line), .pdf_scroll => |s| { - try w.putByte(s.pane); - try w.putF32(s.delta_pixels); + try w.writeByte(s.pane); + try w.writeInt(u32, @bitCast(s.delta_pixels), .little); }, - .pinch => |v| try w.putF32(v), - .touch_scroll => |v| try w.putF32(v), + .pinch => |v| try w.writeInt(u32, @bitCast(v), .little), + .touch_scroll => |v| try w.writeInt(u32, @bitCast(v), .little), .pointer_leave => {}, - .focus => |focused| try w.putBool(focused), + .focus => |focused| try w.writeByte(@intFromBool(focused)), // See `clientTag`: no tag, so nothing to encode. .output, .eof, .exited, .lsp_resp, .pipe_resp, .file_changed, .tick => unreachable, }, } try finishMessage(&w, at); - return w.written(); + return w.buffered(); } pub fn decodeClient(tag: u8, payload: []const u8) Error!ClientMsg { - var r: Reader = .init(payload); + var r: std.Io.Reader = .fixed(payload); const msg: ClientMsg = switch (std.enums.fromInt(ClientTag, tag) orelse return error.BadTag) { .hello => .{ .hello = .{ - .version = try r.getU16(), - .cols = try r.getCols(), - .rows = try r.getRows(), + .version = try r.takeInt(u16, .little), + .cols = try getCols(&r), + .rows = try getRows(&r), } }, .bye => .bye, .key => blk: { - const cp = try r.getU32(); + const cp = try r.takeInt(u32, .little); // `Key.cp` is a u21, and the specials live in the private-use // plane below this bound. A larger number is not a codepoint and // @intCast of it would panic in a release build's own decoder. if (cp > 0x10FFFF) return error.BadValue; break :blk .{ .event = .{ .key = .{ .cp = @intCast(cp), - .text = try r.getSlice16(), - .ctrl = try r.getBool(), - .alt = try r.getBool(), - .shift = try r.getBool(), + .text = try r.take(try r.takeInt(u16, .little)), + .ctrl = try getBool(&r), + .alt = try getBool(&r), + .shift = try getBool(&r), } } }; }, .mouse => .{ .event = .{ .mouse = .{ - .button = switch (try r.getTag(ButtonTag)) { + .button = switch (try getTag(&r, ButtonTag)) { inline else => |t| @field(pardes.Mouse.Button, @tagName(t)), }, - .kind = switch (try r.getTag(KindTag)) { + .kind = switch (try getTag(&r, KindTag)) { inline else => |t| @field(pardes.Mouse.Kind, @tagName(t)), }, - .col = try r.getU16(), - .row = try r.getU16(), - .ctrl = try r.getBool(), - .shift = try r.getBool(), - .alt = try r.getBool(), + .col = try r.takeInt(u16, .little), + .row = try r.takeInt(u16, .little), + .ctrl = try getBool(&r), + .shift = try getBool(&r), + .alt = try getBool(&r), .body_hit = try getBodyHit(&r), .tag_hit = try getTagHit(&r), } } }, .resize => blk: { - var ev: pardes.Event = .{ .resize = .{ .cols = try r.getCols(), .rows = try r.getRows() } }; - const px_w = try r.getU16(); - const px_h = try r.getU16(); + var ev: pardes.Event = .{ .resize = .{ .cols = try getCols(&r), .rows = try getRows(&r) } }; + const px_w = try r.takeInt(u16, .little); + const px_h = try r.takeInt(u16, .little); // Read either way — the bytes are on the wire — and kept only by a // build that has somewhere to keep them. if (comptime has_cell_pixels) ev.resize.cell_pixels = .{ .w = px_w, .h = px_h }; ev.resize.row_metrics = try getMetrics(&r); break :blk .{ .event = ev }; }, - .paste => .{ .event = .{ .paste = try r.getSlice32() } }, - .command => .{ .event = .{ .command = try r.getSlice16() } }, - .pdf_scroll => .{ .event = .{ .pdf_scroll = .{ .pane = try r.getPane(), .delta_pixels = try r.getF32() } } }, - .pinch => .{ .event = .{ .pinch = try r.getF32() } }, - .touch_scroll => .{ .event = .{ .touch_scroll = try r.getF32() } }, + .paste => .{ .event = .{ .paste = try getSlice32(&r) } }, + .command => .{ .event = .{ .command = try r.take(try r.takeInt(u16, .little)) } }, + .pdf_scroll => .{ .event = .{ .pdf_scroll = .{ .pane = try getPane(&r), .delta_pixels = try getF32(&r) } } }, + .pinch => .{ .event = .{ .pinch = try getF32(&r) } }, + .touch_scroll => .{ .event = .{ .touch_scroll = try getF32(&r) } }, .pointer_leave => .{ .event = .pointer_leave }, - .focus => .{ .event = .{ .focus = try r.getBool() } }, + .focus => .{ .event = .{ .focus = try getBool(&r) } }, }; - try r.end(); + try end(&r); return msg; } @@ -1161,42 +1065,42 @@ fn serverTag(msg: ServerMsg) ServerTag { } /// Every server message EXCEPT a frame, which has its own encoder because its -/// payload is a walk of two grids rather than a value (see `encodeFrame`). +/// payload is a walk of two grids rather than a value (see `encodeFrameLayers`). pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 { - var w: Writer = .init(out); + var w: std.Io.Writer = .fixed(out); const at = try beginMessage(&w, @backingInt(serverTag(msg))); switch (msg) { .welcome => |v| { - try w.putU16(v.version); - try w.putByte(v.slot); - try w.putU16(v.cols); - try w.putU16(v.rows); + try w.writeInt(u16, v.version, .little); + try w.writeByte(v.slot); + try w.writeInt(u16, v.cols, .little); + try w.writeInt(u16, v.rows, .little); }, - .refuse => |why| try w.putByte(@backingInt(why)), + .refuse => |why| try w.writeByte(@backingInt(why)), // A frame's runs are not a value this union can hold; the server calls - // encodeFrame directly and this arm exists so the switch stays + // encodeFrameLayers directly and this arm exists so the switch stays // exhaustive over ServerMsg. .frame => return error.BadValue, .quit, .detach => {}, - .set_clipboard => |t| try w.putSlice32(t), + .set_clipboard => |t| try putSlice32(&w, t), .read_clipboard => {}, - .open_link => |u| try w.putSlice16(u), + .open_link => |u| try putSlice16(&w, u), .post => |p| { - try w.putByte(@backingInt(p.animation)); - try w.putByte(p.len); + try w.writeByte(@backingInt(p.animation)); + try w.writeByte(p.len); for (p.list()) |pass| { // 0 a file, else a bundled scene and one. - try w.putByte(if (pass.scene) |scene| @as(u8, @backingInt(scene)) + 1 else 0); - try w.putByte(pass.level); - try w.putByte(@intFromBool(pass.animated)); - try w.putU32(pass.revision); - try w.putSlice16(pass.path); - try w.putSlice32(pass.spirv); + try w.writeByte(if (pass.scene) |scene| @as(u8, @backingInt(scene)) + 1 else 0); + try w.writeByte(pass.level); + try w.writeByte(@intFromBool(pass.animated)); + try w.writeInt(u32, pass.revision, .little); + try putSlice16(&w, pass.path); + try putSlice32(&w, pass.spirv); } }, } try finishMessage(&w, at); - return w.written(); + return w.buffered(); } /// Slack over a message's variable payload, covering every fixed field any @@ -1239,33 +1143,33 @@ pub fn clientBound(msg: ClientMsg) usize { } pub fn decodeServer(tag: u8, payload: []const u8) Error!ServerMsg { - var r: Reader = .init(payload); + var r: std.Io.Reader = .fixed(payload); const msg: ServerMsg = switch (std.enums.fromInt(ServerTag, tag) orelse return error.BadTag) { .welcome => .{ .welcome = .{ - .version = try r.getU16(), - .slot = try r.getByte(), - .cols = try r.getCols(), - .rows = try r.getRows(), + .version = try r.takeInt(u16, .little), + .slot = try r.takeByte(), + .cols = try getCols(&r), + .rows = try getRows(&r), } }, - .refuse => .{ .refuse = try r.getTag(Refusal) }, + .refuse => .{ .refuse = try getTag(&r, Refusal) }, .frame => blk: { - const header = try r.getTag(FrameHeader); + const header = try getTag(&r, FrameHeader); const kind: FrameKind = switch (header) { .full, .full_link => .full, .diff, .diff_link => .diff, }; - const cols = try r.getCols(); - const rows = try r.getRows(); + const cols = try getCols(&r); + const rows = try getRows(&r); const cursor = try getCursor(&r, cols, rows); - const layers = try r.getSlice32(); - const nruns = try r.getU32(); + const layers = try getSlice32(&r); + const nruns = try r.takeInt(u32, .little); // One run per cell is the worst an encoder emits, so a bigger // count cannot be describing this grid. Checked HERE rather than // in `apply`'s loop so the number is refused before it is used to // bound anything. if (nruns > @as(u32, cols) * @as(u32, rows)) return error.Overlong; - const runs = r.bytes[r.i..]; - r.i = r.bytes.len; + const runs = r.buffered(); + r.tossBuffered(); break :blk .{ .frame = .{ .layers = layers, .kind = kind, @@ -1279,32 +1183,32 @@ pub fn decodeServer(tag: u8, payload: []const u8) Error!ServerMsg { }, .quit => .quit, .detach => .detach, - .set_clipboard => .{ .set_clipboard = try r.getSlice32() }, + .set_clipboard => .{ .set_clipboard = try getSlice32(&r) }, .read_clipboard => .read_clipboard, - .open_link => .{ .open_link = try r.getSlice16() }, + .open_link => .{ .open_link = try r.take(try r.takeInt(u16, .little)) }, .post => blk: { - var p: Post = .{ .animation = try r.getTag(ShaderAnimation) }; - p.len = try r.getByte(); + var p: Post = .{ .animation = try getTag(&r, ShaderAnimation) }; + p.len = try r.takeByte(); if (p.len > ShaderBuild.max) return error.Overlong; for (p.passes[0..p.len]) |*pass| { - const kind = try r.getByte(); + const kind = try r.takeByte(); pass.* = .{ .scene = if (kind == 0) null else std.enums.fromInt(Scene, kind - 1) orelse return error.BadValue, - .level = try r.getByte(), - .animated = switch (try r.getByte()) { + .level = try r.takeByte(), + .animated = switch (try r.takeByte()) { 0 => false, 1 => true, else => return error.BadValue, }, - .revision = try r.getU32(), - .path = try r.getSlice16(), - .spirv = try r.getSlice32(), + .revision = try r.takeInt(u32, .little), + .path = try r.take(try r.takeInt(u16, .little)), + .spirv = try getSlice32(&r), }; } break :blk .{ .post = p }; }, }; - try r.end(); + try end(&r); return msg; } @@ -1498,7 +1402,7 @@ test "detached wire: a session is never told to do a frontend's remembering" { for (0..256) |i| { const tag: u8 = @intCast(i); // Empty payloads on purpose: what is asked is whether the TAG is known. - // A known one fails later (`Truncated`) or succeeds, never with + // A known one fails later (`EndOfStream`) or succeeds, never with // `BadTag`. if (decodeClient(tag, &.{})) |_| accepted += 1 else |err| switch (err) { error.BadTag => continue, @@ -1578,7 +1482,7 @@ test "detached wire: a full frame carries the grid, a diff carries the change" { // FULL: nothing on the far side is comparable, which is the late joiner // and the resize both. - const full_bytes = try encodeFrame(buf, cols, rows, .{ .x = 3, .y = 4, .bar = true }, cells, &.{}); + const full_bytes = try encodeFrameLayers(buf, cols, rows, .{ .x = 3, .y = 4, .bar = true }, .arrow, cells, &.{}, &.{}, &.{}, &.{}, .{}); { const f = (try framed(full_bytes)).?; const msg = (try decodeServer(f.tag, f.payload)).frame; @@ -1598,7 +1502,7 @@ test "detached wire: a full frame carries the grid, a diff carries the change" { defer gpa.free(before); cells[100] = .{ .text = "q".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; cells[0] = .{}; // ...and one goes back to unpainted, which a diff must say - const diff_bytes = try encodeFrame(buf, cols, rows, null, cells, before); + const diff_bytes = try encodeFrameLayers(buf, cols, rows, null, .arrow, cells, before, &.{}, &.{}, &.{}, .{}); { const f = (try framed(diff_bytes)).?; const msg = (try decodeServer(f.tag, f.payload)).frame; @@ -1612,7 +1516,7 @@ test "detached wire: a full frame carries the grid, a diff carries the change" { // An unchanged frame is the head and nothing else: no runs, and the // receiver keeps what it has. This is what makes an idle session silent. { - const idle = try encodeFrame(buf, cols, rows, null, cells, cells); + const idle = try encodeFrameLayers(buf, cols, rows, null, .arrow, cells, cells, &.{}, &.{}, &.{}, .{}); try testing.expectEqual(@as(usize, header_len + frame_head), idle.len); const f = (try framed(idle)).?; const msg = (try decodeServer(f.tag, f.payload)).frame; @@ -1648,7 +1552,7 @@ test "detached wire: the largest grid is one cell past a run, and survives it" { for (cells) |*c| c.* = .{ .text = "a".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; @memset(mirror, .{}); - const bytes = try encodeFrame(buf, cols, rows, null, cells, &.{}); + const bytes = try encodeFrameLayers(buf, cols, rows, null, .arrow, cells, &.{}, &.{}, &.{}, &.{}, .{}); const f = (try framed(bytes)).?; const msg = (try decodeServer(f.tag, f.payload)).frame; try testing.expectEqual(FrameKind.full, msg.kind); @@ -1658,7 +1562,7 @@ test "detached wire: the largest grid is one cell past a run, and survives it" { try expectGridEqual(cells, mirror); // ...at exactly the two headers the split costs and not one byte more. // `bytes.len <= frameBound(...)` would prove nothing here — the buffer IS - // `frameBound` bytes, so an over-run is `NoSpace` above, not a false + // `frameBound` bytes, so an over-run is `WriteFailed` above, not a false // assertion here — and what wants pinning is that the second run is the // whole of the cost. try testing.expectEqual( @@ -1668,7 +1572,7 @@ test "detached wire: the largest grid is one cell past a run, and survives it" { } test "detached wire: the diff is worth having, in bytes, on the board's grid" { - // The numbers quoted in `encodeFrame`'s comment, asserted so the claim + // The numbers quoted in `encodeFrameLayers`'s comment, asserted so the claim // cannot rot. 56x14 is the ESP32-P4 board's default grid (esp32p4.zig). const cols: u16 = 56; const rows: u16 = 14; @@ -1683,7 +1587,7 @@ test "detached wire: the diff is worth having, in bytes, on the board's grid" { // Every cell painted with a plain ASCII glyph and default colors, which is // what a pardes frame overwhelmingly is: eight bytes a cell. for (cells) |*c| c.* = .{ .text = "a".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; - const full = (try encodeFrame(buf, cols, rows, null, cells, &.{})).len; + const full = (try encodeFrameLayers(buf, cols, rows, null, .arrow, cells, &.{}, &.{}, &.{}, &.{}, .{})).len; try testing.expectEqual(@as(usize, header_len + frame_head + run_header + n * 8), full); try testing.expectEqual(@as(usize, 6302), full); @@ -1694,7 +1598,7 @@ test "detached wire: the diff is worth having, in bytes, on the board's grid" { cells[300] = .{ .text = "b".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; cells[301] = .{ .text = "c".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; cells[500] = .{ .text = "d".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; - const diff = (try encodeFrame(buf, cols, rows, null, cells, before)).len; + const diff = (try encodeFrameLayers(buf, cols, rows, null, .arrow, cells, before, &.{}, &.{}, &.{}, .{})).len; try testing.expectEqual(@as(usize, header_len + frame_head + 2 * run_header + 3 * 8), diff); try testing.expectEqual(@as(usize, 60), diff); // The whole reason this codec exists rather than shipping the Surface. @@ -1713,7 +1617,7 @@ test "detached wire: a run is coalesced across a gap only when that is cheaper" cells[0] = .{ .text = "a".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; cells[4] = .{ .text = "b".* ++ @as([6]u8, @splat(0)), .len = 1, .default = false }; { - const f = (try framed(try encodeFrame(&buf, cols, rows, null, &cells, &prev))).?; + const f = (try framed(try encodeFrameLayers(&buf, cols, rows, null, .arrow, &cells, &prev, &.{}, &.{}, &.{}, .{}))).?; try testing.expectEqual(@as(u32, 1), (try decodeServer(f.tag, f.payload)).frame.nruns); } // Now put a PAINTED cell in the gap that both sides already agree about. @@ -1722,12 +1626,12 @@ test "detached wire: a run is coalesced across a gap only when that is cheaper" cells[2] = painted; prev[2] = painted; { - const f = (try framed(try encodeFrame(&buf, cols, rows, null, &cells, &prev))).?; + const f = (try framed(try encodeFrameLayers(&buf, cols, rows, null, .arrow, &cells, &prev, &.{}, &.{}, &.{}, .{}))).?; try testing.expectEqual(@as(u32, 2), (try decodeServer(f.tag, f.payload)).frame.nruns); } // Whichever it chose, the receiver ends up with the same grid. var mirror: [8]pardes.Cell = prev; - const f = (try framed(try encodeFrame(&buf, cols, rows, null, &cells, &prev))).?; + const f = (try framed(try encodeFrameLayers(&buf, cols, rows, null, .arrow, &cells, &prev, &.{}, &.{}, &.{}, .{}))).?; try (try decodeServer(f.tag, f.payload)).frame.apply(&mirror); try expectGridEqual(&cells, &mirror); } @@ -1746,7 +1650,7 @@ test "detached wire: a truncated frame is refused at every length" { // ...and the same bytes handed to the decoder with the header's length // left claiming the whole message, which is how a decoder is walked // off the end of its buffer. - try testing.expectError(error.Truncated, decodeClient(copy[0], copy[header_len..cut])); + try testing.expectError(error.EndOfStream, decodeClient(copy[0], copy[header_len..cut])); } // Shorter than the header itself is not yet a message at all. for (0..header_len + 1) |cut| @@ -1789,7 +1693,7 @@ test "detached wire: an over-long length prefix is refused before it is believed var paste: [8]u8 = undefined; std.mem.writeInt(u32, paste[0..4], 4096, .little); @memcpy(paste[4..8], "abcd"); - try testing.expectError(error.Truncated, decodeClient(@backingInt(ClientTag.paste), &paste)); + try testing.expectError(error.EndOfStream, decodeClient(@backingInt(ClientTag.paste), &paste)); // ...and past the cap, which is refused rather than read. std.mem.writeInt(u32, paste[0..4], max_payload + 1, .little); try testing.expectError(error.Overlong, decodeClient(@backingInt(ClientTag.paste), &paste)); @@ -1836,14 +1740,14 @@ test "detached wire: a frame that lies about its runs cannot walk out of the gri // A run count larger than the grid has cells is refused at DECODE, before // it is used to bound the walk. var head: [frame_head]u8 = undefined; - var w: Writer = .init(&head); - try w.putByte(@backingInt(FrameKind.diff)); - try w.putU16(cols); - try w.putU16(rows); + var w: std.Io.Writer = .fixed(&head); + try w.writeByte(@backingInt(FrameKind.diff)); + try w.writeInt(u16, cols, .little); + try w.writeInt(u16, rows, .little); try putCursor(&w, null, cols, rows); - try w.putU32(0); // no body layers - try w.putU32(9); - try testing.expectError(error.Overlong, decodeServer(@backingInt(ServerTag.frame), w.written())); + try w.writeInt(u32, 0, .little); // no body layers + try w.writeInt(u32, 9, .little); + try testing.expectError(error.Overlong, decodeServer(@backingInt(ServerTag.frame), w.buffered())); // ...and a grid of the wrong size is the receiver's own bug, not a frame // it should paint half of. @@ -1863,7 +1767,7 @@ test "detached wire: link pointer survives full and unchanged grid frames" { var buffer: [256]u8 = undefined; for ([_]pardes.Surface.PointerShape{ .link, .arrow, .link }) |shape| { for ([_]bool{ true, false }) |full| { - const bytes = try encodeFramePointer(&buffer, 1, 1, null, shape, &cells, if (full) &.{} else &cells); + const bytes = try encodeFrameLayers(&buffer, 1, 1, null, shape, &cells, if (full) &.{} else &cells, &.{}, &.{}, &.{}, .{}); const packet = (try framed(bytes)).?; const frame = (try decodeServer(packet.tag, packet.payload)).frame; try std.testing.expectEqual(shape, frame.pointer_shape); @@ -1884,32 +1788,32 @@ test "detached wire: a cursor outside the grid is refused, not painted" { const rows: u16 = 2; var head: [frame_head]u8 = undefined; for ([_][2]u16{ .{ cols, 0 }, .{ 0, rows }, .{ 0xffff, 0xffff } }) |xy| { - var w: Writer = .init(&head); - try w.putByte(@backingInt(FrameKind.diff)); - try w.putU16(cols); - try w.putU16(rows); + var w: std.Io.Writer = .fixed(&head); + try w.writeByte(@backingInt(FrameKind.diff)); + try w.writeInt(u16, cols, .little); + try w.writeInt(u16, rows, .little); // Written by hand: `putCursor` now refuses this too, which is the // other half of the same fix and is asserted below. - try w.putBool(true); - try w.putU16(xy[0]); - try w.putU16(xy[1]); - try w.putBool(false); - try w.putU32(0); + try w.writeByte(@intFromBool(true)); + try w.writeInt(u16, xy[0], .little); + try w.writeInt(u16, xy[1], .little); + try w.writeByte(@intFromBool(false)); + try w.writeInt(u32, 0, .little); try testing.expectError( error.BadValue, - decodeServer(@backingInt(ServerTag.frame), w.written()), + decodeServer(@backingInt(ServerTag.frame), w.buffered()), ); } // The last cell IS in the grid, and a frame carrying it decodes. { - var w: Writer = .init(&head); - try w.putByte(@backingInt(FrameKind.diff)); - try w.putU16(cols); - try w.putU16(rows); + var w: std.Io.Writer = .fixed(&head); + try w.writeByte(@backingInt(FrameKind.diff)); + try w.writeInt(u16, cols, .little); + try w.writeInt(u16, rows, .little); try putCursor(&w, .{ .x = cols - 1, .y = rows - 1, .bar = true }, cols, rows); - try w.putU32(0); // no body layers - try w.putU32(0); - const got = (try decodeServer(@backingInt(ServerTag.frame), w.written())).frame; + try w.writeInt(u32, 0, .little); // no body layers + try w.writeInt(u32, 0, .little); + const got = (try decodeServer(@backingInt(ServerTag.frame), w.buffered())).frame; try testing.expectEqual(@as(u16, cols - 1), got.cursor.?.x); try testing.expectEqual(@as(u16, rows - 1), got.cursor.?.y); } @@ -1919,13 +1823,13 @@ test "detached wire: a cursor outside the grid is refused, not painted" { var buf: [512]u8 = undefined; try testing.expectError( error.BadValue, - encodeFrame(&buf, cols, rows, .{ .x = cols, .y = 0, .bar = false }, &cells, &.{}), + encodeFrameLayers(&buf, cols, rows, .{ .x = cols, .y = 0, .bar = false }, .arrow, &cells, &.{}, &.{}, &.{}, &.{}, .{}), ); // A grid past the protocol's own ceiling is refused by the encoder for the // same reason: `max_payload` is derived from it, so the decoder would. try testing.expectError( error.Overlong, - encodeFrame(&buf, max_cols + 1, 1, null, cells[0..0], &.{}), + encodeFrameLayers(&buf, max_cols + 1, 1, null, .arrow, cells[0..0], &.{}, &.{}, &.{}, &.{}, .{}), ); } @@ -1943,7 +1847,7 @@ test "detached wire: values a field cannot mean are refused" { )); // A pane the core cannot index. `pdf_scroll` reads its pane byte before the // f32 that follows, so a one-byte payload reaches the check this is about - // rather than tripping `Truncated` first. + // rather than tripping `EndOfStream` first. try testing.expectError(error.BadValue, decodeClient( @backingInt(ClientTag.pdf_scroll), &.{pardes.MAX_PANES}, @@ -2002,10 +1906,10 @@ test "detached wire: max_payload bounds every message this protocol can build" { const room = try gpa.alloc(u8, huge.len + header_len + 2); defer gpa.free(room); try testing.expectError(error.Overlong, encodeClient(room, .{ .event = .{ .command = huge } })); - // ...and a buffer the caller sized too small is NoSpace, which is the + // ...and a buffer the caller sized too small is WriteFailed, which is the // server's signal to drop that one message rather than the client. var small: [8]u8 = undefined; - try testing.expectError(error.NoSpace, encodeClient(&small, .{ .event = .{ .paste = "0123456789" } })); + try testing.expectError(error.WriteFailed, encodeClient(&small, .{ .event = .{ .paste = "0123456789" } })); } test "detached wire carries compact body rows and exact pointer metrics" { @@ -2061,7 +1965,7 @@ test "detached wire carries compact body rows and exact pointer metrics" { try std.testing.expect(mouse_encoded.len <= clientBound(message)); var truncated = frame; truncated.layers = frame.layers[0 .. frame.layers.len - 1]; - try std.testing.expectError(error.Truncated, truncated.applyLayers(gpa, &decoded, &tags, ®ions, &chrome)); + try std.testing.expectError(error.EndOfStream, truncated.applyLayers(gpa, &decoded, &tags, ®ions, &chrome)); for (decoded) |item| { try std.testing.expectEqual(@as(u16, 0), item.rows); try std.testing.expectEqual(@as(usize, 0), item.cells.len); @@ -2072,7 +1976,7 @@ test "detached wire carries compact body rows and exact pointer metrics" { try std.testing.expectEqual(@as(usize, 0), item.cells.len); } try std.testing.expectEqual(@as(usize, 0), regions.items.len); - const no_layers = try encodeFramePointer(out, 2, 4, null, .arrow, &cells, &cells); + const no_layers = try encodeFrameLayers(out, 2, 4, null, .arrow, &cells, &cells, &.{}, &.{}, &.{}, .{}); const cleared_packet = (try framed(no_layers)).?; const cleared = (try decodeServer(cleared_packet.tag, cleared_packet.payload)).frame; try cleared.applyLayers(gpa, &decoded, &tags, ®ions, &chrome); |
