authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-08-30 12:43:52-07:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2025-08-30 12:43:52-07:00
logb7104231af68c26b850325748a64f15119a2dd69
treec83483ec36ae96af5cf429cf8129336fa09ef256
parent151314346d7c4ed4da13a0a0146e1016c9ca5dd7
parent31a0c2a36a09fd3cd82f061b090fc12c3239dfb1
signaturebadge-check Signed by PGP key B5690EEEBB952194

Merge pull request #25077 from ziglang/GenericReader

std.Io: delete GenericReader, AnyReader, FixedBufferStream; and related API breakage

187 files changed, 1379 insertions(+), 2136 deletions(-)

build.zig+1-1
...@@ -304,7 +304,7 @@ pub fn build(b: *std.Build) !void {...@@ -304,7 +304,7 @@ pub fn build(b: *std.Build) !void {
304 if (enable_llvm) {304 if (enable_llvm) {
305 const cmake_cfg = if (static_llvm) null else blk: {305 const cmake_cfg = if (static_llvm) null else blk: {
306 if (findConfigH(b, config_h_path_option)) |config_h_path| {306 if (findConfigH(b, config_h_path_option)) |config_h_path| {
307 const file_contents = fs.cwd().readFileAlloc(b.allocator, config_h_path, max_config_h_bytes) catch unreachable;307 const file_contents = fs.cwd().readFileAlloc(config_h_path, b.allocator, .limited(max_config_h_bytes)) catch unreachable;
308 break :blk parseConfigH(b, file_contents);308 break :blk parseConfigH(b, file_contents);
309 } else {309 } else {
310 std.log.warn("config.h could not be located automatically. Consider providing it explicitly via \"-Dconfig_h\"", .{});310 std.log.warn("config.h could not be located automatically. Consider providing it explicitly via \"-Dconfig_h\"", .{});
lib/compiler/aro/aro/Attribute/names.zig+2-3
...@@ -117,8 +117,7 @@ pub fn nameFromUniqueIndex(index: u16, buf: []u8) []u8 {...@@ -117,8 +117,7 @@ pub fn nameFromUniqueIndex(index: u16, buf: []u8) []u8 {
117117
118 var node_index: u16 = 0;118 var node_index: u16 = 0;
119 var count: u16 = index;119 var count: u16 = index;
120 var fbs = std.io.fixedBufferStream(buf);120 var w: std.Io.Writer = .fixed(buf);
121 const w = fbs.writer();
122121
123 while (true) {122 while (true) {
124 var sibling_index = dafsa[node_index].child_index;123 var sibling_index = dafsa[node_index].child_index;
...@@ -140,7 +139,7 @@ pub fn nameFromUniqueIndex(index: u16, buf: []u8) []u8 {...@@ -140,7 +139,7 @@ pub fn nameFromUniqueIndex(index: u16, buf: []u8) []u8 {
140 if (count == 0) break;139 if (count == 0) break;
141 }140 }
142141
143 return fbs.getWritten();142 return w.buffered();
144}143}
145144
146const Node = packed struct(u32) {145const Node = packed struct(u32) {
lib/compiler/aro/aro/Compilation.zig+6-24
...@@ -1308,13 +1308,7 @@ fn addSourceFromPathExtra(comp: *Compilation, path: []const u8, kind: Source.Kin...@@ -1308,13 +1308,7 @@ fn addSourceFromPathExtra(comp: *Compilation, path: []const u8, kind: Source.Kin
1308 return error.FileNotFound;1308 return error.FileNotFound;
1309 }1309 }
13101310
1311 const file = try comp.cwd.openFile(path, .{});1311 const contents = try comp.cwd.readFileAlloc(path, comp.gpa, .limited(std.math.maxInt(u32)));
1312 defer file.close();
1313
1314 const contents = file.readToEndAlloc(comp.gpa, std.math.maxInt(u32)) catch |err| switch (err) {
1315 error.FileTooBig => return error.StreamTooLong,
1316 else => |e| return e,
1317 };
1318 errdefer comp.gpa.free(contents);1312 errdefer comp.gpa.free(contents);
13191313
1320 return comp.addSourceFromOwnedBuffer(contents, path, kind);1314 return comp.addSourceFromOwnedBuffer(contents, path, kind);
...@@ -1433,19 +1427,7 @@ fn getFileContents(comp: *Compilation, path: []const u8, limit: ?u32) ![]const u...@@ -1433,19 +1427,7 @@ fn getFileContents(comp: *Compilation, path: []const u8, limit: ?u32) ![]const u
1433 return error.FileNotFound;1427 return error.FileNotFound;
1434 }1428 }
14351429
1436 const file = try comp.cwd.openFile(path, .{});1430 return comp.cwd.readFileAlloc(path, comp.gpa, .limited(limit orelse std.math.maxInt(u32)));
1437 defer file.close();
1438
1439 var buf = std.array_list.Managed(u8).init(comp.gpa);
1440 defer buf.deinit();
1441
1442 const max = limit orelse std.math.maxInt(u32);
1443 file.deprecatedReader().readAllArrayList(&buf, max) catch |e| switch (e) {
1444 error.StreamTooLong => if (limit == null) return e,
1445 else => return e,
1446 };
1447
1448 return buf.toOwnedSlice();
1449}1431}
14501432
1451pub fn findEmbed(1433pub fn findEmbed(
...@@ -1645,8 +1627,8 @@ test "addSourceFromReader" {...@@ -1645,8 +1627,8 @@ test "addSourceFromReader" {
1645 var comp = Compilation.init(std.testing.allocator, std.fs.cwd());1627 var comp = Compilation.init(std.testing.allocator, std.fs.cwd());
1646 defer comp.deinit();1628 defer comp.deinit();
16471629
1648 var buf_reader = std.io.fixedBufferStream(str);1630 var buf_reader: std.Io.Reader = .fixed(str);
1649 const source = try comp.addSourceFromReader(buf_reader.reader(), "path", .user);1631 const source = try comp.addSourceFromReader(&buf_reader, "path", .user);
16501632
1651 try std.testing.expectEqualStrings(expected, source.buf);1633 try std.testing.expectEqualStrings(expected, source.buf);
1652 try std.testing.expectEqual(warning_count, @as(u32, @intCast(comp.diagnostics.list.items.len)));1634 try std.testing.expectEqual(warning_count, @as(u32, @intCast(comp.diagnostics.list.items.len)));
...@@ -1727,8 +1709,8 @@ test "ignore BOM at beginning of file" {...@@ -1727,8 +1709,8 @@ test "ignore BOM at beginning of file" {
1727 var comp = Compilation.init(std.testing.allocator, std.fs.cwd());1709 var comp = Compilation.init(std.testing.allocator, std.fs.cwd());
1728 defer comp.deinit();1710 defer comp.deinit();
17291711
1730 var buf_reader = std.io.fixedBufferStream(buf);1712 var buf_reader: std.Io.Reader = .fixed(buf);
1731 const source = try comp.addSourceFromReader(buf_reader.reader(), "file.c", .user);1713 const source = try comp.addSourceFromReader(&buf_reader, "file.c", .user);
1732 const expected_output = if (mem.startsWith(u8, buf, BOM)) buf[BOM.len..] else buf;1714 const expected_output = if (mem.startsWith(u8, buf, BOM)) buf[BOM.len..] else buf;
1733 try std.testing.expectEqualStrings(expected_output, source.buf);1715 try std.testing.expectEqualStrings(expected_output, source.buf);
1734 }1716 }
lib/compiler/aro/aro/Diagnostics.zig+7-7
...@@ -322,14 +322,14 @@ pub fn addExtra(...@@ -322,14 +322,14 @@ pub fn addExtra(
322 return error.FatalError;322 return error.FatalError;
323}323}
324324
325pub fn render(comp: *Compilation, config: std.io.tty.Config) void {325pub fn render(comp: *Compilation, config: std.Io.tty.Config) void {
326 if (comp.diagnostics.list.items.len == 0) return;326 if (comp.diagnostics.list.items.len == 0) return;
327 var buffer: [1000]u8 = undefined;327 var buffer: [1000]u8 = undefined;
328 var m = defaultMsgWriter(config, &buffer);328 var m = defaultMsgWriter(config, &buffer);
329 defer m.deinit();329 defer m.deinit();
330 renderMessages(comp, &m);330 renderMessages(comp, &m);
331}331}
332pub fn defaultMsgWriter(config: std.io.tty.Config, buffer: []u8) MsgWriter {332pub fn defaultMsgWriter(config: std.Io.tty.Config, buffer: []u8) MsgWriter {
333 return MsgWriter.init(config, buffer);333 return MsgWriter.init(config, buffer);
334}334}
335335
...@@ -451,7 +451,7 @@ pub fn renderMessage(comp: *Compilation, m: anytype, msg: Message) void {...@@ -451,7 +451,7 @@ pub fn renderMessage(comp: *Compilation, m: anytype, msg: Message) void {
451 },451 },
452 .normalized => {452 .normalized => {
453 const f = struct {453 const f = struct {
454 pub fn f(bytes: []const u8, writer: *std.io.Writer) std.io.Writer.Error!void {454 pub fn f(bytes: []const u8, writer: *std.Io.Writer) std.Io.Writer.Error!void {
455 var it: std.unicode.Utf8Iterator = .{455 var it: std.unicode.Utf8Iterator = .{
456 .bytes = bytes,456 .bytes = bytes,
457 .i = 0,457 .i = 0,
...@@ -526,10 +526,10 @@ fn tagKind(d: *Diagnostics, tag: Tag, langopts: LangOpts) Kind {...@@ -526,10 +526,10 @@ fn tagKind(d: *Diagnostics, tag: Tag, langopts: LangOpts) Kind {
526}526}
527527
528const MsgWriter = struct {528const MsgWriter = struct {
529 writer: *std.io.Writer,529 writer: *std.Io.Writer,
530 config: std.io.tty.Config,530 config: std.Io.tty.Config,
531531
532 fn init(config: std.io.tty.Config, buffer: []u8) MsgWriter {532 fn init(config: std.Io.tty.Config, buffer: []u8) MsgWriter {
533 return .{533 return .{
534 .writer = std.debug.lockStderrWriter(buffer),534 .writer = std.debug.lockStderrWriter(buffer),
535 .config = config,535 .config = config,
...@@ -549,7 +549,7 @@ const MsgWriter = struct {...@@ -549,7 +549,7 @@ const MsgWriter = struct {
549 m.writer.writeAll(msg) catch {};549 m.writer.writeAll(msg) catch {};
550 }550 }
551551
552 fn setColor(m: *MsgWriter, color: std.io.tty.Color) void {552 fn setColor(m: *MsgWriter, color: std.Io.tty.Color) void {
553 m.config.setColor(m.writer, color) catch {};553 m.config.setColor(m.writer, color) catch {};
554 }554 }
555555
lib/compiler/aro/aro/Driver.zig+3-3
...@@ -519,8 +519,8 @@ fn option(arg: []const u8, name: []const u8) ?[]const u8 {...@@ -519,8 +519,8 @@ fn option(arg: []const u8, name: []const u8) ?[]const u8 {
519519
520fn addSource(d: *Driver, path: []const u8) !Source {520fn addSource(d: *Driver, path: []const u8) !Source {
521 if (mem.eql(u8, "-", path)) {521 if (mem.eql(u8, "-", path)) {
522 const stdin = std.fs.File.stdin().deprecatedReader();522 var stdin_reader: std.fs.File.Reader = .initStreaming(.stdin(), &.{});
523 const input = try stdin.readAllAlloc(d.comp.gpa, std.math.maxInt(u32));523 const input = try stdin_reader.interface.allocRemaining(d.comp.gpa, .limited(std.math.maxInt(u32)));
524 defer d.comp.gpa.free(input);524 defer d.comp.gpa.free(input);
525 return d.comp.addSourceFromBuffer("<stdin>", input);525 return d.comp.addSourceFromBuffer("<stdin>", input);
526 }526 }
...@@ -544,7 +544,7 @@ pub fn renderErrors(d: *Driver) void {...@@ -544,7 +544,7 @@ pub fn renderErrors(d: *Driver) void {
544 Diagnostics.render(d.comp, d.detectConfig(std.fs.File.stderr()));544 Diagnostics.render(d.comp, d.detectConfig(std.fs.File.stderr()));
545}545}
546546
547pub fn detectConfig(d: *Driver, file: std.fs.File) std.io.tty.Config {547pub fn detectConfig(d: *Driver, file: std.fs.File) std.Io.tty.Config {
548 if (d.color == true) return .escape_codes;548 if (d.color == true) return .escape_codes;
549 if (d.color == false) return .no_color;549 if (d.color == false) return .no_color;
550550
lib/compiler/aro/aro/Tree.zig+8-8
...@@ -800,7 +800,7 @@ pub fn nodeLoc(tree: *const Tree, node: NodeIndex) ?Source.Location {...@@ -800,7 +800,7 @@ pub fn nodeLoc(tree: *const Tree, node: NodeIndex) ?Source.Location {
800 return tree.tokens.items(.loc)[@intFromEnum(tok_i)];800 return tree.tokens.items(.loc)[@intFromEnum(tok_i)];
801}801}
802802
803pub fn dump(tree: *const Tree, config: std.io.tty.Config, writer: anytype) !void {803pub fn dump(tree: *const Tree, config: std.Io.tty.Config, writer: anytype) !void {
804 const mapper = tree.comp.string_interner.getFastTypeMapper(tree.comp.gpa) catch tree.comp.string_interner.getSlowTypeMapper();804 const mapper = tree.comp.string_interner.getFastTypeMapper(tree.comp.gpa) catch tree.comp.string_interner.getSlowTypeMapper();
805 defer mapper.deinit(tree.comp.gpa);805 defer mapper.deinit(tree.comp.gpa);
806806
...@@ -855,17 +855,17 @@ fn dumpNode(...@@ -855,17 +855,17 @@ fn dumpNode(
855 node: NodeIndex,855 node: NodeIndex,
856 level: u32,856 level: u32,
857 mapper: StringInterner.TypeMapper,857 mapper: StringInterner.TypeMapper,
858 config: std.io.tty.Config,858 config: std.Io.tty.Config,
859 w: anytype,859 w: anytype,
860) !void {860) !void {
861 const delta = 2;861 const delta = 2;
862 const half = delta / 2;862 const half = delta / 2;
863 const TYPE = std.io.tty.Color.bright_magenta;863 const TYPE = std.Io.tty.Color.bright_magenta;
864 const TAG = std.io.tty.Color.bright_cyan;864 const TAG = std.Io.tty.Color.bright_cyan;
865 const IMPLICIT = std.io.tty.Color.bright_blue;865 const IMPLICIT = std.Io.tty.Color.bright_blue;
866 const NAME = std.io.tty.Color.bright_red;866 const NAME = std.Io.tty.Color.bright_red;
867 const LITERAL = std.io.tty.Color.bright_green;867 const LITERAL = std.Io.tty.Color.bright_green;
868 const ATTRIBUTE = std.io.tty.Color.bright_yellow;868 const ATTRIBUTE = std.Io.tty.Color.bright_yellow;
869 std.debug.assert(node != .none);869 std.debug.assert(node != .none);
870870
871 const tag = tree.nodes.items(.tag)[@intFromEnum(node)];871 const tag = tree.nodes.items(.tag)[@intFromEnum(node)];
lib/compiler/aro/aro/target.zig+2-3
...@@ -578,8 +578,7 @@ pub fn toLLVMTriple(target: std.Target, buf: []u8) []const u8 {...@@ -578,8 +578,7 @@ pub fn toLLVMTriple(target: std.Target, buf: []u8) []const u8 {
578 // 64 bytes is assumed to be large enough to hold any target triple; increase if necessary578 // 64 bytes is assumed to be large enough to hold any target triple; increase if necessary
579 std.debug.assert(buf.len >= 64);579 std.debug.assert(buf.len >= 64);
580580
581 var stream = std.io.fixedBufferStream(buf);581 var writer: std.Io.Writer = .fixed(buf);
582 const writer = stream.writer();
583582
584 const llvm_arch = switch (target.cpu.arch) {583 const llvm_arch = switch (target.cpu.arch) {
585 .arm => "arm",584 .arm => "arm",
...@@ -719,7 +718,7 @@ pub fn toLLVMTriple(target: std.Target, buf: []u8) []const u8 {...@@ -719,7 +718,7 @@ pub fn toLLVMTriple(target: std.Target, buf: []u8) []const u8 {
719 .ohoseabi => "ohoseabi",718 .ohoseabi => "ohoseabi",
720 };719 };
721 writer.writeAll(llvm_abi) catch unreachable;720 writer.writeAll(llvm_abi) catch unreachable;
722 return stream.getWritten();721 return writer.buffered();
723}722}
724723
725test "alignment functions - smoke test" {724test "alignment functions - smoke test" {
lib/compiler/aro/backend/Ir.zig+12-12
...@@ -374,21 +374,21 @@ pub fn deinit(ir: *Ir, gpa: std.mem.Allocator) void {...@@ -374,21 +374,21 @@ pub fn deinit(ir: *Ir, gpa: std.mem.Allocator) void {
374 ir.* = undefined;374 ir.* = undefined;
375}375}
376376
377const TYPE = std.io.tty.Color.bright_magenta;377const TYPE = std.Io.tty.Color.bright_magenta;
378const INST = std.io.tty.Color.bright_cyan;378const INST = std.Io.tty.Color.bright_cyan;
379const REF = std.io.tty.Color.bright_blue;379const REF = std.Io.tty.Color.bright_blue;
380const LITERAL = std.io.tty.Color.bright_green;380const LITERAL = std.Io.tty.Color.bright_green;
381const ATTRIBUTE = std.io.tty.Color.bright_yellow;381const ATTRIBUTE = std.Io.tty.Color.bright_yellow;
382382
383const RefMap = std.AutoArrayHashMap(Ref, void);383const RefMap = std.AutoArrayHashMap(Ref, void);
384384
385pub fn dump(ir: *const Ir, gpa: Allocator, config: std.io.tty.Config, w: anytype) !void {385pub fn dump(ir: *const Ir, gpa: Allocator, config: std.Io.tty.Config, w: anytype) !void {
386 for (ir.decls.keys(), ir.decls.values()) |name, *decl| {386 for (ir.decls.keys(), ir.decls.values()) |name, *decl| {
387 try ir.dumpDecl(decl, gpa, name, config, w);387 try ir.dumpDecl(decl, gpa, name, config, w);
388 }388 }
389}389}
390390
391fn dumpDecl(ir: *const Ir, decl: *const Decl, gpa: Allocator, name: []const u8, config: std.io.tty.Config, w: anytype) !void {391fn dumpDecl(ir: *const Ir, decl: *const Decl, gpa: Allocator, name: []const u8, config: std.Io.tty.Config, w: anytype) !void {
392 const tags = decl.instructions.items(.tag);392 const tags = decl.instructions.items(.tag);
393 const data = decl.instructions.items(.data);393 const data = decl.instructions.items(.data);
394394
...@@ -609,7 +609,7 @@ fn dumpDecl(ir: *const Ir, decl: *const Decl, gpa: Allocator, name: []const u8,...@@ -609,7 +609,7 @@ fn dumpDecl(ir: *const Ir, decl: *const Decl, gpa: Allocator, name: []const u8,
609 try w.writeAll("}\n\n");609 try w.writeAll("}\n\n");
610}610}
611611
612fn writeType(ir: Ir, ty_ref: Interner.Ref, config: std.io.tty.Config, w: anytype) !void {612fn writeType(ir: Ir, ty_ref: Interner.Ref, config: std.Io.tty.Config, w: anytype) !void {
613 const ty = ir.interner.get(ty_ref);613 const ty = ir.interner.get(ty_ref);
614 try config.setColor(w, TYPE);614 try config.setColor(w, TYPE);
615 switch (ty) {615 switch (ty) {
...@@ -639,7 +639,7 @@ fn writeType(ir: Ir, ty_ref: Interner.Ref, config: std.io.tty.Config, w: anytype...@@ -639,7 +639,7 @@ fn writeType(ir: Ir, ty_ref: Interner.Ref, config: std.io.tty.Config, w: anytype
639 }639 }
640}640}
641641
642fn writeValue(ir: Ir, val: Interner.Ref, config: std.io.tty.Config, w: anytype) !void {642fn writeValue(ir: Ir, val: Interner.Ref, config: std.Io.tty.Config, w: anytype) !void {
643 try config.setColor(w, LITERAL);643 try config.setColor(w, LITERAL);
644 const key = ir.interner.get(val);644 const key = ir.interner.get(val);
645 switch (key) {645 switch (key) {
...@@ -655,7 +655,7 @@ fn writeValue(ir: Ir, val: Interner.Ref, config: std.io.tty.Config, w: anytype)...@@ -655,7 +655,7 @@ fn writeValue(ir: Ir, val: Interner.Ref, config: std.io.tty.Config, w: anytype)
655 }655 }
656}656}
657657
658fn writeRef(ir: Ir, decl: *const Decl, ref_map: *RefMap, ref: Ref, config: std.io.tty.Config, w: anytype) !void {658fn writeRef(ir: Ir, decl: *const Decl, ref_map: *RefMap, ref: Ref, config: std.Io.tty.Config, w: anytype) !void {
659 assert(ref != .none);659 assert(ref != .none);
660 const index = @intFromEnum(ref);660 const index = @intFromEnum(ref);
661 const ty_ref = decl.instructions.items(.ty)[index];661 const ty_ref = decl.instructions.items(.ty)[index];
...@@ -678,7 +678,7 @@ fn writeRef(ir: Ir, decl: *const Decl, ref_map: *RefMap, ref: Ref, config: std.i...@@ -678,7 +678,7 @@ fn writeRef(ir: Ir, decl: *const Decl, ref_map: *RefMap, ref: Ref, config: std.i
678 try w.print(" %{d}", .{ref_index});678 try w.print(" %{d}", .{ref_index});
679}679}
680680
681fn writeNewRef(ir: Ir, decl: *const Decl, ref_map: *RefMap, ref: Ref, config: std.io.tty.Config, w: anytype) !void {681fn writeNewRef(ir: Ir, decl: *const Decl, ref_map: *RefMap, ref: Ref, config: std.Io.tty.Config, w: anytype) !void {
682 try ref_map.put(ref, {});682 try ref_map.put(ref, {});
683 try w.writeAll(" ");683 try w.writeAll(" ");
684 try ir.writeRef(decl, ref_map, ref, config, w);684 try ir.writeRef(decl, ref_map, ref, config, w);
...@@ -687,7 +687,7 @@ fn writeNewRef(ir: Ir, decl: *const Decl, ref_map: *RefMap, ref: Ref, config: st...@@ -687,7 +687,7 @@ fn writeNewRef(ir: Ir, decl: *const Decl, ref_map: *RefMap, ref: Ref, config: st
687 try config.setColor(w, INST);687 try config.setColor(w, INST);
688}688}
689689
690fn writeLabel(decl: *const Decl, label_map: *RefMap, ref: Ref, config: std.io.tty.Config, w: anytype) !void {690fn writeLabel(decl: *const Decl, label_map: *RefMap, ref: Ref, config: std.Io.tty.Config, w: anytype) !void {
691 assert(ref != .none);691 assert(ref != .none);
692 const index = @intFromEnum(ref);692 const index = @intFromEnum(ref);
693 const label = decl.instructions.items(.data)[index].label;693 const label = decl.instructions.items(.data)[index].label;
lib/compiler/aro_translate_c.zig+1-1
...@@ -1783,7 +1783,7 @@ fn renderErrorsAndExit(comp: *aro.Compilation) noreturn {...@@ -1783,7 +1783,7 @@ fn renderErrorsAndExit(comp: *aro.Compilation) noreturn {
1783 defer std.process.exit(1);1783 defer std.process.exit(1);
17841784
1785 var buffer: [1000]u8 = undefined;1785 var buffer: [1000]u8 = undefined;
1786 var writer = aro.Diagnostics.defaultMsgWriter(std.io.tty.detectConfig(std.fs.File.stderr()), &buffer);1786 var writer = aro.Diagnostics.defaultMsgWriter(std.Io.tty.detectConfig(std.fs.File.stderr()), &buffer);
1787 defer writer.deinit(); // writer deinit must run *before* exit so that stderr is flushed1787 defer writer.deinit(); // writer deinit must run *before* exit so that stderr is flushed
17881788
1789 var saw_error = false;1789 var saw_error = false;
lib/compiler/build_runner.zig+10-10
...@@ -1,7 +1,6 @@...@@ -1,7 +1,6 @@
1const std = @import("std");1const std = @import("std");
2const builtin = @import("builtin");2const builtin = @import("builtin");
3const assert = std.debug.assert;3const assert = std.debug.assert;
4const io = std.io;
5const fmt = std.fmt;4const fmt = std.fmt;
6const mem = std.mem;5const mem = std.mem;
7const process = std.process;6const process = std.process;
...@@ -11,8 +10,9 @@ const Watch = std.Build.Watch;...@@ -11,8 +10,9 @@ const Watch = std.Build.Watch;
11const WebServer = std.Build.WebServer;10const WebServer = std.Build.WebServer;
12const Allocator = std.mem.Allocator;11const Allocator = std.mem.Allocator;
13const fatal = std.process.fatal;12const fatal = std.process.fatal;
14const Writer = std.io.Writer;13const Writer = std.Io.Writer;
15const runner = @This();14const runner = @This();
15const tty = std.Io.tty;
1616
17pub const root = @import("@build");17pub const root = @import("@build");
18pub const dependencies = @import("@dependencies");18pub const dependencies = @import("@dependencies");
...@@ -576,7 +576,7 @@ const Run = struct {...@@ -576,7 +576,7 @@ const Run = struct {
576576
577 claimed_rss: usize,577 claimed_rss: usize,
578 summary: Summary,578 summary: Summary,
579 ttyconf: std.io.tty.Config,579 ttyconf: tty.Config,
580 stderr: File,580 stderr: File,
581581
582 fn cleanExit(run: Run) void {582 fn cleanExit(run: Run) void {
...@@ -819,7 +819,7 @@ const PrintNode = struct {...@@ -819,7 +819,7 @@ const PrintNode = struct {
819 last: bool = false,819 last: bool = false,
820};820};
821821
822fn printPrefix(node: *PrintNode, stderr: *Writer, ttyconf: std.io.tty.Config) !void {822fn printPrefix(node: *PrintNode, stderr: *Writer, ttyconf: tty.Config) !void {
823 const parent = node.parent orelse return;823 const parent = node.parent orelse return;
824 if (parent.parent == null) return;824 if (parent.parent == null) return;
825 try printPrefix(parent, stderr, ttyconf);825 try printPrefix(parent, stderr, ttyconf);
...@@ -833,7 +833,7 @@ fn printPrefix(node: *PrintNode, stderr: *Writer, ttyconf: std.io.tty.Config) !v...@@ -833,7 +833,7 @@ fn printPrefix(node: *PrintNode, stderr: *Writer, ttyconf: std.io.tty.Config) !v
833 }833 }
834}834}
835835
836fn printChildNodePrefix(stderr: *Writer, ttyconf: std.io.tty.Config) !void {836fn printChildNodePrefix(stderr: *Writer, ttyconf: tty.Config) !void {
837 try stderr.writeAll(switch (ttyconf) {837 try stderr.writeAll(switch (ttyconf) {
838 .no_color, .windows_api => "+- ",838 .no_color, .windows_api => "+- ",
839 .escape_codes => "\x1B\x28\x30\x6d\x71\x1B\x28\x42 ", // └─839 .escape_codes => "\x1B\x28\x30\x6d\x71\x1B\x28\x42 ", // └─
...@@ -843,7 +843,7 @@ fn printChildNodePrefix(stderr: *Writer, ttyconf: std.io.tty.Config) !void {...@@ -843,7 +843,7 @@ fn printChildNodePrefix(stderr: *Writer, ttyconf: std.io.tty.Config) !void {
843fn printStepStatus(843fn printStepStatus(
844 s: *Step,844 s: *Step,
845 stderr: *Writer,845 stderr: *Writer,
846 ttyconf: std.io.tty.Config,846 ttyconf: tty.Config,
847 run: *const Run,847 run: *const Run,
848) !void {848) !void {
849 switch (s.state) {849 switch (s.state) {
...@@ -923,7 +923,7 @@ fn printStepStatus(...@@ -923,7 +923,7 @@ fn printStepStatus(
923fn printStepFailure(923fn printStepFailure(
924 s: *Step,924 s: *Step,
925 stderr: *Writer,925 stderr: *Writer,
926 ttyconf: std.io.tty.Config,926 ttyconf: tty.Config,
927) !void {927) !void {
928 if (s.result_error_bundle.errorMessageCount() > 0) {928 if (s.result_error_bundle.errorMessageCount() > 0) {
929 try ttyconf.setColor(stderr, .red);929 try ttyconf.setColor(stderr, .red);
...@@ -977,7 +977,7 @@ fn printTreeStep(...@@ -977,7 +977,7 @@ fn printTreeStep(
977 s: *Step,977 s: *Step,
978 run: *const Run,978 run: *const Run,
979 stderr: *Writer,979 stderr: *Writer,
980 ttyconf: std.io.tty.Config,980 ttyconf: tty.Config,
981 parent_node: *PrintNode,981 parent_node: *PrintNode,
982 step_stack: *std.AutoArrayHashMapUnmanaged(*Step, void),982 step_stack: *std.AutoArrayHashMapUnmanaged(*Step, void),
983) !void {983) !void {
...@@ -1494,9 +1494,9 @@ fn uncleanExit() error{UncleanExit} {...@@ -1494,9 +1494,9 @@ fn uncleanExit() error{UncleanExit} {
1494const Color = std.zig.Color;1494const Color = std.zig.Color;
1495const Summary = enum { all, new, failures, none };1495const Summary = enum { all, new, failures, none };
14961496
1497fn get_tty_conf(color: Color, stderr: File) std.io.tty.Config {1497fn get_tty_conf(color: Color, stderr: File) tty.Config {
1498 return switch (color) {1498 return switch (color) {
1499 .auto => std.io.tty.detectConfig(stderr),1499 .auto => tty.detectConfig(stderr),
1500 .on => .escape_codes,1500 .on => .escape_codes,
1501 .off => .no_color,1501 .off => .no_color,
1502 };1502 };
lib/compiler/libc.zig-1
...@@ -1,6 +1,5 @@...@@ -1,6 +1,5 @@
1const std = @import("std");1const std = @import("std");
2const mem = std.mem;2const mem = std.mem;
3const io = std.io;
4const LibCInstallation = std.zig.LibCInstallation;3const LibCInstallation = std.zig.LibCInstallation;
54
6const usage_libc =5const usage_libc =
lib/compiler/reduce.zig+3-4
...@@ -381,7 +381,7 @@ fn transformationsToFixups(...@@ -381,7 +381,7 @@ fn transformationsToFixups(
381 }381 }
382 }382 }
383383
384 var other_source: std.io.Writer.Allocating = .init(gpa);384 var other_source: std.Io.Writer.Allocating = .init(gpa);
385 defer other_source.deinit();385 defer other_source.deinit();
386 try other_source.writer.writeAll("struct {\n");386 try other_source.writer.writeAll("struct {\n");
387 try other_file_ast.render(gpa, &other_source.writer, inlined_fixups);387 try other_file_ast.render(gpa, &other_source.writer, inlined_fixups);
...@@ -398,10 +398,9 @@ fn transformationsToFixups(...@@ -398,10 +398,9 @@ fn transformationsToFixups(
398398
399fn parse(gpa: Allocator, file_path: []const u8) !Ast {399fn parse(gpa: Allocator, file_path: []const u8) !Ast {
400 const source_code = std.fs.cwd().readFileAllocOptions(400 const source_code = std.fs.cwd().readFileAllocOptions(
401 gpa,
402 file_path,401 file_path,
403 std.math.maxInt(u32),402 gpa,
404 null,403 .limited(std.math.maxInt(u32)),
405 .fromByteUnits(1),404 .fromByteUnits(1),
406 0,405 0,
407 ) catch |err| {406 ) catch |err| {
lib/compiler/resinator/ast.zig+3-3
...@@ -22,7 +22,7 @@ pub const Tree = struct {...@@ -22,7 +22,7 @@ pub const Tree = struct {
22 return @alignCast(@fieldParentPtr("base", self.node));22 return @alignCast(@fieldParentPtr("base", self.node));
23 }23 }
2424
25 pub fn dump(self: *Tree, writer: *std.io.Writer) !void {25 pub fn dump(self: *Tree, writer: *std.Io.Writer) !void {
26 try self.node.dump(self, writer, 0);26 try self.node.dump(self, writer, 0);
27 }27 }
28};28};
...@@ -726,9 +726,9 @@ pub const Node = struct {...@@ -726,9 +726,9 @@ pub const Node = struct {
726 pub fn dump(726 pub fn dump(
727 node: *const Node,727 node: *const Node,
728 tree: *const Tree,728 tree: *const Tree,
729 writer: *std.io.Writer,729 writer: *std.Io.Writer,
730 indent: usize,730 indent: usize,
731 ) std.io.Writer.Error!void {731 ) std.Io.Writer.Error!void {
732 try writer.splatByteAll(' ', indent);732 try writer.splatByteAll(' ', indent);
733 try writer.writeAll(@tagName(node.id));733 try writer.writeAll(@tagName(node.id));
734 switch (node.id) {734 switch (node.id) {
lib/compiler/resinator/cli.zig+4-4
...@@ -124,13 +124,13 @@ pub const Diagnostics = struct {...@@ -124,13 +124,13 @@ pub const Diagnostics = struct {
124 try self.errors.append(self.allocator, error_details);124 try self.errors.append(self.allocator, error_details);
125 }125 }
126126
127 pub fn renderToStdErr(self: *Diagnostics, args: []const []const u8, config: std.io.tty.Config) void {127 pub fn renderToStdErr(self: *Diagnostics, args: []const []const u8, config: std.Io.tty.Config) void {
128 const stderr = std.debug.lockStderrWriter(&.{});128 const stderr = std.debug.lockStderrWriter(&.{});
129 defer std.debug.unlockStderrWriter();129 defer std.debug.unlockStderrWriter();
130 self.renderToWriter(args, stderr, config) catch return;130 self.renderToWriter(args, stderr, config) catch return;
131 }131 }
132132
133 pub fn renderToWriter(self: *Diagnostics, args: []const []const u8, writer: *std.io.Writer, config: std.io.tty.Config) !void {133 pub fn renderToWriter(self: *Diagnostics, args: []const []const u8, writer: *std.Io.Writer, config: std.Io.tty.Config) !void {
134 for (self.errors.items) |err_details| {134 for (self.errors.items) |err_details| {
135 try renderErrorMessage(writer, config, err_details, args);135 try renderErrorMessage(writer, config, err_details, args);
136 }136 }
...@@ -1343,7 +1343,7 @@ test parsePercent {...@@ -1343,7 +1343,7 @@ test parsePercent {
1343 try std.testing.expectError(error.InvalidFormat, parsePercent("~1"));1343 try std.testing.expectError(error.InvalidFormat, parsePercent("~1"));
1344}1344}
13451345
1346pub fn renderErrorMessage(writer: *std.io.Writer, config: std.io.tty.Config, err_details: Diagnostics.ErrorDetails, args: []const []const u8) !void {1346pub fn renderErrorMessage(writer: *std.Io.Writer, config: std.Io.tty.Config, err_details: Diagnostics.ErrorDetails, args: []const []const u8) !void {
1347 try config.setColor(writer, .dim);1347 try config.setColor(writer, .dim);
1348 try writer.writeAll("<cli>");1348 try writer.writeAll("<cli>");
1349 try config.setColor(writer, .reset);1349 try config.setColor(writer, .reset);
...@@ -1470,7 +1470,7 @@ fn testParseOutput(args: []const []const u8, expected_output: []const u8) !?Opti...@@ -1470,7 +1470,7 @@ fn testParseOutput(args: []const []const u8, expected_output: []const u8) !?Opti
1470 var diagnostics = Diagnostics.init(std.testing.allocator);1470 var diagnostics = Diagnostics.init(std.testing.allocator);
1471 defer diagnostics.deinit();1471 defer diagnostics.deinit();
14721472
1473 var output: std.io.Writer.Allocating = .init(std.testing.allocator);1473 var output: std.Io.Writer.Allocating = .init(std.testing.allocator);
1474 defer output.deinit();1474 defer output.deinit();
14751475
1476 var options = parse(std.testing.allocator, args, &diagnostics) catch |err| switch (err) {1476 var options = parse(std.testing.allocator, args, &diagnostics) catch |err| switch (err) {
lib/compiler/resinator/errors.zig+4-4
...@@ -61,7 +61,7 @@ pub const Diagnostics = struct {...@@ -61,7 +61,7 @@ pub const Diagnostics = struct {
61 return @intCast(index);61 return @intCast(index);
62 }62 }
6363
64 pub fn renderToStdErr(self: *Diagnostics, cwd: std.fs.Dir, source: []const u8, tty_config: std.io.tty.Config, source_mappings: ?SourceMappings) void {64 pub fn renderToStdErr(self: *Diagnostics, cwd: std.fs.Dir, source: []const u8, tty_config: std.Io.tty.Config, source_mappings: ?SourceMappings) void {
65 const stderr = std.debug.lockStderrWriter(&.{});65 const stderr = std.debug.lockStderrWriter(&.{});
66 defer std.debug.unlockStderrWriter();66 defer std.debug.unlockStderrWriter();
67 for (self.errors.items) |err_details| {67 for (self.errors.items) |err_details| {
...@@ -70,7 +70,7 @@ pub const Diagnostics = struct {...@@ -70,7 +70,7 @@ pub const Diagnostics = struct {
70 }70 }
7171
72 pub fn renderToStdErrDetectTTY(self: *Diagnostics, cwd: std.fs.Dir, source: []const u8, source_mappings: ?SourceMappings) void {72 pub fn renderToStdErrDetectTTY(self: *Diagnostics, cwd: std.fs.Dir, source: []const u8, source_mappings: ?SourceMappings) void {
73 const tty_config = std.io.tty.detectConfig(std.fs.File.stderr());73 const tty_config = std.Io.tty.detectConfig(std.fs.File.stderr());
74 return self.renderToStdErr(cwd, source, tty_config, source_mappings);74 return self.renderToStdErr(cwd, source, tty_config, source_mappings);
75 }75 }
7676
...@@ -409,7 +409,7 @@ pub const ErrorDetails = struct {...@@ -409,7 +409,7 @@ pub const ErrorDetails = struct {
409 failed_to_open_cwd,409 failed_to_open_cwd,
410 };410 };
411411
412 fn formatToken(ctx: TokenFormatContext, writer: *std.io.Writer) std.io.Writer.Error!void {412 fn formatToken(ctx: TokenFormatContext, writer: *std.Io.Writer) std.Io.Writer.Error!void {
413 switch (ctx.token.id) {413 switch (ctx.token.id) {
414 .eof => return writer.writeAll(ctx.token.id.nameForErrorDisplay()),414 .eof => return writer.writeAll(ctx.token.id.nameForErrorDisplay()),
415 else => {},415 else => {},
...@@ -894,7 +894,7 @@ fn cellCount(code_page: SupportedCodePage, source: []const u8, start_index: usiz...@@ -894,7 +894,7 @@ fn cellCount(code_page: SupportedCodePage, source: []const u8, start_index: usiz
894894
895const truncated_str = "<...truncated...>";895const truncated_str = "<...truncated...>";
896896
897pub fn renderErrorMessage(writer: *std.io.Writer, tty_config: std.io.tty.Config, cwd: std.fs.Dir, err_details: ErrorDetails, source: []const u8, strings: []const []const u8, source_mappings: ?SourceMappings) !void {897pub fn renderErrorMessage(writer: *std.Io.Writer, tty_config: std.Io.tty.Config, cwd: std.fs.Dir, err_details: ErrorDetails, source: []const u8, strings: []const []const u8, source_mappings: ?SourceMappings) !void {
898 if (err_details.type == .hint) return;898 if (err_details.type == .hint) return;
899899
900 const source_line_start = err_details.token.getLineStartForErrorDisplay(source);900 const source_line_start = err_details.token.getLineStartForErrorDisplay(source);
lib/compiler/resinator/main.zig+10-6
...@@ -24,7 +24,7 @@ pub fn main() !void {...@@ -24,7 +24,7 @@ pub fn main() !void {
24 const arena = arena_state.allocator();24 const arena = arena_state.allocator();
2525
26 const stderr = std.fs.File.stderr();26 const stderr = std.fs.File.stderr();
27 const stderr_config = std.io.tty.detectConfig(stderr);27 const stderr_config = std.Io.tty.detectConfig(stderr);
2828
29 const args = try std.process.argsAlloc(allocator);29 const args = try std.process.argsAlloc(allocator);
30 defer std.process.argsFree(allocator, args);30 defer std.process.argsFree(allocator, args);
...@@ -164,13 +164,14 @@ pub fn main() !void {...@@ -164,13 +164,14 @@ pub fn main() !void {
164 } else {164 } else {
165 switch (options.input_source) {165 switch (options.input_source) {
166 .stdio => |file| {166 .stdio => |file| {
167 break :full_input file.readToEndAlloc(allocator, std.math.maxInt(usize)) catch |err| {167 var file_reader = file.reader(&.{});
168 break :full_input file_reader.interface.allocRemaining(allocator, .unlimited) catch |err| {
168 try error_handler.emitMessage(allocator, .err, "unable to read input from stdin: {s}", .{@errorName(err)});169 try error_handler.emitMessage(allocator, .err, "unable to read input from stdin: {s}", .{@errorName(err)});
169 std.process.exit(1);170 std.process.exit(1);
170 };171 };
171 },172 },
172 .filename => |input_filename| {173 .filename => |input_filename| {
173 break :full_input std.fs.cwd().readFileAlloc(allocator, input_filename, std.math.maxInt(usize)) catch |err| {174 break :full_input std.fs.cwd().readFileAlloc(input_filename, allocator, .unlimited) catch |err| {
174 try error_handler.emitMessage(allocator, .err, "unable to read input file path '{s}': {s}", .{ input_filename, @errorName(err) });175 try error_handler.emitMessage(allocator, .err, "unable to read input file path '{s}': {s}", .{ input_filename, @errorName(err) });
175 std.process.exit(1);176 std.process.exit(1);
176 };177 };
...@@ -462,7 +463,10 @@ const IoStream = struct {...@@ -462,7 +463,10 @@ const IoStream = struct {
462 pub fn readAll(self: Source, allocator: std.mem.Allocator) !Data {463 pub fn readAll(self: Source, allocator: std.mem.Allocator) !Data {
463 return switch (self) {464 return switch (self) {
464 inline .file, .stdio => |file| .{465 inline .file, .stdio => |file| .{
465 .bytes = try file.readToEndAlloc(allocator, std.math.maxInt(usize)),466 .bytes = b: {
467 var file_reader = file.reader(&.{});
468 break :b try file_reader.interface.allocRemaining(allocator, .unlimited);
469 },
466 .needs_free = true,470 .needs_free = true,
467 },471 },
468 .memory => |list| .{ .bytes = list.items, .needs_free = false },472 .memory => |list| .{ .bytes = list.items, .needs_free = false },
...@@ -621,7 +625,7 @@ const SourceMappings = @import("source_mapping.zig").SourceMappings;...@@ -621,7 +625,7 @@ const SourceMappings = @import("source_mapping.zig").SourceMappings;
621625
622const ErrorHandler = union(enum) {626const ErrorHandler = union(enum) {
623 server: std.zig.Server,627 server: std.zig.Server,
624 tty: std.io.tty.Config,628 tty: std.Io.tty.Config,
625629
626 pub fn emitCliDiagnostics(630 pub fn emitCliDiagnostics(
627 self: *ErrorHandler,631 self: *ErrorHandler,
...@@ -984,7 +988,7 @@ const MsgWriter = struct {...@@ -984,7 +988,7 @@ const MsgWriter = struct {
984 m.buf.appendSlice(msg) catch {};988 m.buf.appendSlice(msg) catch {};
985 }989 }
986990
987 pub fn setColor(m: *MsgWriter, color: std.io.tty.Color) void {991 pub fn setColor(m: *MsgWriter, color: std.Io.tty.Color) void {
988 _ = m;992 _ = m;
989 _ = color;993 _ = color;
990 }994 }
lib/compiler/resinator/res.zig+3-3
...@@ -164,7 +164,7 @@ pub const Language = packed struct(u16) {...@@ -164,7 +164,7 @@ pub const Language = packed struct(u16) {
164 return @bitCast(self);164 return @bitCast(self);
165 }165 }
166166
167 pub fn format(language: Language, w: *std.io.Writer) std.io.Writer.Error!void {167 pub fn format(language: Language, w: *std.Io.Writer) std.Io.Writer.Error!void {
168 const language_id = language.asInt();168 const language_id = language.asInt();
169 const language_name = language_name: {169 const language_name = language_name: {
170 if (std.enums.fromInt(lang.LanguageId, language_id)) |lang_enum_val| {170 if (std.enums.fromInt(lang.LanguageId, language_id)) |lang_enum_val| {
...@@ -439,7 +439,7 @@ pub const NameOrOrdinal = union(enum) {...@@ -439,7 +439,7 @@ pub const NameOrOrdinal = union(enum) {
439 }439 }
440 }440 }
441441
442 pub fn format(self: NameOrOrdinal, w: *std.io.Writer) !void {442 pub fn format(self: NameOrOrdinal, w: *std.Io.Writer) !void {
443 switch (self) {443 switch (self) {
444 .name => |name| {444 .name => |name| {
445 try w.print("{f}", .{std.unicode.fmtUtf16Le(name)});445 try w.print("{f}", .{std.unicode.fmtUtf16Le(name)});
...@@ -450,7 +450,7 @@ pub const NameOrOrdinal = union(enum) {...@@ -450,7 +450,7 @@ pub const NameOrOrdinal = union(enum) {
450 }450 }
451 }451 }
452452
453 fn formatResourceType(self: NameOrOrdinal, w: *std.io.Writer) std.io.Writer.Error!void {453 fn formatResourceType(self: NameOrOrdinal, w: *std.Io.Writer) std.Io.Writer.Error!void {
454 switch (self) {454 switch (self) {
455 .name => |name| {455 .name => |name| {
456 try w.print("{f}", .{std.unicode.fmtUtf16Le(name)});456 try w.print("{f}", .{std.unicode.fmtUtf16Le(name)});
lib/compiler/resinator/utils.zig+1-2
...@@ -1,7 +1,6 @@...@@ -1,7 +1,6 @@
1const std = @import("std");1const std = @import("std");
2const builtin = @import("builtin");2const builtin = @import("builtin");
33
4/// Like std.io.FixedBufferStream but does no bounds checking
5pub const UncheckedSliceWriter = struct {4pub const UncheckedSliceWriter = struct {
6 const Self = @This();5 const Self = @This();
76
...@@ -86,7 +85,7 @@ pub const ErrorMessageType = enum { err, warning, note };...@@ -86,7 +85,7 @@ pub const ErrorMessageType = enum { err, warning, note };
8685
87/// Used for generic colored errors/warnings/notes, more context-specific error messages86/// Used for generic colored errors/warnings/notes, more context-specific error messages
88/// are handled elsewhere.87/// are handled elsewhere.
89pub fn renderErrorMessage(writer: *std.io.Writer, config: std.io.tty.Config, msg_type: ErrorMessageType, comptime format: []const u8, args: anytype) !void {88pub fn renderErrorMessage(writer: *std.Io.Writer, config: std.Io.tty.Config, msg_type: ErrorMessageType, comptime format: []const u8, args: anytype) !void {
90 switch (msg_type) {89 switch (msg_type) {
91 .err => {90 .err => {
92 try config.setColor(writer, .bold);91 try config.setColor(writer, .bold);
lib/compiler/std-docs.zig+3-4
...@@ -1,7 +1,6 @@...@@ -1,7 +1,6 @@
1const builtin = @import("builtin");1const builtin = @import("builtin");
2const std = @import("std");2const std = @import("std");
3const mem = std.mem;3const mem = std.mem;
4const io = std.io;
5const Allocator = std.mem.Allocator;4const Allocator = std.mem.Allocator;
6const assert = std.debug.assert;5const assert = std.debug.assert;
7const Cache = std.Build.Cache;6const Cache = std.Build.Cache;
...@@ -174,7 +173,7 @@ fn serveDocsFile(...@@ -174,7 +173,7 @@ fn serveDocsFile(
174 // The desired API is actually sendfile, which will require enhancing std.http.Server.173 // The desired API is actually sendfile, which will require enhancing std.http.Server.
175 // We load the file with every request so that the user can make changes to the file174 // We load the file with every request so that the user can make changes to the file
176 // and refresh the HTML page without restarting this server.175 // and refresh the HTML page without restarting this server.
177 const file_contents = try context.lib_dir.readFileAlloc(gpa, name, 10 * 1024 * 1024);176 const file_contents = try context.lib_dir.readFileAlloc(name, gpa, .limited(10 * 1024 * 1024));
178 defer gpa.free(file_contents);177 defer gpa.free(file_contents);
179 try request.respond(file_contents, .{178 try request.respond(file_contents, .{
180 .extra_headers = &.{179 .extra_headers = &.{
...@@ -264,7 +263,7 @@ fn serveWasm(...@@ -264,7 +263,7 @@ fn serveWasm(
264 });263 });
265 // std.http.Server does not have a sendfile API yet.264 // std.http.Server does not have a sendfile API yet.
266 const bin_path = try wasm_base_path.join(arena, bin_name);265 const bin_path = try wasm_base_path.join(arena, bin_name);
267 const file_contents = try bin_path.root_dir.handle.readFileAlloc(gpa, bin_path.sub_path, 10 * 1024 * 1024);266 const file_contents = try bin_path.root_dir.handle.readFileAlloc(bin_path.sub_path, gpa, .limited(10 * 1024 * 1024));
268 defer gpa.free(file_contents);267 defer gpa.free(file_contents);
269 try request.respond(file_contents, .{268 try request.respond(file_contents, .{
270 .extra_headers = &.{269 .extra_headers = &.{
...@@ -318,7 +317,7 @@ fn buildWasmBinary(...@@ -318,7 +317,7 @@ fn buildWasmBinary(
318 child.stderr_behavior = .Pipe;317 child.stderr_behavior = .Pipe;
319 try child.spawn();318 try child.spawn();
320319
321 var poller = std.io.poll(gpa, enum { stdout, stderr }, .{320 var poller = std.Io.poll(gpa, enum { stdout, stderr }, .{
322 .stdout = child.stdout.?,321 .stdout = child.stdout.?,
323 .stderr = child.stderr.?,322 .stderr = child.stderr.?,
324 });323 });
lib/fuzzer.zig+1-1
...@@ -220,7 +220,7 @@ const Fuzzer = struct {...@@ -220,7 +220,7 @@ const Fuzzer = struct {
220 const i = f.corpus.items.len;220 const i = f.corpus.items.len;
221 var buf: [30]u8 = undefined;221 var buf: [30]u8 = undefined;
222 const input_sub_path = std.fmt.bufPrint(&buf, "{d}", .{i}) catch unreachable;222 const input_sub_path = std.fmt.bufPrint(&buf, "{d}", .{i}) catch unreachable;
223 const input = f.corpus_directory.handle.readFileAlloc(gpa, input_sub_path, 1 << 31) catch |err| switch (err) {223 const input = f.corpus_directory.handle.readFileAlloc(input_sub_path, gpa, .limited(1 << 31)) catch |err| switch (err) {
224 error.FileNotFound => {224 error.FileNotFound => {
225 // Make this one the next input.225 // Make this one the next input.
226 const input_file = f.corpus_directory.handle.createFile(input_sub_path, .{226 const input_file = f.corpus_directory.handle.createFile(input_sub_path, .{
lib/std/Build.zig+5-5
...@@ -1,6 +1,5 @@...@@ -1,6 +1,5 @@
1const std = @import("std.zig");1const std = @import("std.zig");
2const builtin = @import("builtin");2const builtin = @import("builtin");
3const io = std.io;
4const fs = std.fs;3const fs = std.fs;
5const mem = std.mem;4const mem = std.mem;
6const debug = std.debug;5const debug = std.debug;
...@@ -1830,7 +1829,8 @@ pub fn runAllowFail(...@@ -1830,7 +1829,8 @@ pub fn runAllowFail(
1830 try Step.handleVerbose2(b, null, child.env_map, argv);1829 try Step.handleVerbose2(b, null, child.env_map, argv);
1831 try child.spawn();1830 try child.spawn();
18321831
1833 const stdout = child.stdout.?.deprecatedReader().readAllAlloc(b.allocator, max_output_size) catch {1832 var stdout_reader = child.stdout.?.readerStreaming(&.{});
1833 const stdout = stdout_reader.interface.allocRemaining(b.allocator, .limited(max_output_size)) catch {
1834 return error.ReadFailure;1834 return error.ReadFailure;
1835 };1835 };
1836 errdefer b.allocator.free(stdout);1836 errdefer b.allocator.free(stdout);
...@@ -2540,7 +2540,7 @@ fn dumpBadDirnameHelp(...@@ -2540,7 +2540,7 @@ fn dumpBadDirnameHelp(
25402540
2541 try w.print(msg, args);2541 try w.print(msg, args);
25422542
2543 const tty_config = std.io.tty.detectConfig(.stderr());2543 const tty_config = std.Io.tty.detectConfig(.stderr());
25442544
2545 if (fail_step) |s| {2545 if (fail_step) |s| {
2546 tty_config.setColor(w, .red) catch {};2546 tty_config.setColor(w, .red) catch {};
...@@ -2566,8 +2566,8 @@ fn dumpBadDirnameHelp(...@@ -2566,8 +2566,8 @@ fn dumpBadDirnameHelp(
2566/// In this function the stderr mutex has already been locked.2566/// In this function the stderr mutex has already been locked.
2567pub fn dumpBadGetPathHelp(2567pub fn dumpBadGetPathHelp(
2568 s: *Step,2568 s: *Step,
2569 w: *std.io.Writer,2569 w: *std.Io.Writer,
2570 tty_config: std.io.tty.Config,2570 tty_config: std.Io.tty.Config,
2571 src_builder: *Build,2571 src_builder: *Build,
2572 asking_step: ?*Step,2572 asking_step: ?*Step,
2573) anyerror!void {2573) anyerror!void {
lib/std/Build/Cache.zig+3-3
...@@ -286,7 +286,7 @@ pub const HashHelper = struct {...@@ -286,7 +286,7 @@ pub const HashHelper = struct {
286286
287pub fn binToHex(bin_digest: BinDigest) HexDigest {287pub fn binToHex(bin_digest: BinDigest) HexDigest {
288 var out_digest: HexDigest = undefined;288 var out_digest: HexDigest = undefined;
289 var w: std.io.Writer = .fixed(&out_digest);289 var w: std.Io.Writer = .fixed(&out_digest);
290 w.printHex(&bin_digest, .lower) catch unreachable;290 w.printHex(&bin_digest, .lower) catch unreachable;
291 return out_digest;291 return out_digest;
292}292}
...@@ -664,7 +664,7 @@ pub const Manifest = struct {...@@ -664,7 +664,7 @@ pub const Manifest = struct {
664 const input_file_count = self.files.entries.len;664 const input_file_count = self.files.entries.len;
665 var tiny_buffer: [1]u8 = undefined; // allows allocRemaining to detect limit exceeded665 var tiny_buffer: [1]u8 = undefined; // allows allocRemaining to detect limit exceeded
666 var manifest_reader = self.manifest_file.?.reader(&tiny_buffer); // Reads positionally from zero.666 var manifest_reader = self.manifest_file.?.reader(&tiny_buffer); // Reads positionally from zero.
667 const limit: std.io.Limit = .limited(manifest_file_size_max);667 const limit: std.Io.Limit = .limited(manifest_file_size_max);
668 const file_contents = manifest_reader.interface.allocRemaining(gpa, limit) catch |err| switch (err) {668 const file_contents = manifest_reader.interface.allocRemaining(gpa, limit) catch |err| switch (err) {
669 error.OutOfMemory => return error.OutOfMemory,669 error.OutOfMemory => return error.OutOfMemory,
670 error.StreamTooLong => return error.OutOfMemory,670 error.StreamTooLong => return error.OutOfMemory,
...@@ -1056,7 +1056,7 @@ pub const Manifest = struct {...@@ -1056,7 +1056,7 @@ pub const Manifest = struct {
10561056
1057 fn addDepFileMaybePost(self: *Manifest, dir: fs.Dir, dep_file_basename: []const u8) !void {1057 fn addDepFileMaybePost(self: *Manifest, dir: fs.Dir, dep_file_basename: []const u8) !void {
1058 const gpa = self.cache.gpa;1058 const gpa = self.cache.gpa;
1059 const dep_file_contents = try dir.readFileAlloc(gpa, dep_file_basename, manifest_file_size_max);1059 const dep_file_contents = try dir.readFileAlloc(dep_file_basename, gpa, .limited(manifest_file_size_max));
1060 defer gpa.free(dep_file_contents);1060 defer gpa.free(dep_file_contents);
10611061
1062 var error_buf: std.ArrayListUnmanaged(u8) = .empty;1062 var error_buf: std.ArrayListUnmanaged(u8) = .empty;
lib/std/Build/Cache/Directory.zig+1-1
...@@ -56,7 +56,7 @@ pub fn closeAndFree(self: *Directory, gpa: Allocator) void {...@@ -56,7 +56,7 @@ pub fn closeAndFree(self: *Directory, gpa: Allocator) void {
56 self.* = undefined;56 self.* = undefined;
57}57}
5858
59pub fn format(self: Directory, writer: *std.io.Writer) std.io.Writer.Error!void {59pub fn format(self: Directory, writer: *std.Io.Writer) std.Io.Writer.Error!void {
60 if (self.path) |p| {60 if (self.path) |p| {
61 try writer.writeAll(p);61 try writer.writeAll(p);
62 try writer.writeAll(fs.path.sep_str);62 try writer.writeAll(fs.path.sep_str);
lib/std/Build/Cache/Path.zig+3-3
...@@ -151,7 +151,7 @@ pub fn fmtEscapeString(path: Path) std.fmt.Formatter(Path, formatEscapeString) {...@@ -151,7 +151,7 @@ pub fn fmtEscapeString(path: Path) std.fmt.Formatter(Path, formatEscapeString) {
151 return .{ .data = path };151 return .{ .data = path };
152}152}
153153
154pub fn formatEscapeString(path: Path, writer: *std.io.Writer) std.io.Writer.Error!void {154pub fn formatEscapeString(path: Path, writer: *std.Io.Writer) std.Io.Writer.Error!void {
155 if (path.root_dir.path) |p| {155 if (path.root_dir.path) |p| {
156 try std.zig.stringEscape(p, writer);156 try std.zig.stringEscape(p, writer);
157 if (path.sub_path.len > 0) try std.zig.stringEscape(fs.path.sep_str, writer);157 if (path.sub_path.len > 0) try std.zig.stringEscape(fs.path.sep_str, writer);
...@@ -167,7 +167,7 @@ pub fn fmtEscapeChar(path: Path) std.fmt.Formatter(Path, formatEscapeChar) {...@@ -167,7 +167,7 @@ pub fn fmtEscapeChar(path: Path) std.fmt.Formatter(Path, formatEscapeChar) {
167}167}
168168
169/// Deprecated, use double quoted escape to print paths.169/// Deprecated, use double quoted escape to print paths.
170pub fn formatEscapeChar(path: Path, writer: *std.io.Writer) std.io.Writer.Error!void {170pub fn formatEscapeChar(path: Path, writer: *std.Io.Writer) std.Io.Writer.Error!void {
171 if (path.root_dir.path) |p| {171 if (path.root_dir.path) |p| {
172 for (p) |byte| try std.zig.charEscape(byte, writer);172 for (p) |byte| try std.zig.charEscape(byte, writer);
173 if (path.sub_path.len > 0) try writer.writeByte(fs.path.sep);173 if (path.sub_path.len > 0) try writer.writeByte(fs.path.sep);
...@@ -177,7 +177,7 @@ pub fn formatEscapeChar(path: Path, writer: *std.io.Writer) std.io.Writer.Error!...@@ -177,7 +177,7 @@ pub fn formatEscapeChar(path: Path, writer: *std.io.Writer) std.io.Writer.Error!
177 }177 }
178}178}
179179
180pub fn format(self: Path, writer: *std.io.Writer) std.io.Writer.Error!void {180pub fn format(self: Path, writer: *std.Io.Writer) std.Io.Writer.Error!void {
181 if (std.fs.path.isAbsolute(self.sub_path)) {181 if (std.fs.path.isAbsolute(self.sub_path)) {
182 try writer.writeAll(self.sub_path);182 try writer.writeAll(self.sub_path);
183 return;183 return;
lib/std/Build/Fuzz.zig+2-2
...@@ -127,7 +127,7 @@ pub fn deinit(fuzz: *Fuzz) void {...@@ -127,7 +127,7 @@ pub fn deinit(fuzz: *Fuzz) void {
127 gpa.free(fuzz.run_steps);127 gpa.free(fuzz.run_steps);
128}128}
129129
130fn rebuildTestsWorkerRun(run: *Step.Run, gpa: Allocator, ttyconf: std.io.tty.Config, parent_prog_node: std.Progress.Node) void {130fn rebuildTestsWorkerRun(run: *Step.Run, gpa: Allocator, ttyconf: std.Io.tty.Config, parent_prog_node: std.Progress.Node) void {
131 rebuildTestsWorkerRunFallible(run, gpa, ttyconf, parent_prog_node) catch |err| {131 rebuildTestsWorkerRunFallible(run, gpa, ttyconf, parent_prog_node) catch |err| {
132 const compile = run.producer.?;132 const compile = run.producer.?;
133 log.err("step '{s}': failed to rebuild in fuzz mode: {s}", .{133 log.err("step '{s}': failed to rebuild in fuzz mode: {s}", .{
...@@ -136,7 +136,7 @@ fn rebuildTestsWorkerRun(run: *Step.Run, gpa: Allocator, ttyconf: std.io.tty.Con...@@ -136,7 +136,7 @@ fn rebuildTestsWorkerRun(run: *Step.Run, gpa: Allocator, ttyconf: std.io.tty.Con
136 };136 };
137}137}
138138
139fn rebuildTestsWorkerRunFallible(run: *Step.Run, gpa: Allocator, ttyconf: std.io.tty.Config, parent_prog_node: std.Progress.Node) !void {139fn rebuildTestsWorkerRunFallible(run: *Step.Run, gpa: Allocator, ttyconf: std.Io.tty.Config, parent_prog_node: std.Progress.Node) !void {
140 const compile = run.producer.?;140 const compile = run.producer.?;
141 const prog_node = parent_prog_node.start(compile.step.name, 0);141 const prog_node = parent_prog_node.start(compile.step.name, 0);
142 defer prog_node.end();142 defer prog_node.end();
lib/std/Build/Step/CheckFile.zig+1-1
...@@ -53,7 +53,7 @@ fn make(step: *Step, options: Step.MakeOptions) !void {...@@ -53,7 +53,7 @@ fn make(step: *Step, options: Step.MakeOptions) !void {
53 try step.singleUnchangingWatchInput(check_file.source);53 try step.singleUnchangingWatchInput(check_file.source);
5454
55 const src_path = check_file.source.getPath2(b, step);55 const src_path = check_file.source.getPath2(b, step);
56 const contents = fs.cwd().readFileAlloc(b.allocator, src_path, check_file.max_bytes) catch |err| {56 const contents = fs.cwd().readFileAlloc(src_path, b.allocator, .limited(check_file.max_bytes)) catch |err| {
57 return step.fail("unable to read '{s}': {s}", .{57 return step.fail("unable to read '{s}': {s}", .{
58 src_path, @errorName(err),58 src_path, @errorName(err),
59 });59 });
lib/std/Build/Step/CheckObject.zig+139-150
...@@ -6,7 +6,7 @@ const macho = std.macho;...@@ -6,7 +6,7 @@ const macho = std.macho;
6const math = std.math;6const math = std.math;
7const mem = std.mem;7const mem = std.mem;
8const testing = std.testing;8const testing = std.testing;
9const Writer = std.io.Writer;9const Writer = std.Io.Writer;
1010
11const CheckObject = @This();11const CheckObject = @This();
1212
...@@ -553,14 +553,13 @@ fn make(step: *Step, make_options: Step.MakeOptions) !void {...@@ -553,14 +553,13 @@ fn make(step: *Step, make_options: Step.MakeOptions) !void {
553553
554 const src_path = check_object.source.getPath3(b, step);554 const src_path = check_object.source.getPath3(b, step);
555 const contents = src_path.root_dir.handle.readFileAllocOptions(555 const contents = src_path.root_dir.handle.readFileAllocOptions(
556 gpa,
557 src_path.sub_path,556 src_path.sub_path,
558 check_object.max_bytes,557 gpa,
559 null,558 .limited(check_object.max_bytes),
560 .of(u64),559 .of(u64),
561 null,560 null,
562 ) catch |err| return step.fail("unable to read '{f}': {s}", .{561 ) catch |err| return step.fail("unable to read '{f}': {t}", .{
563 std.fmt.alt(src_path, .formatEscapeChar), @errorName(err),562 std.fmt.alt(src_path, .formatEscapeChar), err,
564 });563 });
565564
566 var vars: std.StringHashMap(u64) = .init(gpa);565 var vars: std.StringHashMap(u64) = .init(gpa);
...@@ -1462,7 +1461,7 @@ const MachODumper = struct {...@@ -1462,7 +1461,7 @@ const MachODumper = struct {
1462 const TrieIterator = struct {1461 const TrieIterator = struct {
1463 stream: std.Io.Reader,1462 stream: std.Io.Reader,
14641463
1465 fn readUleb128(it: *TrieIterator) !u64 {1464 fn takeLeb128(it: *TrieIterator) !u64 {
1466 return it.stream.takeLeb128(u64);1465 return it.stream.takeLeb128(u64);
1467 }1466 }
14681467
...@@ -1470,7 +1469,7 @@ const MachODumper = struct {...@@ -1470,7 +1469,7 @@ const MachODumper = struct {
1470 return it.stream.takeSentinel(0);1469 return it.stream.takeSentinel(0);
1471 }1470 }
14721471
1473 fn readByte(it: *TrieIterator) !u8 {1472 fn takeByte(it: *TrieIterator) !u8 {
1474 return it.stream.takeByte();1473 return it.stream.takeByte();
1475 }1474 }
1476 };1475 };
...@@ -1518,12 +1517,12 @@ const MachODumper = struct {...@@ -1518,12 +1517,12 @@ const MachODumper = struct {
1518 prefix: []const u8,1517 prefix: []const u8,
1519 exports: *std.array_list.Managed(Export),1518 exports: *std.array_list.Managed(Export),
1520 ) !void {1519 ) !void {
1521 const size = try it.readUleb128();1520 const size = try it.takeLeb128();
1522 if (size > 0) {1521 if (size > 0) {
1523 const flags = try it.readUleb128();1522 const flags = try it.takeLeb128();
1524 switch (flags) {1523 switch (flags) {
1525 macho.EXPORT_SYMBOL_FLAGS_REEXPORT => {1524 macho.EXPORT_SYMBOL_FLAGS_REEXPORT => {
1526 const ord = try it.readUleb128();1525 const ord = try it.takeLeb128();
1527 const name = try arena.dupe(u8, try it.readString());1526 const name = try arena.dupe(u8, try it.readString());
1528 try exports.append(.{1527 try exports.append(.{
1529 .name = if (name.len > 0) name else prefix,1528 .name = if (name.len > 0) name else prefix,
...@@ -1532,8 +1531,8 @@ const MachODumper = struct {...@@ -1532,8 +1531,8 @@ const MachODumper = struct {
1532 });1531 });
1533 },1532 },
1534 macho.EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER => {1533 macho.EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER => {
1535 const stub_offset = try it.readUleb128();1534 const stub_offset = try it.takeLeb128();
1536 const resolver_offset = try it.readUleb128();1535 const resolver_offset = try it.takeLeb128();
1537 try exports.append(.{1536 try exports.append(.{
1538 .name = prefix,1537 .name = prefix,
1539 .tag = .stub_resolver,1538 .tag = .stub_resolver,
...@@ -1544,7 +1543,7 @@ const MachODumper = struct {...@@ -1544,7 +1543,7 @@ const MachODumper = struct {
1544 });1543 });
1545 },1544 },
1546 else => {1545 else => {
1547 const vmoff = try it.readUleb128();1546 const vmoff = try it.takeLeb128();
1548 try exports.append(.{1547 try exports.append(.{
1549 .name = prefix,1548 .name = prefix,
1550 .tag = .@"export",1549 .tag = .@"export",
...@@ -1563,10 +1562,10 @@ const MachODumper = struct {...@@ -1563,10 +1562,10 @@ const MachODumper = struct {
1563 }1562 }
1564 }1563 }
15651564
1566 const nedges = try it.readByte();1565 const nedges = try it.takeByte();
1567 for (0..nedges) |_| {1566 for (0..nedges) |_| {
1568 const label = try it.readString();1567 const label = try it.readString();
1569 const off = try it.readUleb128();1568 const off = try it.takeLeb128();
1570 const prefix_label = try std.fmt.allocPrint(arena, "{s}{s}", .{ prefix, label });1569 const prefix_label = try std.fmt.allocPrint(arena, "{s}{s}", .{ prefix, label });
1571 const curr = it.stream.seek;1570 const curr = it.stream.seek;
1572 it.stream.seek = off;1571 it.stream.seek = off;
...@@ -1701,11 +1700,10 @@ const ElfDumper = struct {...@@ -1701,11 +1700,10 @@ const ElfDumper = struct {
17011700
1702 fn parseAndDumpArchive(step: *Step, check: Check, bytes: []const u8) ![]const u8 {1701 fn parseAndDumpArchive(step: *Step, check: Check, bytes: []const u8) ![]const u8 {
1703 const gpa = step.owner.allocator;1702 const gpa = step.owner.allocator;
1704 var stream = std.io.fixedBufferStream(bytes);1703 var reader: std.Io.Reader = .fixed(bytes);
1705 const reader = stream.reader();
17061704
1707 const magic = try reader.readBytesNoEof(elf.ARMAG.len);1705 const magic = try reader.takeArray(elf.ARMAG.len);
1708 if (!mem.eql(u8, &magic, elf.ARMAG)) {1706 if (!mem.eql(u8, magic, elf.ARMAG)) {
1709 return error.InvalidArchiveMagicNumber;1707 return error.InvalidArchiveMagicNumber;
1710 }1708 }
17111709
...@@ -1722,28 +1720,26 @@ const ElfDumper = struct {...@@ -1722,28 +1720,26 @@ const ElfDumper = struct {
1722 }1720 }
17231721
1724 while (true) {1722 while (true) {
1725 if (stream.pos >= ctx.data.len) break;1723 if (reader.seek >= ctx.data.len) break;
1726 if (!mem.isAligned(stream.pos, 2)) stream.pos += 1;1724 if (!mem.isAligned(reader.seek, 2)) reader.seek += 1;
17271725
1728 const hdr = try reader.readStruct(elf.ar_hdr);1726 const hdr = try reader.takeStruct(elf.ar_hdr, .little);
17291727
1730 if (!mem.eql(u8, &hdr.ar_fmag, elf.ARFMAG)) return error.InvalidArchiveHeaderMagicNumber;1728 if (!mem.eql(u8, &hdr.ar_fmag, elf.ARFMAG)) return error.InvalidArchiveHeaderMagicNumber;
17311729
1732 const size = try hdr.size();1730 const size = try hdr.size();
1733 defer {1731 defer reader.seek += size;
1734 _ = stream.seekBy(size) catch {};
1735 }
17361732
1737 if (hdr.isSymtab()) {1733 if (hdr.isSymtab()) {
1738 try ctx.parseSymtab(ctx.data[stream.pos..][0..size], .p32);1734 try ctx.parseSymtab(ctx.data[reader.seek..][0..size], .p32);
1739 continue;1735 continue;
1740 }1736 }
1741 if (hdr.isSymtab64()) {1737 if (hdr.isSymtab64()) {
1742 try ctx.parseSymtab(ctx.data[stream.pos..][0..size], .p64);1738 try ctx.parseSymtab(ctx.data[reader.seek..][0..size], .p64);
1743 continue;1739 continue;
1744 }1740 }
1745 if (hdr.isStrtab()) {1741 if (hdr.isStrtab()) {
1746 ctx.strtab = ctx.data[stream.pos..][0..size];1742 ctx.strtab = ctx.data[reader.seek..][0..size];
1747 continue;1743 continue;
1748 }1744 }
1749 if (hdr.isSymdef() or hdr.isSymdefSorted()) continue;1745 if (hdr.isSymdef() or hdr.isSymdefSorted()) continue;
...@@ -1755,7 +1751,7 @@ const ElfDumper = struct {...@@ -1755,7 +1751,7 @@ const ElfDumper = struct {
1755 else1751 else
1756 unreachable;1752 unreachable;
17571753
1758 try ctx.objects.append(gpa, .{ .name = name, .off = stream.pos, .len = size });1754 try ctx.objects.append(gpa, .{ .name = name, .off = reader.seek, .len = size });
1759 }1755 }
17601756
1761 var output: std.Io.Writer.Allocating = .init(gpa);1757 var output: std.Io.Writer.Allocating = .init(gpa);
...@@ -1783,11 +1779,10 @@ const ElfDumper = struct {...@@ -1783,11 +1779,10 @@ const ElfDumper = struct {
1783 objects: std.ArrayListUnmanaged(struct { name: []const u8, off: usize, len: usize }) = .empty,1779 objects: std.ArrayListUnmanaged(struct { name: []const u8, off: usize, len: usize }) = .empty,
17841780
1785 fn parseSymtab(ctx: *ArchiveContext, raw: []const u8, ptr_width: enum { p32, p64 }) !void {1781 fn parseSymtab(ctx: *ArchiveContext, raw: []const u8, ptr_width: enum { p32, p64 }) !void {
1786 var stream = std.io.fixedBufferStream(raw);1782 var reader: std.Io.Reader = .fixed(raw);
1787 const reader = stream.reader();
1788 const num = switch (ptr_width) {1783 const num = switch (ptr_width) {
1789 .p32 => try reader.readInt(u32, .big),1784 .p32 => try reader.takeInt(u32, .big),
1790 .p64 => try reader.readInt(u64, .big),1785 .p64 => try reader.takeInt(u64, .big),
1791 };1786 };
1792 const ptr_size: usize = switch (ptr_width) {1787 const ptr_size: usize = switch (ptr_width) {
1793 .p32 => @sizeOf(u32),1788 .p32 => @sizeOf(u32),
...@@ -1802,8 +1797,8 @@ const ElfDumper = struct {...@@ -1802,8 +1797,8 @@ const ElfDumper = struct {
1802 var stroff: usize = 0;1797 var stroff: usize = 0;
1803 for (0..num) |_| {1798 for (0..num) |_| {
1804 const off = switch (ptr_width) {1799 const off = switch (ptr_width) {
1805 .p32 => try reader.readInt(u32, .big),1800 .p32 => try reader.takeInt(u32, .big),
1806 .p64 => try reader.readInt(u64, .big),1801 .p64 => try reader.takeInt(u64, .big),
1807 };1802 };
1808 const name = mem.sliceTo(@as([*:0]const u8, @ptrCast(strtab.ptr + stroff)), 0);1803 const name = mem.sliceTo(@as([*:0]const u8, @ptrCast(strtab.ptr + stroff)), 0);
1809 stroff += name.len + 1;1804 stroff += name.len + 1;
...@@ -1868,10 +1863,9 @@ const ElfDumper = struct {...@@ -1868,10 +1863,9 @@ const ElfDumper = struct {
18681863
1869 fn parseAndDumpObject(step: *Step, check: Check, bytes: []const u8) ![]const u8 {1864 fn parseAndDumpObject(step: *Step, check: Check, bytes: []const u8) ![]const u8 {
1870 const gpa = step.owner.allocator;1865 const gpa = step.owner.allocator;
1871 var stream = std.io.fixedBufferStream(bytes);1866 var reader: std.Io.Reader = .fixed(bytes);
1872 const reader = stream.reader();
18731867
1874 const hdr = try reader.readStruct(elf.Elf64_Ehdr);1868 const hdr = try reader.takeStruct(elf.Elf64_Ehdr, .little);
1875 if (!mem.eql(u8, hdr.e_ident[0..4], "\x7fELF")) {1869 if (!mem.eql(u8, hdr.e_ident[0..4], "\x7fELF")) {
1876 return error.InvalidMagicNumber;1870 return error.InvalidMagicNumber;
1877 }1871 }
...@@ -2360,10 +2354,9 @@ const WasmDumper = struct {...@@ -2360,10 +2354,9 @@ const WasmDumper = struct {
23602354
2361 fn parseAndDump(step: *Step, check: Check, bytes: []const u8) ![]const u8 {2355 fn parseAndDump(step: *Step, check: Check, bytes: []const u8) ![]const u8 {
2362 const gpa = step.owner.allocator;2356 const gpa = step.owner.allocator;
2363 var fbs = std.io.fixedBufferStream(bytes);2357 var reader: std.Io.Reader = .fixed(bytes);
2364 const reader = fbs.reader();
23652358
2366 const buf = try reader.readBytesNoEof(8);2359 const buf = try reader.takeArray(8);
2367 if (!mem.eql(u8, buf[0..4], &std.wasm.magic)) {2360 if (!mem.eql(u8, buf[0..4], &std.wasm.magic)) {
2368 return error.InvalidMagicByte;2361 return error.InvalidMagicByte;
2369 }2362 }
...@@ -2373,7 +2366,7 @@ const WasmDumper = struct {...@@ -2373,7 +2366,7 @@ const WasmDumper = struct {
23732366
2374 var output: std.Io.Writer.Allocating = .init(gpa);2367 var output: std.Io.Writer.Allocating = .init(gpa);
2375 defer output.deinit();2368 defer output.deinit();
2376 parseAndDumpInner(step, check, bytes, &fbs, &output.writer) catch |err| switch (err) {2369 parseAndDumpInner(step, check, bytes, &reader, &output.writer) catch |err| switch (err) {
2377 error.EndOfStream => try output.writer.writeAll("\n<UnexpectedEndOfStream>"),2370 error.EndOfStream => try output.writer.writeAll("\n<UnexpectedEndOfStream>"),
2378 else => |e| return e,2371 else => |e| return e,
2379 };2372 };
...@@ -2384,21 +2377,19 @@ const WasmDumper = struct {...@@ -2384,21 +2377,19 @@ const WasmDumper = struct {
2384 step: *Step,2377 step: *Step,
2385 check: Check,2378 check: Check,
2386 bytes: []const u8,2379 bytes: []const u8,
2387 fbs: *std.io.FixedBufferStream([]const u8),2380 reader: *std.Io.Reader,
2388 writer: *std.Io.Writer,2381 writer: *std.Io.Writer,
2389 ) !void {2382 ) !void {
2390 const reader = fbs.reader();
2391
2392 switch (check.kind) {2383 switch (check.kind) {
2393 .headers => {2384 .headers => {
2394 while (reader.readByte()) |current_byte| {2385 while (reader.takeByte()) |current_byte| {
2395 const section = std.enums.fromInt(std.wasm.Section, current_byte) orelse {2386 const section = std.enums.fromInt(std.wasm.Section, current_byte) orelse {
2396 return step.fail("Found invalid section id '{d}'", .{current_byte});2387 return step.fail("Found invalid section id '{d}'", .{current_byte});
2397 };2388 };
23982389
2399 const section_length = try std.leb.readUleb128(u32, reader);2390 const section_length = try reader.takeLeb128(u32);
2400 try parseAndDumpSection(step, section, bytes[fbs.pos..][0..section_length], writer);2391 try parseAndDumpSection(step, section, bytes[reader.seek..][0..section_length], writer);
2401 fbs.pos += section_length;2392 reader.seek += section_length;
2402 } else |_| {} // reached end of stream2393 } else |_| {} // reached end of stream
2403 },2394 },
24042395
...@@ -2410,10 +2401,9 @@ const WasmDumper = struct {...@@ -2410,10 +2401,9 @@ const WasmDumper = struct {
2410 step: *Step,2401 step: *Step,
2411 section: std.wasm.Section,2402 section: std.wasm.Section,
2412 data: []const u8,2403 data: []const u8,
2413 writer: anytype,2404 writer: *std.Io.Writer,
2414 ) !void {2405 ) !void {
2415 var fbs = std.io.fixedBufferStream(data);2406 var reader: std.Io.Reader = .fixed(data);
2416 const reader = fbs.reader();
24172407
2418 try writer.print(2408 try writer.print(
2419 \\Section {s}2409 \\Section {s}
...@@ -2432,31 +2422,31 @@ const WasmDumper = struct {...@@ -2432,31 +2422,31 @@ const WasmDumper = struct {
2432 .code,2422 .code,
2433 .data,2423 .data,
2434 => {2424 => {
2435 const entries = try std.leb.readUleb128(u32, reader);2425 const entries = try reader.takeLeb128(u32);
2436 try writer.print("\nentries {d}\n", .{entries});2426 try writer.print("\nentries {d}\n", .{entries});
2437 try parseSection(step, section, data[fbs.pos..], entries, writer);2427 try parseSection(step, section, data[reader.seek..], entries, writer);
2438 },2428 },
2439 .custom => {2429 .custom => {
2440 const name_length = try std.leb.readUleb128(u32, reader);2430 const name_length = try reader.takeLeb128(u32);
2441 const name = data[fbs.pos..][0..name_length];2431 const name = data[reader.seek..][0..name_length];
2442 fbs.pos += name_length;2432 reader.seek += name_length;
2443 try writer.print("\nname {s}\n", .{name});2433 try writer.print("\nname {s}\n", .{name});
24442434
2445 if (mem.eql(u8, name, "name")) {2435 if (mem.eql(u8, name, "name")) {
2446 try parseDumpNames(step, reader, writer, data);2436 try parseDumpNames(step, &reader, writer, data);
2447 } else if (mem.eql(u8, name, "producers")) {2437 } else if (mem.eql(u8, name, "producers")) {
2448 try parseDumpProducers(reader, writer, data);2438 try parseDumpProducers(&reader, writer, data);
2449 } else if (mem.eql(u8, name, "target_features")) {2439 } else if (mem.eql(u8, name, "target_features")) {
2450 try parseDumpFeatures(reader, writer, data);2440 try parseDumpFeatures(&reader, writer, data);
2451 }2441 }
2452 // TODO: Implement parsing and dumping other custom sections (such as relocations)2442 // TODO: Implement parsing and dumping other custom sections (such as relocations)
2453 },2443 },
2454 .start => {2444 .start => {
2455 const start = try std.leb.readUleb128(u32, reader);2445 const start = try reader.takeLeb128(u32);
2456 try writer.print("\nstart {d}\n", .{start});2446 try writer.print("\nstart {d}\n", .{start});
2457 },2447 },
2458 .data_count => {2448 .data_count => {
2459 const count = try std.leb.readUleb128(u32, reader);2449 const count = try reader.takeLeb128(u32);
2460 try writer.print("\ncount {d}\n", .{count});2450 try writer.print("\ncount {d}\n", .{count});
2461 },2451 },
2462 else => {}, // skip unknown sections2452 else => {}, // skip unknown sections
...@@ -2464,41 +2454,40 @@ const WasmDumper = struct {...@@ -2464,41 +2454,40 @@ const WasmDumper = struct {
2464 }2454 }
24652455
2466 fn parseSection(step: *Step, section: std.wasm.Section, data: []const u8, entries: u32, writer: anytype) !void {2456 fn parseSection(step: *Step, section: std.wasm.Section, data: []const u8, entries: u32, writer: anytype) !void {
2467 var fbs = std.io.fixedBufferStream(data);2457 var reader: std.Io.Reader = .fixed(data);
2468 const reader = fbs.reader();
24692458
2470 switch (section) {2459 switch (section) {
2471 .type => {2460 .type => {
2472 var i: u32 = 0;2461 var i: u32 = 0;
2473 while (i < entries) : (i += 1) {2462 while (i < entries) : (i += 1) {
2474 const func_type = try reader.readByte();2463 const func_type = try reader.takeByte();
2475 if (func_type != std.wasm.function_type) {2464 if (func_type != std.wasm.function_type) {
2476 return step.fail("expected function type, found byte '{d}'", .{func_type});2465 return step.fail("expected function type, found byte '{d}'", .{func_type});
2477 }2466 }
2478 const params = try std.leb.readUleb128(u32, reader);2467 const params = try reader.takeLeb128(u32);
2479 try writer.print("params {d}\n", .{params});2468 try writer.print("params {d}\n", .{params});
2480 var index: u32 = 0;2469 var index: u32 = 0;
2481 while (index < params) : (index += 1) {2470 while (index < params) : (index += 1) {
2482 _ = try parseDumpType(step, std.wasm.Valtype, reader, writer);2471 _ = try parseDumpType(step, std.wasm.Valtype, &reader, writer);
2483 } else index = 0;2472 } else index = 0;
2484 const returns = try std.leb.readUleb128(u32, reader);2473 const returns = try reader.takeLeb128(u32);
2485 try writer.print("returns {d}\n", .{returns});2474 try writer.print("returns {d}\n", .{returns});
2486 while (index < returns) : (index += 1) {2475 while (index < returns) : (index += 1) {
2487 _ = try parseDumpType(step, std.wasm.Valtype, reader, writer);2476 _ = try parseDumpType(step, std.wasm.Valtype, &reader, writer);
2488 }2477 }
2489 }2478 }
2490 },2479 },
2491 .import => {2480 .import => {
2492 var i: u32 = 0;2481 var i: u32 = 0;
2493 while (i < entries) : (i += 1) {2482 while (i < entries) : (i += 1) {
2494 const module_name_len = try std.leb.readUleb128(u32, reader);2483 const module_name_len = try reader.takeLeb128(u32);
2495 const module_name = data[fbs.pos..][0..module_name_len];2484 const module_name = data[reader.seek..][0..module_name_len];
2496 fbs.pos += module_name_len;2485 reader.seek += module_name_len;
2497 const name_len = try std.leb.readUleb128(u32, reader);2486 const name_len = try reader.takeLeb128(u32);
2498 const name = data[fbs.pos..][0..name_len];2487 const name = data[reader.seek..][0..name_len];
2499 fbs.pos += name_len;2488 reader.seek += name_len;
25002489
2501 const kind = std.enums.fromInt(std.wasm.ExternalKind, try reader.readByte()) orelse {2490 const kind = std.enums.fromInt(std.wasm.ExternalKind, try reader.takeByte()) orelse {
2502 return step.fail("invalid import kind", .{});2491 return step.fail("invalid import kind", .{});
2503 };2492 };
25042493
...@@ -2510,18 +2499,18 @@ const WasmDumper = struct {...@@ -2510,18 +2499,18 @@ const WasmDumper = struct {
2510 try writer.writeByte('\n');2499 try writer.writeByte('\n');
2511 switch (kind) {2500 switch (kind) {
2512 .function => {2501 .function => {
2513 try writer.print("index {d}\n", .{try std.leb.readUleb128(u32, reader)});2502 try writer.print("index {d}\n", .{try reader.takeLeb128(u32)});
2514 },2503 },
2515 .memory => {2504 .memory => {
2516 try parseDumpLimits(reader, writer);2505 try parseDumpLimits(&reader, writer);
2517 },2506 },
2518 .global => {2507 .global => {
2519 _ = try parseDumpType(step, std.wasm.Valtype, reader, writer);2508 _ = try parseDumpType(step, std.wasm.Valtype, &reader, writer);
2520 try writer.print("mutable {}\n", .{0x01 == try std.leb.readUleb128(u32, reader)});2509 try writer.print("mutable {}\n", .{0x01 == try reader.takeLeb128(u32)});
2521 },2510 },
2522 .table => {2511 .table => {
2523 _ = try parseDumpType(step, std.wasm.RefType, reader, writer);2512 _ = try parseDumpType(step, std.wasm.RefType, &reader, writer);
2524 try parseDumpLimits(reader, writer);2513 try parseDumpLimits(&reader, writer);
2525 },2514 },
2526 }2515 }
2527 }2516 }
...@@ -2529,41 +2518,41 @@ const WasmDumper = struct {...@@ -2529,41 +2518,41 @@ const WasmDumper = struct {
2529 .function => {2518 .function => {
2530 var i: u32 = 0;2519 var i: u32 = 0;
2531 while (i < entries) : (i += 1) {2520 while (i < entries) : (i += 1) {
2532 try writer.print("index {d}\n", .{try std.leb.readUleb128(u32, reader)});2521 try writer.print("index {d}\n", .{try reader.takeLeb128(u32)});
2533 }2522 }
2534 },2523 },
2535 .table => {2524 .table => {
2536 var i: u32 = 0;2525 var i: u32 = 0;
2537 while (i < entries) : (i += 1) {2526 while (i < entries) : (i += 1) {
2538 _ = try parseDumpType(step, std.wasm.RefType, reader, writer);2527 _ = try parseDumpType(step, std.wasm.RefType, &reader, writer);
2539 try parseDumpLimits(reader, writer);2528 try parseDumpLimits(&reader, writer);
2540 }2529 }
2541 },2530 },
2542 .memory => {2531 .memory => {
2543 var i: u32 = 0;2532 var i: u32 = 0;
2544 while (i < entries) : (i += 1) {2533 while (i < entries) : (i += 1) {
2545 try parseDumpLimits(reader, writer);2534 try parseDumpLimits(&reader, writer);
2546 }2535 }
2547 },2536 },
2548 .global => {2537 .global => {
2549 var i: u32 = 0;2538 var i: u32 = 0;
2550 while (i < entries) : (i += 1) {2539 while (i < entries) : (i += 1) {
2551 _ = try parseDumpType(step, std.wasm.Valtype, reader, writer);2540 _ = try parseDumpType(step, std.wasm.Valtype, &reader, writer);
2552 try writer.print("mutable {}\n", .{0x01 == try std.leb.readUleb128(u1, reader)});2541 try writer.print("mutable {}\n", .{0x01 == try reader.takeLeb128(u1)});
2553 try parseDumpInit(step, reader, writer);2542 try parseDumpInit(step, &reader, writer);
2554 }2543 }
2555 },2544 },
2556 .@"export" => {2545 .@"export" => {
2557 var i: u32 = 0;2546 var i: u32 = 0;
2558 while (i < entries) : (i += 1) {2547 while (i < entries) : (i += 1) {
2559 const name_len = try std.leb.readUleb128(u32, reader);2548 const name_len = try reader.takeLeb128(u32);
2560 const name = data[fbs.pos..][0..name_len];2549 const name = data[reader.seek..][0..name_len];
2561 fbs.pos += name_len;2550 reader.seek += name_len;
2562 const kind_byte = try std.leb.readUleb128(u8, reader);2551 const kind_byte = try reader.takeLeb128(u8);
2563 const kind = std.enums.fromInt(std.wasm.ExternalKind, kind_byte) orelse {2552 const kind = std.enums.fromInt(std.wasm.ExternalKind, kind_byte) orelse {
2564 return step.fail("invalid export kind value '{d}'", .{kind_byte});2553 return step.fail("invalid export kind value '{d}'", .{kind_byte});
2565 };2554 };
2566 const index = try std.leb.readUleb128(u32, reader);2555 const index = try reader.takeLeb128(u32);
2567 try writer.print(2556 try writer.print(
2568 \\name {s}2557 \\name {s}
2569 \\kind {s}2558 \\kind {s}
...@@ -2575,14 +2564,14 @@ const WasmDumper = struct {...@@ -2575,14 +2564,14 @@ const WasmDumper = struct {
2575 .element => {2564 .element => {
2576 var i: u32 = 0;2565 var i: u32 = 0;
2577 while (i < entries) : (i += 1) {2566 while (i < entries) : (i += 1) {
2578 try writer.print("table index {d}\n", .{try std.leb.readUleb128(u32, reader)});2567 try writer.print("table index {d}\n", .{try reader.takeLeb128(u32)});
2579 try parseDumpInit(step, reader, writer);2568 try parseDumpInit(step, &reader, writer);
25802569
2581 const function_indexes = try std.leb.readUleb128(u32, reader);2570 const function_indexes = try reader.takeLeb128(u32);
2582 var function_index: u32 = 0;2571 var function_index: u32 = 0;
2583 try writer.print("indexes {d}\n", .{function_indexes});2572 try writer.print("indexes {d}\n", .{function_indexes});
2584 while (function_index < function_indexes) : (function_index += 1) {2573 while (function_index < function_indexes) : (function_index += 1) {
2585 try writer.print("index {d}\n", .{try std.leb.readUleb128(u32, reader)});2574 try writer.print("index {d}\n", .{try reader.takeLeb128(u32)});
2586 }2575 }
2587 }2576 }
2588 },2577 },
...@@ -2590,27 +2579,27 @@ const WasmDumper = struct {...@@ -2590,27 +2579,27 @@ const WasmDumper = struct {
2590 .data => {2579 .data => {
2591 var i: u32 = 0;2580 var i: u32 = 0;
2592 while (i < entries) : (i += 1) {2581 while (i < entries) : (i += 1) {
2593 const flags = try std.leb.readUleb128(u32, reader);2582 const flags = try reader.takeLeb128(u32);
2594 const index = if (flags & 0x02 != 0)2583 const index = if (flags & 0x02 != 0)
2595 try std.leb.readUleb128(u32, reader)2584 try reader.takeLeb128(u32)
2596 else2585 else
2597 0;2586 0;
2598 try writer.print("memory index 0x{x}\n", .{index});2587 try writer.print("memory index 0x{x}\n", .{index});
2599 if (flags == 0) {2588 if (flags == 0) {
2600 try parseDumpInit(step, reader, writer);2589 try parseDumpInit(step, &reader, writer);
2601 }2590 }
26022591
2603 const size = try std.leb.readUleb128(u32, reader);2592 const size = try reader.takeLeb128(u32);
2604 try writer.print("size {d}\n", .{size});2593 try writer.print("size {d}\n", .{size});
2605 try reader.skipBytes(size, .{}); // we do not care about the content of the segments2594 try reader.discardAll(size); // we do not care about the content of the segments
2606 }2595 }
2607 },2596 },
2608 else => unreachable,2597 else => unreachable,
2609 }2598 }
2610 }2599 }
26112600
2612 fn parseDumpType(step: *Step, comptime E: type, reader: anytype, writer: anytype) !E {2601 fn parseDumpType(step: *Step, comptime E: type, reader: *std.Io.Reader, writer: *std.Io.Writer) !E {
2613 const byte = try reader.readByte();2602 const byte = try reader.takeByte();
2614 const tag = std.enums.fromInt(E, byte) orelse {2603 const tag = std.enums.fromInt(E, byte) orelse {
2615 return step.fail("invalid wasm type value '{d}'", .{byte});2604 return step.fail("invalid wasm type value '{d}'", .{byte});
2616 };2605 };
...@@ -2619,65 +2608,65 @@ const WasmDumper = struct {...@@ -2619,65 +2608,65 @@ const WasmDumper = struct {
2619 }2608 }
26202609
2621 fn parseDumpLimits(reader: anytype, writer: anytype) !void {2610 fn parseDumpLimits(reader: anytype, writer: anytype) !void {
2622 const flags = try std.leb.readUleb128(u8, reader);2611 const flags = try reader.takeLeb128(u8);
2623 const min = try std.leb.readUleb128(u32, reader);2612 const min = try reader.takeLeb128(u32);
26242613
2625 try writer.print("min {x}\n", .{min});2614 try writer.print("min {x}\n", .{min});
2626 if (flags != 0) {2615 if (flags != 0) {
2627 try writer.print("max {x}\n", .{try std.leb.readUleb128(u32, reader)});2616 try writer.print("max {x}\n", .{try reader.takeLeb128(u32)});
2628 }2617 }
2629 }2618 }
26302619
2631 fn parseDumpInit(step: *Step, reader: anytype, writer: anytype) !void {2620 fn parseDumpInit(step: *Step, reader: *std.Io.Reader, writer: *std.Io.Writer) !void {
2632 const byte = try reader.readByte();2621 const byte = try reader.takeByte();
2633 const opcode = std.enums.fromInt(std.wasm.Opcode, byte) orelse {2622 const opcode = std.enums.fromInt(std.wasm.Opcode, byte) orelse {
2634 return step.fail("invalid wasm opcode '{d}'", .{byte});2623 return step.fail("invalid wasm opcode '{d}'", .{byte});
2635 };2624 };
2636 switch (opcode) {2625 switch (opcode) {
2637 .i32_const => try writer.print("i32.const {x}\n", .{try std.leb.readIleb128(i32, reader)}),2626 .i32_const => try writer.print("i32.const {x}\n", .{try reader.takeLeb128(i32)}),
2638 .i64_const => try writer.print("i64.const {x}\n", .{try std.leb.readIleb128(i64, reader)}),2627 .i64_const => try writer.print("i64.const {x}\n", .{try reader.takeLeb128(i64)}),
2639 .f32_const => try writer.print("f32.const {x}\n", .{@as(f32, @bitCast(try reader.readInt(u32, .little)))}),2628 .f32_const => try writer.print("f32.const {x}\n", .{@as(f32, @bitCast(try reader.takeInt(u32, .little)))}),
2640 .f64_const => try writer.print("f64.const {x}\n", .{@as(f64, @bitCast(try reader.readInt(u64, .little)))}),2629 .f64_const => try writer.print("f64.const {x}\n", .{@as(f64, @bitCast(try reader.takeInt(u64, .little)))}),
2641 .global_get => try writer.print("global.get {x}\n", .{try std.leb.readUleb128(u32, reader)}),2630 .global_get => try writer.print("global.get {x}\n", .{try reader.takeLeb128(u32)}),
2642 else => unreachable,2631 else => unreachable,
2643 }2632 }
2644 const end_opcode = try std.leb.readUleb128(u8, reader);2633 const end_opcode = try reader.takeLeb128(u8);
2645 if (end_opcode != @intFromEnum(std.wasm.Opcode.end)) {2634 if (end_opcode != @intFromEnum(std.wasm.Opcode.end)) {
2646 return step.fail("expected 'end' opcode in init expression", .{});2635 return step.fail("expected 'end' opcode in init expression", .{});
2647 }2636 }
2648 }2637 }
26492638
2650 /// https://webassembly.github.io/spec/core/appendix/custom.html2639 /// https://webassembly.github.io/spec/core/appendix/custom.html
2651 fn parseDumpNames(step: *Step, reader: anytype, writer: anytype, data: []const u8) !void {2640 fn parseDumpNames(step: *Step, reader: *std.Io.Reader, writer: *std.Io.Writer, data: []const u8) !void {
2652 while (reader.context.pos < data.len) {2641 while (reader.seek < data.len) {
2653 switch (try parseDumpType(step, std.wasm.NameSubsection, reader, writer)) {2642 switch (try parseDumpType(step, std.wasm.NameSubsection, reader, writer)) {
2654 // The module name subsection ... consists of a single name2643 // The module name subsection ... consists of a single name
2655 // that is assigned to the module itself.2644 // that is assigned to the module itself.
2656 .module => {2645 .module => {
2657 const size = try std.leb.readUleb128(u32, reader);2646 const size = try reader.takeLeb128(u32);
2658 const name_len = try std.leb.readUleb128(u32, reader);2647 const name_len = try reader.takeLeb128(u32);
2659 if (size != name_len + 1) return error.BadSubsectionSize;2648 if (size != name_len + 1) return error.BadSubsectionSize;
2660 if (reader.context.pos + name_len > data.len) return error.UnexpectedEndOfStream;2649 if (reader.seek + name_len > data.len) return error.UnexpectedEndOfStream;
2661 try writer.print("name {s}\n", .{data[reader.context.pos..][0..name_len]});2650 try writer.print("name {s}\n", .{data[reader.seek..][0..name_len]});
2662 reader.context.pos += name_len;2651 reader.seek += name_len;
2663 },2652 },
26642653
2665 // The function name subsection ... consists of a name map2654 // The function name subsection ... consists of a name map
2666 // assigning function names to function indices.2655 // assigning function names to function indices.
2667 .function, .global, .data_segment => {2656 .function, .global, .data_segment => {
2668 const size = try std.leb.readUleb128(u32, reader);2657 const size = try reader.takeLeb128(u32);
2669 const entries = try std.leb.readUleb128(u32, reader);2658 const entries = try reader.takeLeb128(u32);
2670 try writer.print(2659 try writer.print(
2671 \\size {d}2660 \\size {d}
2672 \\names {d}2661 \\names {d}
2673 \\2662 \\
2674 , .{ size, entries });2663 , .{ size, entries });
2675 for (0..entries) |_| {2664 for (0..entries) |_| {
2676 const index = try std.leb.readUleb128(u32, reader);2665 const index = try reader.takeLeb128(u32);
2677 const name_len = try std.leb.readUleb128(u32, reader);2666 const name_len = try reader.takeLeb128(u32);
2678 if (reader.context.pos + name_len > data.len) return error.UnexpectedEndOfStream;2667 if (reader.seek + name_len > data.len) return error.UnexpectedEndOfStream;
2679 const name = data[reader.context.pos..][0..name_len];2668 const name = data[reader.seek..][0..name_len];
2680 reader.context.pos += name.len;2669 reader.seek += name.len;
26812670
2682 try writer.print(2671 try writer.print(
2683 \\index {d}2672 \\index {d}
...@@ -2699,16 +2688,16 @@ const WasmDumper = struct {...@@ -2699,16 +2688,16 @@ const WasmDumper = struct {
2699 }2688 }
2700 }2689 }
27012690
2702 fn parseDumpProducers(reader: anytype, writer: anytype, data: []const u8) !void {2691 fn parseDumpProducers(reader: *std.Io.Reader, writer: *std.Io.Writer, data: []const u8) !void {
2703 const field_count = try std.leb.readUleb128(u32, reader);2692 const field_count = try reader.takeLeb128(u32);
2704 try writer.print("fields {d}\n", .{field_count});2693 try writer.print("fields {d}\n", .{field_count});
2705 var current_field: u32 = 0;2694 var current_field: u32 = 0;
2706 while (current_field < field_count) : (current_field += 1) {2695 while (current_field < field_count) : (current_field += 1) {
2707 const field_name_length = try std.leb.readUleb128(u32, reader);2696 const field_name_length = try reader.takeLeb128(u32);
2708 const field_name = data[reader.context.pos..][0..field_name_length];2697 const field_name = data[reader.seek..][0..field_name_length];
2709 reader.context.pos += field_name_length;2698 reader.seek += field_name_length;
27102699
2711 const value_count = try std.leb.readUleb128(u32, reader);2700 const value_count = try reader.takeLeb128(u32);
2712 try writer.print(2701 try writer.print(
2713 \\field_name {s}2702 \\field_name {s}
2714 \\values {d}2703 \\values {d}
...@@ -2716,13 +2705,13 @@ const WasmDumper = struct {...@@ -2716,13 +2705,13 @@ const WasmDumper = struct {
2716 try writer.writeByte('\n');2705 try writer.writeByte('\n');
2717 var current_value: u32 = 0;2706 var current_value: u32 = 0;
2718 while (current_value < value_count) : (current_value += 1) {2707 while (current_value < value_count) : (current_value += 1) {
2719 const value_length = try std.leb.readUleb128(u32, reader);2708 const value_length = try reader.takeLeb128(u32);
2720 const value = data[reader.context.pos..][0..value_length];2709 const value = data[reader.seek..][0..value_length];
2721 reader.context.pos += value_length;2710 reader.seek += value_length;
27222711
2723 const version_length = try std.leb.readUleb128(u32, reader);2712 const version_length = try reader.takeLeb128(u32);
2724 const version = data[reader.context.pos..][0..version_length];2713 const version = data[reader.seek..][0..version_length];
2725 reader.context.pos += version_length;2714 reader.seek += version_length;
27262715
2727 try writer.print(2716 try writer.print(
2728 \\value_name {s}2717 \\value_name {s}
...@@ -2733,16 +2722,16 @@ const WasmDumper = struct {...@@ -2733,16 +2722,16 @@ const WasmDumper = struct {
2733 }2722 }
2734 }2723 }
27352724
2736 fn parseDumpFeatures(reader: anytype, writer: anytype, data: []const u8) !void {2725 fn parseDumpFeatures(reader: *std.Io.Reader, writer: *std.Io.Writer, data: []const u8) !void {
2737 const feature_count = try std.leb.readUleb128(u32, reader);2726 const feature_count = try reader.takeLeb128(u32);
2738 try writer.print("features {d}\n", .{feature_count});2727 try writer.print("features {d}\n", .{feature_count});
27392728
2740 var index: u32 = 0;2729 var index: u32 = 0;
2741 while (index < feature_count) : (index += 1) {2730 while (index < feature_count) : (index += 1) {
2742 const prefix_byte = try std.leb.readUleb128(u8, reader);2731 const prefix_byte = try reader.takeLeb128(u8);
2743 const name_length = try std.leb.readUleb128(u32, reader);2732 const name_length = try reader.takeLeb128(u32);
2744 const feature_name = data[reader.context.pos..][0..name_length];2733 const feature_name = data[reader.seek..][0..name_length];
2745 reader.context.pos += name_length;2734 reader.seek += name_length;
27462735
2747 try writer.print("{c} {s}\n", .{ prefix_byte, feature_name });2736 try writer.print("{c} {s}\n", .{ prefix_byte, feature_name });
2748 }2737 }
lib/std/Build/Step/Compile.zig+1-1
...@@ -2021,7 +2021,7 @@ fn checkCompileErrors(compile: *Compile) !void {...@@ -2021,7 +2021,7 @@ fn checkCompileErrors(compile: *Compile) !void {
2021 const arena = compile.step.owner.allocator;2021 const arena = compile.step.owner.allocator;
20222022
2023 const actual_errors = ae: {2023 const actual_errors = ae: {
2024 var aw: std.io.Writer.Allocating = .init(arena);2024 var aw: std.Io.Writer.Allocating = .init(arena);
2025 defer aw.deinit();2025 defer aw.deinit();
2026 try actual_eb.renderToWriter(.{2026 try actual_eb.renderToWriter(.{
2027 .ttyconf = .no_color,2027 .ttyconf = .no_color,
lib/std/Build/Step/ConfigHeader.zig+6-6
...@@ -2,7 +2,7 @@ const std = @import("std");...@@ -2,7 +2,7 @@ const std = @import("std");
2const ConfigHeader = @This();2const ConfigHeader = @This();
3const Step = std.Build.Step;3const Step = std.Build.Step;
4const Allocator = std.mem.Allocator;4const Allocator = std.mem.Allocator;
5const Writer = std.io.Writer;5const Writer = std.Io.Writer;
66
7pub const Style = union(enum) {7pub const Style = union(enum) {
8 /// A configure format supported by autotools that uses `#undef foo` to8 /// A configure format supported by autotools that uses `#undef foo` to
...@@ -196,7 +196,7 @@ fn make(step: *Step, options: Step.MakeOptions) !void {...@@ -196,7 +196,7 @@ fn make(step: *Step, options: Step.MakeOptions) !void {
196 man.hash.addBytes(config_header.include_path);196 man.hash.addBytes(config_header.include_path);
197 man.hash.addOptionalBytes(config_header.include_guard_override);197 man.hash.addOptionalBytes(config_header.include_guard_override);
198198
199 var aw: std.io.Writer.Allocating = .init(gpa);199 var aw: Writer.Allocating = .init(gpa);
200 defer aw.deinit();200 defer aw.deinit();
201 const bw = &aw.writer;201 const bw = &aw.writer;
202202
...@@ -208,7 +208,7 @@ fn make(step: *Step, options: Step.MakeOptions) !void {...@@ -208,7 +208,7 @@ fn make(step: *Step, options: Step.MakeOptions) !void {
208 .autoconf_undef, .autoconf_at => |file_source| {208 .autoconf_undef, .autoconf_at => |file_source| {
209 try bw.writeAll(c_generated_line);209 try bw.writeAll(c_generated_line);
210 const src_path = file_source.getPath2(b, step);210 const src_path = file_source.getPath2(b, step);
211 const contents = std.fs.cwd().readFileAlloc(arena, src_path, config_header.max_bytes) catch |err| {211 const contents = std.fs.cwd().readFileAlloc(src_path, arena, .limited(config_header.max_bytes)) catch |err| {
212 return step.fail("unable to read autoconf input file '{s}': {s}", .{212 return step.fail("unable to read autoconf input file '{s}': {s}", .{
213 src_path, @errorName(err),213 src_path, @errorName(err),
214 });214 });
...@@ -222,7 +222,7 @@ fn make(step: *Step, options: Step.MakeOptions) !void {...@@ -222,7 +222,7 @@ fn make(step: *Step, options: Step.MakeOptions) !void {
222 .cmake => |file_source| {222 .cmake => |file_source| {
223 try bw.writeAll(c_generated_line);223 try bw.writeAll(c_generated_line);
224 const src_path = file_source.getPath2(b, step);224 const src_path = file_source.getPath2(b, step);
225 const contents = std.fs.cwd().readFileAlloc(arena, src_path, config_header.max_bytes) catch |err| {225 const contents = std.fs.cwd().readFileAlloc(src_path, arena, .limited(config_header.max_bytes)) catch |err| {
226 return step.fail("unable to read cmake input file '{s}': {s}", .{226 return step.fail("unable to read cmake input file '{s}': {s}", .{
227 src_path, @errorName(err),227 src_path, @errorName(err),
228 });228 });
...@@ -329,7 +329,7 @@ fn render_autoconf_undef(...@@ -329,7 +329,7 @@ fn render_autoconf_undef(
329fn render_autoconf_at(329fn render_autoconf_at(
330 step: *Step,330 step: *Step,
331 contents: []const u8,331 contents: []const u8,
332 aw: *std.io.Writer.Allocating,332 aw: *Writer.Allocating,
333 values: std.StringArrayHashMap(Value),333 values: std.StringArrayHashMap(Value),
334 src_path: []const u8,334 src_path: []const u8,
335) !void {335) !void {
...@@ -753,7 +753,7 @@ fn testReplaceVariablesAutoconfAt(...@@ -753,7 +753,7 @@ fn testReplaceVariablesAutoconfAt(
753 expected: []const u8,753 expected: []const u8,
754 values: std.StringArrayHashMap(Value),754 values: std.StringArrayHashMap(Value),
755) !void {755) !void {
756 var aw: std.io.Writer.Allocating = .init(allocator);756 var aw: Writer.Allocating = .init(allocator);
757 defer aw.deinit();757 defer aw.deinit();
758758
759 const used = try allocator.alloc(bool, values.count());759 const used = try allocator.alloc(bool, values.count());
lib/std/Build/Step/ObjCopy.zig-1
...@@ -9,7 +9,6 @@ const InstallDir = std.Build.InstallDir;...@@ -9,7 +9,6 @@ const InstallDir = std.Build.InstallDir;
9const Step = std.Build.Step;9const Step = std.Build.Step;
10const elf = std.elf;10const elf = std.elf;
11const fs = std.fs;11const fs = std.fs;
12const io = std.io;
13const sort = std.sort;12const sort = std.sort;
1413
15pub const base_id: Step.Id = .objcopy;14pub const base_id: Step.Id = .objcopy;
lib/std/Build/WebServer.zig+4-4
...@@ -3,7 +3,7 @@ thread_pool: *std.Thread.Pool,...@@ -3,7 +3,7 @@ thread_pool: *std.Thread.Pool,
3graph: *const Build.Graph,3graph: *const Build.Graph,
4all_steps: []const *Build.Step,4all_steps: []const *Build.Step,
5listen_address: std.net.Address,5listen_address: std.net.Address,
6ttyconf: std.io.tty.Config,6ttyconf: std.Io.tty.Config,
7root_prog_node: std.Progress.Node,7root_prog_node: std.Progress.Node,
8watch: bool,8watch: bool,
99
...@@ -53,7 +53,7 @@ pub const Options = struct {...@@ -53,7 +53,7 @@ pub const Options = struct {
53 thread_pool: *std.Thread.Pool,53 thread_pool: *std.Thread.Pool,
54 graph: *const std.Build.Graph,54 graph: *const std.Build.Graph,
55 all_steps: []const *Build.Step,55 all_steps: []const *Build.Step,
56 ttyconf: std.io.tty.Config,56 ttyconf: std.Io.tty.Config,
57 root_prog_node: std.Progress.Node,57 root_prog_node: std.Progress.Node,
58 watch: bool,58 watch: bool,
59 listen_address: std.net.Address,59 listen_address: std.net.Address,
...@@ -446,7 +446,7 @@ pub fn serveFile(...@@ -446,7 +446,7 @@ pub fn serveFile(
446 // The desired API is actually sendfile, which will require enhancing http.Server.446 // The desired API is actually sendfile, which will require enhancing http.Server.
447 // We load the file with every request so that the user can make changes to the file447 // We load the file with every request so that the user can make changes to the file
448 // and refresh the HTML page without restarting this server.448 // and refresh the HTML page without restarting this server.
449 const file_contents = path.root_dir.handle.readFileAlloc(gpa, path.sub_path, 10 * 1024 * 1024) catch |err| {449 const file_contents = path.root_dir.handle.readFileAlloc(path.sub_path, gpa, .limited(10 * 1024 * 1024)) catch |err| {
450 log.err("failed to read '{f}': {s}", .{ path, @errorName(err) });450 log.err("failed to read '{f}': {s}", .{ path, @errorName(err) });
451 return error.AlreadyReported;451 return error.AlreadyReported;
452 };452 };
...@@ -557,7 +557,7 @@ fn buildClientWasm(ws: *WebServer, arena: Allocator, optimize: std.builtin.Optim...@@ -557,7 +557,7 @@ fn buildClientWasm(ws: *WebServer, arena: Allocator, optimize: std.builtin.Optim
557 child.stderr_behavior = .Pipe;557 child.stderr_behavior = .Pipe;
558 try child.spawn();558 try child.spawn();
559559
560 var poller = std.io.poll(gpa, enum { stdout, stderr }, .{560 var poller = std.Io.poll(gpa, enum { stdout, stderr }, .{
561 .stdout = child.stdout.?,561 .stdout = child.stdout.?,
562 .stderr = child.stderr.?,562 .stderr = child.stderr.?,
563 });563 });
lib/std/Io.zig-197
...@@ -82,202 +82,6 @@ pub const Limit = enum(usize) {...@@ -82,202 +82,6 @@ pub const Limit = enum(usize) {
82pub const Reader = @import("Io/Reader.zig");82pub const Reader = @import("Io/Reader.zig");
83pub const Writer = @import("Io/Writer.zig");83pub const Writer = @import("Io/Writer.zig");
8484
85/// Deprecated in favor of `Reader`.
86pub fn GenericReader(
87 comptime Context: type,
88 comptime ReadError: type,
89 /// Returns the number of bytes read. It may be less than buffer.len.
90 /// If the number of bytes read is 0, it means end of stream.
91 /// End of stream is not an error condition.
92 comptime readFn: fn (context: Context, buffer: []u8) ReadError!usize,
93) type {
94 return struct {
95 context: Context,
96
97 pub const Error = ReadError;
98 pub const NoEofError = ReadError || error{
99 EndOfStream,
100 };
101
102 pub inline fn read(self: Self, buffer: []u8) Error!usize {
103 return readFn(self.context, buffer);
104 }
105
106 pub inline fn readAll(self: Self, buffer: []u8) Error!usize {
107 return @errorCast(self.any().readAll(buffer));
108 }
109
110 pub inline fn readAtLeast(self: Self, buffer: []u8, len: usize) Error!usize {
111 return @errorCast(self.any().readAtLeast(buffer, len));
112 }
113
114 pub inline fn readNoEof(self: Self, buf: []u8) NoEofError!void {
115 return @errorCast(self.any().readNoEof(buf));
116 }
117
118 pub inline fn readAllArrayList(
119 self: Self,
120 array_list: *std.array_list.Managed(u8),
121 max_append_size: usize,
122 ) (error{StreamTooLong} || Allocator.Error || Error)!void {
123 return @errorCast(self.any().readAllArrayList(array_list, max_append_size));
124 }
125
126 pub inline fn readAllArrayListAligned(
127 self: Self,
128 comptime alignment: ?Alignment,
129 array_list: *std.array_list.AlignedManaged(u8, alignment),
130 max_append_size: usize,
131 ) (error{StreamTooLong} || Allocator.Error || Error)!void {
132 return @errorCast(self.any().readAllArrayListAligned(
133 alignment,
134 array_list,
135 max_append_size,
136 ));
137 }
138
139 pub inline fn readAllAlloc(
140 self: Self,
141 allocator: Allocator,
142 max_size: usize,
143 ) (Error || Allocator.Error || error{StreamTooLong})![]u8 {
144 return @errorCast(self.any().readAllAlloc(allocator, max_size));
145 }
146
147 pub inline fn streamUntilDelimiter(
148 self: Self,
149 writer: anytype,
150 delimiter: u8,
151 optional_max_size: ?usize,
152 ) (NoEofError || error{StreamTooLong} || @TypeOf(writer).Error)!void {
153 return @errorCast(self.any().streamUntilDelimiter(
154 writer,
155 delimiter,
156 optional_max_size,
157 ));
158 }
159
160 pub inline fn skipUntilDelimiterOrEof(self: Self, delimiter: u8) Error!void {
161 return @errorCast(self.any().skipUntilDelimiterOrEof(delimiter));
162 }
163
164 pub inline fn readByte(self: Self) NoEofError!u8 {
165 return @errorCast(self.any().readByte());
166 }
167
168 pub inline fn readByteSigned(self: Self) NoEofError!i8 {
169 return @errorCast(self.any().readByteSigned());
170 }
171
172 pub inline fn readBytesNoEof(
173 self: Self,
174 comptime num_bytes: usize,
175 ) NoEofError![num_bytes]u8 {
176 return @errorCast(self.any().readBytesNoEof(num_bytes));
177 }
178
179 pub inline fn readInt(self: Self, comptime T: type, endian: std.builtin.Endian) NoEofError!T {
180 return @errorCast(self.any().readInt(T, endian));
181 }
182
183 pub inline fn readVarInt(
184 self: Self,
185 comptime ReturnType: type,
186 endian: std.builtin.Endian,
187 size: usize,
188 ) NoEofError!ReturnType {
189 return @errorCast(self.any().readVarInt(ReturnType, endian, size));
190 }
191
192 pub const SkipBytesOptions = AnyReader.SkipBytesOptions;
193
194 pub inline fn skipBytes(
195 self: Self,
196 num_bytes: u64,
197 comptime options: SkipBytesOptions,
198 ) NoEofError!void {
199 return @errorCast(self.any().skipBytes(num_bytes, options));
200 }
201
202 pub inline fn isBytes(self: Self, slice: []const u8) NoEofError!bool {
203 return @errorCast(self.any().isBytes(slice));
204 }
205
206 pub inline fn readStruct(self: Self, comptime T: type) NoEofError!T {
207 return @errorCast(self.any().readStruct(T));
208 }
209
210 pub inline fn readStructEndian(self: Self, comptime T: type, endian: std.builtin.Endian) NoEofError!T {
211 return @errorCast(self.any().readStructEndian(T, endian));
212 }
213
214 pub const ReadEnumError = NoEofError || error{
215 /// An integer was read, but it did not match any of the tags in the supplied enum.
216 InvalidValue,
217 };
218
219 pub inline fn readEnum(
220 self: Self,
221 comptime Enum: type,
222 endian: std.builtin.Endian,
223 ) ReadEnumError!Enum {
224 return @errorCast(self.any().readEnum(Enum, endian));
225 }
226
227 pub inline fn any(self: *const Self) AnyReader {
228 return .{
229 .context = @ptrCast(&self.context),
230 .readFn = typeErasedReadFn,
231 };
232 }
233
234 const Self = @This();
235
236 fn typeErasedReadFn(context: *const anyopaque, buffer: []u8) anyerror!usize {
237 const ptr: *const Context = @ptrCast(@alignCast(context));
238 return readFn(ptr.*, buffer);
239 }
240
241 /// Helper for bridging to the new `Reader` API while upgrading.
242 pub fn adaptToNewApi(self: *const Self, buffer: []u8) Adapter {
243 return .{
244 .derp_reader = self.*,
245 .new_interface = .{
246 .buffer = buffer,
247 .vtable = &.{ .stream = Adapter.stream },
248 .seek = 0,
249 .end = 0,
250 },
251 };
252 }
253
254 pub const Adapter = struct {
255 derp_reader: Self,
256 new_interface: Reader,
257 err: ?Error = null,
258
259 fn stream(r: *Reader, w: *Writer, limit: Limit) Reader.StreamError!usize {
260 const a: *@This() = @alignCast(@fieldParentPtr("new_interface", r));
261 const buf = limit.slice(try w.writableSliceGreedy(1));
262 const n = a.derp_reader.read(buf) catch |err| {
263 a.err = err;
264 return error.ReadFailed;
265 };
266 if (n == 0) return error.EndOfStream;
267 w.advance(n);
268 return n;
269 }
270 };
271 };
272}
273
274/// Deprecated in favor of `Reader`.
275pub const AnyReader = @import("Io/DeprecatedReader.zig");
276/// Deprecated in favor of `Reader`.
277pub const FixedBufferStream = @import("Io/fixed_buffer_stream.zig").FixedBufferStream;
278/// Deprecated in favor of `Reader`.
279pub const fixedBufferStream = @import("Io/fixed_buffer_stream.zig").fixedBufferStream;
280
281pub const tty = @import("Io/tty.zig");85pub const tty = @import("Io/tty.zig");
28286
283pub fn poll(87pub fn poll(
...@@ -746,7 +550,6 @@ pub fn PollFiles(comptime StreamEnum: type) type {...@@ -746,7 +550,6 @@ pub fn PollFiles(comptime StreamEnum: type) type {
746test {550test {
747 _ = Reader;551 _ = Reader;
748 _ = Writer;552 _ = Writer;
749 _ = FixedBufferStream;
750 _ = tty;553 _ = tty;
751 _ = @import("Io/test.zig");554 _ = @import("Io/test.zig");
752}555}
lib/std/Io/DeprecatedReader.zig deleted-292
...@@ -1,292 +0,0 @@
1context: *const anyopaque,
2readFn: *const fn (context: *const anyopaque, buffer: []u8) anyerror!usize,
3
4pub const Error = anyerror;
5
6/// Returns the number of bytes read. It may be less than buffer.len.
7/// If the number of bytes read is 0, it means end of stream.
8/// End of stream is not an error condition.
9pub fn read(self: Self, buffer: []u8) anyerror!usize {
10 return self.readFn(self.context, buffer);
11}
12
13/// Returns the number of bytes read. If the number read is smaller than `buffer.len`, it
14/// means the stream reached the end. Reaching the end of a stream is not an error
15/// condition.
16pub fn readAll(self: Self, buffer: []u8) anyerror!usize {
17 return readAtLeast(self, buffer, buffer.len);
18}
19
20/// Returns the number of bytes read, calling the underlying read
21/// function the minimal number of times until the buffer has at least
22/// `len` bytes filled. If the number read is less than `len` it means
23/// the stream reached the end. Reaching the end of the stream is not
24/// an error condition.
25pub fn readAtLeast(self: Self, buffer: []u8, len: usize) anyerror!usize {
26 assert(len <= buffer.len);
27 var index: usize = 0;
28 while (index < len) {
29 const amt = try self.read(buffer[index..]);
30 if (amt == 0) break;
31 index += amt;
32 }
33 return index;
34}
35
36/// If the number read would be smaller than `buf.len`, `error.EndOfStream` is returned instead.
37pub fn readNoEof(self: Self, buf: []u8) anyerror!void {
38 const amt_read = try self.readAll(buf);
39 if (amt_read < buf.len) return error.EndOfStream;
40}
41
42/// Appends to the `std.array_list.Managed` contents by reading from the stream
43/// until end of stream is found.
44/// If the number of bytes appended would exceed `max_append_size`,
45/// `error.StreamTooLong` is returned
46/// and the `std.array_list.Managed` has exactly `max_append_size` bytes appended.
47pub fn readAllArrayList(
48 self: Self,
49 array_list: *std.array_list.Managed(u8),
50 max_append_size: usize,
51) anyerror!void {
52 return self.readAllArrayListAligned(null, array_list, max_append_size);
53}
54
55pub fn readAllArrayListAligned(
56 self: Self,
57 comptime alignment: ?Alignment,
58 array_list: *std.array_list.AlignedManaged(u8, alignment),
59 max_append_size: usize,
60) anyerror!void {
61 try array_list.ensureTotalCapacity(@min(max_append_size, 4096));
62 const original_len = array_list.items.len;
63 var start_index: usize = original_len;
64 while (true) {
65 array_list.expandToCapacity();
66 const dest_slice = array_list.items[start_index..];
67 const bytes_read = try self.readAll(dest_slice);
68 start_index += bytes_read;
69
70 if (start_index - original_len > max_append_size) {
71 array_list.shrinkAndFree(original_len + max_append_size);
72 return error.StreamTooLong;
73 }
74
75 if (bytes_read != dest_slice.len) {
76 array_list.shrinkAndFree(start_index);
77 return;
78 }
79
80 // This will trigger ArrayList to expand superlinearly at whatever its growth rate is.
81 try array_list.ensureTotalCapacity(start_index + 1);
82 }
83}
84
85/// Allocates enough memory to hold all the contents of the stream. If the allocated
86/// memory would be greater than `max_size`, returns `error.StreamTooLong`.
87/// Caller owns returned memory.
88/// If this function returns an error, the contents from the stream read so far are lost.
89pub fn readAllAlloc(self: Self, allocator: mem.Allocator, max_size: usize) anyerror![]u8 {
90 var array_list = std.array_list.Managed(u8).init(allocator);
91 defer array_list.deinit();
92 try self.readAllArrayList(&array_list, max_size);
93 return try array_list.toOwnedSlice();
94}
95
96/// Appends to the `writer` contents by reading from the stream until `delimiter` is found.
97/// Does not write the delimiter itself.
98/// If `optional_max_size` is not null and amount of written bytes exceeds `optional_max_size`,
99/// returns `error.StreamTooLong` and finishes appending.
100/// If `optional_max_size` is null, appending is unbounded.
101pub fn streamUntilDelimiter(
102 self: Self,
103 writer: anytype,
104 delimiter: u8,
105 optional_max_size: ?usize,
106) anyerror!void {
107 if (optional_max_size) |max_size| {
108 for (0..max_size) |_| {
109 const byte: u8 = try self.readByte();
110 if (byte == delimiter) return;
111 try writer.writeByte(byte);
112 }
113 return error.StreamTooLong;
114 } else {
115 while (true) {
116 const byte: u8 = try self.readByte();
117 if (byte == delimiter) return;
118 try writer.writeByte(byte);
119 }
120 // Can not throw `error.StreamTooLong` since there are no boundary.
121 }
122}
123
124/// Reads from the stream until specified byte is found, discarding all data,
125/// including the delimiter.
126/// If end-of-stream is found, this function succeeds.
127pub fn skipUntilDelimiterOrEof(self: Self, delimiter: u8) anyerror!void {
128 while (true) {
129 const byte = self.readByte() catch |err| switch (err) {
130 error.EndOfStream => return,
131 else => |e| return e,
132 };
133 if (byte == delimiter) return;
134 }
135}
136
137/// Reads 1 byte from the stream or returns `error.EndOfStream`.
138pub fn readByte(self: Self) anyerror!u8 {
139 var result: [1]u8 = undefined;
140 const amt_read = try self.read(result[0..]);
141 if (amt_read < 1) return error.EndOfStream;
142 return result[0];
143}
144
145/// Same as `readByte` except the returned byte is signed.
146pub fn readByteSigned(self: Self) anyerror!i8 {
147 return @as(i8, @bitCast(try self.readByte()));
148}
149
150/// Reads exactly `num_bytes` bytes and returns as an array.
151/// `num_bytes` must be comptime-known
152pub fn readBytesNoEof(self: Self, comptime num_bytes: usize) anyerror![num_bytes]u8 {
153 var bytes: [num_bytes]u8 = undefined;
154 try self.readNoEof(&bytes);
155 return bytes;
156}
157
158pub inline fn readInt(self: Self, comptime T: type, endian: std.builtin.Endian) anyerror!T {
159 const bytes = try self.readBytesNoEof(@divExact(@typeInfo(T).int.bits, 8));
160 return mem.readInt(T, &bytes, endian);
161}
162
163pub fn readVarInt(
164 self: Self,
165 comptime ReturnType: type,
166 endian: std.builtin.Endian,
167 size: usize,
168) anyerror!ReturnType {
169 assert(size <= @sizeOf(ReturnType));
170 var bytes_buf: [@sizeOf(ReturnType)]u8 = undefined;
171 const bytes = bytes_buf[0..size];
172 try self.readNoEof(bytes);
173 return mem.readVarInt(ReturnType, bytes, endian);
174}
175
176/// Optional parameters for `skipBytes`
177pub const SkipBytesOptions = struct {
178 buf_size: usize = 512,
179};
180
181// `num_bytes` is a `u64` to match `off_t`
182/// Reads `num_bytes` bytes from the stream and discards them
183pub fn skipBytes(self: Self, num_bytes: u64, comptime options: SkipBytesOptions) anyerror!void {
184 var buf: [options.buf_size]u8 = undefined;
185 var remaining = num_bytes;
186
187 while (remaining > 0) {
188 const amt = @min(remaining, options.buf_size);
189 try self.readNoEof(buf[0..amt]);
190 remaining -= amt;
191 }
192}
193
194/// Reads `slice.len` bytes from the stream and returns if they are the same as the passed slice
195pub fn isBytes(self: Self, slice: []const u8) anyerror!bool {
196 var i: usize = 0;
197 var matches = true;
198 while (i < slice.len) : (i += 1) {
199 if (slice[i] != try self.readByte()) {
200 matches = false;
201 }
202 }
203 return matches;
204}
205
206pub fn readStruct(self: Self, comptime T: type) anyerror!T {
207 // Only extern and packed structs have defined in-memory layout.
208 comptime assert(@typeInfo(T).@"struct".layout != .auto);
209 var res: [1]T = undefined;
210 try self.readNoEof(mem.sliceAsBytes(res[0..]));
211 return res[0];
212}
213
214pub fn readStructEndian(self: Self, comptime T: type, endian: std.builtin.Endian) anyerror!T {
215 var res = try self.readStruct(T);
216 if (native_endian != endian) {
217 mem.byteSwapAllFields(T, &res);
218 }
219 return res;
220}
221
222/// Reads an integer with the same size as the given enum's tag type. If the integer matches
223/// an enum tag, casts the integer to the enum tag and returns it. Otherwise, returns an `error.InvalidValue`.
224/// TODO optimization taking advantage of most fields being in order
225pub fn readEnum(self: Self, comptime Enum: type, endian: std.builtin.Endian) anyerror!Enum {
226 const E = error{
227 /// An integer was read, but it did not match any of the tags in the supplied enum.
228 InvalidValue,
229 };
230 const type_info = @typeInfo(Enum).@"enum";
231 const tag = try self.readInt(type_info.tag_type, endian);
232
233 inline for (std.meta.fields(Enum)) |field| {
234 if (tag == field.value) {
235 return @field(Enum, field.name);
236 }
237 }
238
239 return E.InvalidValue;
240}
241
242/// Reads the stream until the end, ignoring all the data.
243/// Returns the number of bytes discarded.
244pub fn discard(self: Self) anyerror!u64 {
245 var trash: [4096]u8 = undefined;
246 var index: u64 = 0;
247 while (true) {
248 const n = try self.read(&trash);
249 if (n == 0) return index;
250 index += n;
251 }
252}
253
254/// Helper for bridging to the new `Reader` API while upgrading.
255pub fn adaptToNewApi(self: *const Self, buffer: []u8) Adapter {
256 return .{
257 .derp_reader = self.*,
258 .new_interface = .{
259 .buffer = buffer,
260 .vtable = &.{ .stream = Adapter.stream },
261 .seek = 0,
262 .end = 0,
263 },
264 };
265}
266
267pub const Adapter = struct {
268 derp_reader: Self,
269 new_interface: std.io.Reader,
270 err: ?Error = null,
271
272 fn stream(r: *std.io.Reader, w: *std.io.Writer, limit: std.io.Limit) std.io.Reader.StreamError!usize {
273 const a: *@This() = @alignCast(@fieldParentPtr("new_interface", r));
274 const buf = limit.slice(try w.writableSliceGreedy(1));
275 const n = a.derp_reader.read(buf) catch |err| {
276 a.err = err;
277 return error.ReadFailed;
278 };
279 if (n == 0) return error.EndOfStream;
280 w.advance(n);
281 return n;
282 }
283};
284
285const std = @import("../std.zig");
286const Self = @This();
287const math = std.math;
288const assert = std.debug.assert;
289const mem = std.mem;
290const testing = std.testing;
291const native_endian = @import("builtin").target.cpu.arch.endian();
292const Alignment = std.mem.Alignment;
lib/std/Io/Reader.zig+132-21
...@@ -4,12 +4,12 @@ const builtin = @import("builtin");...@@ -4,12 +4,12 @@ const builtin = @import("builtin");
4const native_endian = builtin.target.cpu.arch.endian();4const native_endian = builtin.target.cpu.arch.endian();
55
6const std = @import("../std.zig");6const std = @import("../std.zig");
7const Writer = std.io.Writer;7const Writer = std.Io.Writer;
8const Limit = std.Io.Limit;
8const assert = std.debug.assert;9const assert = std.debug.assert;
9const testing = std.testing;10const testing = std.testing;
10const Allocator = std.mem.Allocator;11const Allocator = std.mem.Allocator;
11const ArrayList = std.ArrayList;12const ArrayList = std.ArrayList;
12const Limit = std.io.Limit;
1313
14pub const Limited = @import("Reader/Limited.zig");14pub const Limited = @import("Reader/Limited.zig");
1515
...@@ -292,6 +292,23 @@ pub fn allocRemaining(r: *Reader, gpa: Allocator, limit: Limit) LimitedAllocErro...@@ -292,6 +292,23 @@ pub fn allocRemaining(r: *Reader, gpa: Allocator, limit: Limit) LimitedAllocErro
292 return buffer.toOwnedSlice(gpa);292 return buffer.toOwnedSlice(gpa);
293}293}
294294
295pub fn allocRemainingAlignedSentinel(
296 r: *Reader,
297 gpa: Allocator,
298 limit: Limit,
299 comptime alignment: std.mem.Alignment,
300 comptime sentinel: ?u8,
301) LimitedAllocError!(if (sentinel) |s| [:s]align(alignment.toByteUnits()) u8 else []align(alignment.toByteUnits()) u8) {
302 var buffer: std.array_list.Aligned(u8, alignment) = .empty;
303 defer buffer.deinit(gpa);
304 try appendRemainingAligned(r, gpa, alignment, &buffer, limit);
305 if (sentinel) |s| {
306 return buffer.toOwnedSliceSentinel(gpa, s);
307 } else {
308 return buffer.toOwnedSlice(gpa);
309 }
310}
311
295/// Transfers all bytes from the current position to the end of the stream, up312/// Transfers all bytes from the current position to the end of the stream, up
296/// to `limit`, appending them to `list`.313/// to `limit`, appending them to `list`.
297///314///
...@@ -308,15 +325,30 @@ pub fn appendRemaining(...@@ -308,15 +325,30 @@ pub fn appendRemaining(
308 list: *ArrayList(u8),325 list: *ArrayList(u8),
309 limit: Limit,326 limit: Limit,
310) LimitedAllocError!void {327) LimitedAllocError!void {
311 var a: std.Io.Writer.Allocating = .initOwnedSlice(gpa, list.allocatedSlice());328 return appendRemainingAligned(r, gpa, .of(u8), list, limit);
312 a.writer.end = list.items.len;329}
313 list.* = .empty;330
314 defer {331/// Transfers all bytes from the current position to the end of the stream, up
315 list.* = .{332/// to `limit`, appending them to `list`.
316 .items = a.writer.buffer[0..a.writer.end],333///
317 .capacity = a.writer.buffer.len,334/// If `limit` is reached or exceeded, `error.StreamTooLong` is returned
318 };335/// instead. In such case, the next byte that would be read will be the first
319 }336/// one to exceed `limit`, and all preceeding bytes have been appended to
337/// `list`.
338///
339/// See also:
340/// * `appendRemaining`
341/// * `allocRemainingAligned`
342pub fn appendRemainingAligned(
343 r: *Reader,
344 gpa: Allocator,
345 comptime alignment: std.mem.Alignment,
346 list: *std.array_list.Aligned(u8, alignment),
347 limit: Limit,
348) LimitedAllocError!void {
349 var a = std.Io.Writer.Allocating.fromArrayListAligned(gpa, alignment, list);
350 defer list.* = a.toArrayListAligned(alignment);
351
320 var remaining = limit;352 var remaining = limit;
321 while (remaining.nonzero()) {353 while (remaining.nonzero()) {
322 const n = stream(r, &a.writer, remaining) catch |err| switch (err) {354 const n = stream(r, &a.writer, remaining) catch |err| switch (err) {
...@@ -1584,7 +1616,7 @@ test readVec {...@@ -1584,7 +1616,7 @@ test readVec {
1584test "expected error.EndOfStream" {1616test "expected error.EndOfStream" {
1585 // Unit test inspired by https://github.com/ziglang/zig/issues/177331617 // Unit test inspired by https://github.com/ziglang/zig/issues/17733
1586 var buffer: [3]u8 = undefined;1618 var buffer: [3]u8 = undefined;
1587 var r: std.io.Reader = .fixed(&buffer);1619 var r: std.Io.Reader = .fixed(&buffer);
1588 r.end = 0; // capacity 3, but empty1620 r.end = 0; // capacity 3, but empty
1589 try std.testing.expectError(error.EndOfStream, r.takeEnum(enum(u8) { a, b }, .little));1621 try std.testing.expectError(error.EndOfStream, r.takeEnum(enum(u8) { a, b }, .little));
1590 try std.testing.expectError(error.EndOfStream, r.take(3));1622 try std.testing.expectError(error.EndOfStream, r.take(3));
...@@ -1639,15 +1671,6 @@ fn failingDiscard(r: *Reader, limit: Limit) Error!usize {...@@ -1639,15 +1671,6 @@ fn failingDiscard(r: *Reader, limit: Limit) Error!usize {
1639 return error.ReadFailed;1671 return error.ReadFailed;
1640}1672}
16411673
1642pub fn adaptToOldInterface(r: *Reader) std.Io.AnyReader {
1643 return .{ .context = r, .readFn = derpRead };
1644}
1645
1646fn derpRead(context: *const anyopaque, buffer: []u8) anyerror!usize {
1647 const r: *Reader = @ptrCast(@alignCast(@constCast(context)));
1648 return r.readSliceShort(buffer);
1649}
1650
1651test "readAlloc when the backing reader provides one byte at a time" {1674test "readAlloc when the backing reader provides one byte at a time" {
1652 const str = "This is a test";1675 const str = "This is a test";
1653 var tiny_buffer: [1]u8 = undefined;1676 var tiny_buffer: [1]u8 = undefined;
...@@ -1870,6 +1893,94 @@ pub fn writableVector(r: *Reader, buffer: [][]u8, data: []const []u8) Error!stru...@@ -1870,6 +1893,94 @@ pub fn writableVector(r: *Reader, buffer: [][]u8, data: []const []u8) Error!stru
1870 return .{ i, n };1893 return .{ i, n };
1871}1894}
18721895
1896test "deserialize signed LEB128" {
1897 // Truncated
1898 try testing.expectError(error.EndOfStream, testLeb128(i64, "\x80"));
1899
1900 // Overflow
1901 try testing.expectError(error.Overflow, testLeb128(i8, "\x80\x80\x40"));
1902 try testing.expectError(error.Overflow, testLeb128(i16, "\x80\x80\x80\x40"));
1903 try testing.expectError(error.Overflow, testLeb128(i32, "\x80\x80\x80\x80\x40"));
1904 try testing.expectError(error.Overflow, testLeb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x40"));
1905 try testing.expectError(error.Overflow, testLeb128(i8, "\xff\x7e"));
1906 try testing.expectError(error.Overflow, testLeb128(i32, "\x80\x80\x80\x80\x08"));
1907 try testing.expectError(error.Overflow, testLeb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x01"));
1908
1909 // Decode SLEB128
1910 try testing.expect((try testLeb128(i64, "\x00")) == 0);
1911 try testing.expect((try testLeb128(i64, "\x01")) == 1);
1912 try testing.expect((try testLeb128(i64, "\x3f")) == 63);
1913 try testing.expect((try testLeb128(i64, "\x40")) == -64);
1914 try testing.expect((try testLeb128(i64, "\x41")) == -63);
1915 try testing.expect((try testLeb128(i64, "\x7f")) == -1);
1916 try testing.expect((try testLeb128(i64, "\x80\x01")) == 128);
1917 try testing.expect((try testLeb128(i64, "\x81\x01")) == 129);
1918 try testing.expect((try testLeb128(i64, "\xff\x7e")) == -129);
1919 try testing.expect((try testLeb128(i64, "\x80\x7f")) == -128);
1920 try testing.expect((try testLeb128(i64, "\x81\x7f")) == -127);
1921 try testing.expect((try testLeb128(i64, "\xc0\x00")) == 64);
1922 try testing.expect((try testLeb128(i64, "\xc7\x9f\x7f")) == -12345);
1923 try testing.expect((try testLeb128(i8, "\xff\x7f")) == -1);
1924 try testing.expect((try testLeb128(i16, "\xff\xff\x7f")) == -1);
1925 try testing.expect((try testLeb128(i32, "\xff\xff\xff\xff\x7f")) == -1);
1926 try testing.expect((try testLeb128(i32, "\x80\x80\x80\x80\x78")) == -0x80000000);
1927 try testing.expect((try testLeb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x7f")) == @as(i64, @bitCast(@as(u64, @intCast(0x8000000000000000)))));
1928 try testing.expect((try testLeb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x40")) == -0x4000000000000000);
1929 try testing.expect((try testLeb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x7f")) == -0x8000000000000000);
1930
1931 // Decode unnormalized SLEB128 with extra padding bytes.
1932 try testing.expect((try testLeb128(i64, "\x80\x00")) == 0);
1933 try testing.expect((try testLeb128(i64, "\x80\x80\x00")) == 0);
1934 try testing.expect((try testLeb128(i64, "\xff\x00")) == 0x7f);
1935 try testing.expect((try testLeb128(i64, "\xff\x80\x00")) == 0x7f);
1936 try testing.expect((try testLeb128(i64, "\x80\x81\x00")) == 0x80);
1937 try testing.expect((try testLeb128(i64, "\x80\x81\x80\x00")) == 0x80);
1938}
1939
1940test "deserialize unsigned LEB128" {
1941 // Truncated
1942 try testing.expectError(error.EndOfStream, testLeb128(u64, "\x80"));
1943 try testing.expectError(error.EndOfStream, testLeb128(u16, "\x80\x80\x84"));
1944 try testing.expectError(error.EndOfStream, testLeb128(u32, "\x80\x80\x80\x80\x90"));
1945
1946 // Overflow
1947 try testing.expectError(error.Overflow, testLeb128(u8, "\x80\x02"));
1948 try testing.expectError(error.Overflow, testLeb128(u8, "\x80\x80\x40"));
1949 try testing.expectError(error.Overflow, testLeb128(u16, "\x80\x80\x80\x40"));
1950 try testing.expectError(error.Overflow, testLeb128(u32, "\x80\x80\x80\x80\x40"));
1951 try testing.expectError(error.Overflow, testLeb128(u64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x40"));
1952
1953 // Decode ULEB128
1954 try testing.expect((try testLeb128(u64, "\x00")) == 0);
1955 try testing.expect((try testLeb128(u64, "\x01")) == 1);
1956 try testing.expect((try testLeb128(u64, "\x3f")) == 63);
1957 try testing.expect((try testLeb128(u64, "\x40")) == 64);
1958 try testing.expect((try testLeb128(u64, "\x7f")) == 0x7f);
1959 try testing.expect((try testLeb128(u64, "\x80\x01")) == 0x80);
1960 try testing.expect((try testLeb128(u64, "\x81\x01")) == 0x81);
1961 try testing.expect((try testLeb128(u64, "\x90\x01")) == 0x90);
1962 try testing.expect((try testLeb128(u64, "\xff\x01")) == 0xff);
1963 try testing.expect((try testLeb128(u64, "\x80\x02")) == 0x100);
1964 try testing.expect((try testLeb128(u64, "\x81\x02")) == 0x101);
1965 try testing.expect((try testLeb128(u64, "\x80\xc1\x80\x80\x10")) == 4294975616);
1966 try testing.expect((try testLeb128(u64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x01")) == 0x8000000000000000);
1967
1968 // Decode ULEB128 with extra padding bytes
1969 try testing.expect((try testLeb128(u64, "\x80\x00")) == 0);
1970 try testing.expect((try testLeb128(u64, "\x80\x80\x00")) == 0);
1971 try testing.expect((try testLeb128(u64, "\xff\x00")) == 0x7f);
1972 try testing.expect((try testLeb128(u64, "\xff\x80\x00")) == 0x7f);
1973 try testing.expect((try testLeb128(u64, "\x80\x81\x00")) == 0x80);
1974 try testing.expect((try testLeb128(u64, "\x80\x81\x80\x00")) == 0x80);
1975}
1976
1977fn testLeb128(comptime T: type, encoded: []const u8) !T {
1978 var reader: std.Io.Reader = .fixed(encoded);
1979 const result = try reader.takeLeb128(T);
1980 try testing.expect(reader.seek == reader.end);
1981 return result;
1982}
1983
1873test {1984test {
1874 _ = Limited;1985 _ = Limited;
1875}1986}
lib/std/Io/Reader/Limited.zig+3-3
...@@ -1,9 +1,9 @@...@@ -1,9 +1,9 @@
1const Limited = @This();1const Limited = @This();
22
3const std = @import("../../std.zig");3const std = @import("../../std.zig");
4const Reader = std.io.Reader;4const Reader = std.Io.Reader;
5const Writer = std.io.Writer;5const Writer = std.Io.Writer;
6const Limit = std.io.Limit;6const Limit = std.Io.Limit;
77
8unlimited: *Reader,8unlimited: *Reader,
9remaining: Limit,9remaining: Limit,
lib/std/Io/Writer.zig+123-47
...@@ -2531,13 +2531,14 @@ pub fn Hashing(comptime Hasher: type) type {...@@ -2531,13 +2531,14 @@ pub fn Hashing(comptime Hasher: type) type {
2531/// Maintains `Writer` state such that it writes to the unused capacity of an2531/// Maintains `Writer` state such that it writes to the unused capacity of an
2532/// array list, filling it up completely before making a call through the2532/// array list, filling it up completely before making a call through the
2533/// vtable, causing a resize. Consequently, the same, optimized, non-generic2533/// vtable, causing a resize. Consequently, the same, optimized, non-generic
2534/// machine code that uses `std.Io.Reader`, such as formatted printing, takes2534/// machine code that uses `Writer`, such as formatted printing, takes
2535/// the hot paths when using this API.2535/// the hot paths when using this API.
2536///2536///
2537/// When using this API, it is not necessary to call `flush`.2537/// When using this API, it is not necessary to call `flush`.
2538pub const Allocating = struct {2538pub const Allocating = struct {
2539 allocator: Allocator,2539 allocator: Allocator,
2540 writer: Writer,2540 writer: Writer,
2541 alignment: std.mem.Alignment,
25412542
2542 pub fn init(allocator: Allocator) Allocating {2543 pub fn init(allocator: Allocator) Allocating {
2543 return .{2544 return .{
...@@ -2546,6 +2547,7 @@ pub const Allocating = struct {...@@ -2546,6 +2547,7 @@ pub const Allocating = struct {
2546 .buffer = &.{},2547 .buffer = &.{},
2547 .vtable = &vtable,2548 .vtable = &vtable,
2548 },2549 },
2550 .alignment = .of(u8),
2549 };2551 };
2550 }2552 }
25512553
...@@ -2553,24 +2555,47 @@ pub const Allocating = struct {...@@ -2553,24 +2555,47 @@ pub const Allocating = struct {
2553 return .{2555 return .{
2554 .allocator = allocator,2556 .allocator = allocator,
2555 .writer = .{2557 .writer = .{
2556 .buffer = try allocator.alloc(u8, capacity),2558 .buffer = if (capacity == 0)
2559 &.{}
2560 else
2561 (allocator.rawAlloc(capacity, .of(u8), @returnAddress()) orelse
2562 return error.OutOfMemory)[0..capacity],
2557 .vtable = &vtable,2563 .vtable = &vtable,
2558 },2564 },
2565 .alignment = .of(u8),
2559 };2566 };
2560 }2567 }
25612568
2562 pub fn initOwnedSlice(allocator: Allocator, slice: []u8) Allocating {2569 pub fn initOwnedSlice(allocator: Allocator, slice: []u8) Allocating {
2570 return initOwnedSliceAligned(allocator, .of(u8), slice);
2571 }
2572
2573 pub fn initOwnedSliceAligned(
2574 allocator: Allocator,
2575 comptime alignment: std.mem.Alignment,
2576 slice: []align(alignment.toByteUnits()) u8,
2577 ) Allocating {
2563 return .{2578 return .{
2564 .allocator = allocator,2579 .allocator = allocator,
2565 .writer = .{2580 .writer = .{
2566 .buffer = slice,2581 .buffer = slice,
2567 .vtable = &vtable,2582 .vtable = &vtable,
2568 },2583 },
2584 .alignment = alignment,
2569 };2585 };
2570 }2586 }
25712587
2572 /// Replaces `array_list` with empty, taking ownership of the memory.2588 /// Replaces `array_list` with empty, taking ownership of the memory.
2573 pub fn fromArrayList(allocator: Allocator, array_list: *ArrayList(u8)) Allocating {2589 pub fn fromArrayList(allocator: Allocator, array_list: *ArrayList(u8)) Allocating {
2590 return fromArrayListAligned(allocator, .of(u8), array_list);
2591 }
2592
2593 /// Replaces `array_list` with empty, taking ownership of the memory.
2594 pub fn fromArrayListAligned(
2595 allocator: Allocator,
2596 comptime alignment: std.mem.Alignment,
2597 array_list: *std.array_list.Aligned(u8, alignment),
2598 ) Allocating {
2574 defer array_list.* = .empty;2599 defer array_list.* = .empty;
2575 return .{2600 return .{
2576 .allocator = allocator,2601 .allocator = allocator,
...@@ -2579,6 +2604,7 @@ pub const Allocating = struct {...@@ -2579,6 +2604,7 @@ pub const Allocating = struct {
2579 .buffer = array_list.allocatedSlice(),2604 .buffer = array_list.allocatedSlice(),
2580 .end = array_list.items.len,2605 .end = array_list.items.len,
2581 },2606 },
2607 .alignment = alignment,
2582 };2608 };
2583 }2609 }
25842610
...@@ -2590,16 +2616,27 @@ pub const Allocating = struct {...@@ -2590,16 +2616,27 @@ pub const Allocating = struct {
2590 };2616 };
25912617
2592 pub fn deinit(a: *Allocating) void {2618 pub fn deinit(a: *Allocating) void {
2593 a.allocator.free(a.writer.buffer);2619 if (a.writer.buffer.len == 0) return;
2620 a.allocator.rawFree(a.writer.buffer, a.alignment, @returnAddress());
2594 a.* = undefined;2621 a.* = undefined;
2595 }2622 }
25962623
2597 /// Returns an array list that takes ownership of the allocated memory.2624 /// Returns an array list that takes ownership of the allocated memory.
2598 /// Resets the `Allocating` to an empty state.2625 /// Resets the `Allocating` to an empty state.
2599 pub fn toArrayList(a: *Allocating) ArrayList(u8) {2626 pub fn toArrayList(a: *Allocating) ArrayList(u8) {
2627 return toArrayListAligned(a, .of(u8));
2628 }
2629
2630 /// Returns an array list that takes ownership of the allocated memory.
2631 /// Resets the `Allocating` to an empty state.
2632 pub fn toArrayListAligned(
2633 a: *Allocating,
2634 comptime alignment: std.mem.Alignment,
2635 ) std.array_list.Aligned(u8, alignment) {
2636 assert(a.alignment == alignment); // Required for Allocator correctness.
2600 const w = &a.writer;2637 const w = &a.writer;
2601 const result: ArrayList(u8) = .{2638 const result: std.array_list.Aligned(u8, alignment) = .{
2602 .items = w.buffer[0..w.end],2639 .items = @alignCast(w.buffer[0..w.end]),
2603 .capacity = w.buffer.len,2640 .capacity = w.buffer.len,
2604 };2641 };
2605 w.buffer = &.{};2642 w.buffer = &.{};
...@@ -2608,28 +2645,74 @@ pub const Allocating = struct {...@@ -2608,28 +2645,74 @@ pub const Allocating = struct {
2608 }2645 }
26092646
2610 pub fn ensureUnusedCapacity(a: *Allocating, additional_count: usize) Allocator.Error!void {2647 pub fn ensureUnusedCapacity(a: *Allocating, additional_count: usize) Allocator.Error!void {
2611 var list = a.toArrayList();2648 const new_capacity = std.math.add(usize, a.writer.end, additional_count) catch return error.OutOfMemory;
2612 defer a.setArrayList(list);2649 return ensureTotalCapacity(a, new_capacity);
2613 return list.ensureUnusedCapacity(a.allocator, additional_count);
2614 }2650 }
26152651
2616 pub fn ensureTotalCapacity(a: *Allocating, new_capacity: usize) Allocator.Error!void {2652 pub fn ensureTotalCapacity(a: *Allocating, new_capacity: usize) Allocator.Error!void {
2617 var list = a.toArrayList();2653 // Protects growing unnecessarily since better_capacity will be larger.
2618 defer a.setArrayList(list);2654 if (a.writer.buffer.len >= new_capacity) return;
2619 return list.ensureTotalCapacity(a.allocator, new_capacity);2655 const better_capacity = ArrayList(u8).growCapacity(a.writer.buffer.len, new_capacity);
2620 }2656 return ensureTotalCapacityPrecise(a, better_capacity);
2657 }
2658
2659 pub fn ensureTotalCapacityPrecise(a: *Allocating, new_capacity: usize) Allocator.Error!void {
2660 const old_memory = a.writer.buffer;
2661 if (old_memory.len >= new_capacity) return;
2662 assert(new_capacity != 0);
2663 const alignment = a.alignment;
2664 if (old_memory.len > 0) {
2665 if (a.allocator.rawRemap(old_memory, alignment, new_capacity, @returnAddress())) |new| {
2666 a.writer.buffer = new[0..new_capacity];
2667 return;
2668 }
2669 }
2670 const new_memory = (a.allocator.rawAlloc(new_capacity, alignment, @returnAddress()) orelse
2671 return error.OutOfMemory)[0..new_capacity];
2672 const saved = old_memory[0..a.writer.end];
2673 @memcpy(new_memory[0..saved.len], saved);
2674 if (old_memory.len != 0) a.allocator.rawFree(old_memory, alignment, @returnAddress());
2675 a.writer.buffer = new_memory;
2676 }
2677
2678 pub fn toOwnedSlice(a: *Allocating) Allocator.Error![]u8 {
2679 const old_memory = a.writer.buffer;
2680 const alignment = a.alignment;
2681 const buffered_len = a.writer.end;
2682
2683 if (old_memory.len > 0) {
2684 if (buffered_len == 0) {
2685 a.allocator.rawFree(old_memory, alignment, @returnAddress());
2686 a.writer.buffer = &.{};
2687 a.writer.end = 0;
2688 return old_memory[0..0];
2689 } else if (a.allocator.rawRemap(old_memory, alignment, buffered_len, @returnAddress())) |new| {
2690 a.writer.buffer = &.{};
2691 a.writer.end = 0;
2692 return new[0..buffered_len];
2693 }
2694 }
26212695
2622 pub fn toOwnedSlice(a: *Allocating) error{OutOfMemory}![]u8 {2696 if (buffered_len == 0)
2623 var list = a.toArrayList();2697 return a.writer.buffer[0..0];
2624 defer a.setArrayList(list);2698
2625 return list.toOwnedSlice(a.allocator);2699 const new_memory = (a.allocator.rawAlloc(buffered_len, alignment, @returnAddress()) orelse
2700 return error.OutOfMemory)[0..buffered_len];
2701 @memcpy(new_memory, old_memory[0..buffered_len]);
2702 if (old_memory.len != 0) a.allocator.rawFree(old_memory, alignment, @returnAddress());
2703 a.writer.buffer = &.{};
2704 a.writer.end = 0;
2705 return new_memory;
2626 }2706 }
26272707
2628 pub fn toOwnedSliceSentinel(a: *Allocating, comptime sentinel: u8) error{OutOfMemory}![:sentinel]u8 {2708 pub fn toOwnedSliceSentinel(a: *Allocating, comptime sentinel: u8) Allocator.Error![:sentinel]u8 {
2629 const gpa = a.allocator;2709 // This addition can never overflow because `a.writer.buffer` can never occupy the whole address space.
2630 var list = @This().toArrayList(a);2710 try ensureTotalCapacityPrecise(a, a.writer.end + 1);
2631 defer a.setArrayList(list);2711 a.writer.buffer[a.writer.end] = sentinel;
2632 return list.toOwnedSliceSentinel(gpa, sentinel);2712 a.writer.end += 1;
2713 errdefer a.writer.end -= 1;
2714 const result = try toOwnedSlice(a);
2715 return result[0 .. result.len - 1 :sentinel];
2633 }2716 }
26342717
2635 pub fn written(a: *Allocating) []u8 {2718 pub fn written(a: *Allocating) []u8 {
...@@ -2646,57 +2729,50 @@ pub const Allocating = struct {...@@ -2646,57 +2729,50 @@ pub const Allocating = struct {
26462729
2647 fn drain(w: *Writer, data: []const []const u8, splat: usize) Error!usize {2730 fn drain(w: *Writer, data: []const []const u8, splat: usize) Error!usize {
2648 const a: *Allocating = @fieldParentPtr("writer", w);2731 const a: *Allocating = @fieldParentPtr("writer", w);
2649 const gpa = a.allocator;
2650 const pattern = data[data.len - 1];2732 const pattern = data[data.len - 1];
2651 const splat_len = pattern.len * splat;2733 const splat_len = pattern.len * splat;
2652 var list = a.toArrayList();2734 const start_len = a.writer.end;
2653 defer setArrayList(a, list);
2654 const start_len = list.items.len;
2655 assert(data.len != 0);2735 assert(data.len != 0);
2656 for (data) |bytes| {2736 for (data) |bytes| {
2657 list.ensureUnusedCapacity(gpa, bytes.len + splat_len + 1) catch return error.WriteFailed;2737 a.ensureUnusedCapacity(bytes.len + splat_len + 1) catch return error.WriteFailed;
2658 list.appendSliceAssumeCapacity(bytes);2738 @memcpy(a.writer.buffer[a.writer.end..][0..bytes.len], bytes);
2739 a.writer.end += bytes.len;
2659 }2740 }
2660 if (splat == 0) {2741 if (splat == 0) {
2661 list.items.len -= pattern.len;2742 a.writer.end -= pattern.len;
2662 } else switch (pattern.len) {2743 } else switch (pattern.len) {
2663 0 => {},2744 0 => {},
2664 1 => list.appendNTimesAssumeCapacity(pattern[0], splat - 1),2745 1 => {
2665 else => for (0..splat - 1) |_| list.appendSliceAssumeCapacity(pattern),2746 @memset(a.writer.buffer[a.writer.end..][0 .. splat - 1], pattern[0]);
2747 a.writer.end += splat - 1;
2748 },
2749 else => for (0..splat - 1) |_| {
2750 @memcpy(a.writer.buffer[a.writer.end..][0..pattern.len], pattern);
2751 a.writer.end += pattern.len;
2752 },
2666 }2753 }
2667 return list.items.len - start_len;2754 return a.writer.end - start_len;
2668 }2755 }
26692756
2670 fn sendFile(w: *Writer, file_reader: *File.Reader, limit: Limit) FileError!usize {2757 fn sendFile(w: *Writer, file_reader: *File.Reader, limit: Limit) FileError!usize {
2671 if (File.Handle == void) return error.Unimplemented;2758 if (File.Handle == void) return error.Unimplemented;
2672 if (limit == .nothing) return 0;2759 if (limit == .nothing) return 0;
2673 const a: *Allocating = @fieldParentPtr("writer", w);2760 const a: *Allocating = @fieldParentPtr("writer", w);
2674 const gpa = a.allocator;
2675 var list = a.toArrayList();
2676 defer setArrayList(a, list);
2677 const pos = file_reader.logicalPos();2761 const pos = file_reader.logicalPos();
2678 const additional = if (file_reader.getSize()) |size| size - pos else |_| std.atomic.cache_line;2762 const additional = if (file_reader.getSize()) |size| size - pos else |_| std.atomic.cache_line;
2679 if (additional == 0) return error.EndOfStream;2763 if (additional == 0) return error.EndOfStream;
2680 list.ensureUnusedCapacity(gpa, limit.minInt64(additional)) catch return error.WriteFailed;2764 a.ensureUnusedCapacity(limit.minInt64(additional)) catch return error.WriteFailed;
2681 const dest = limit.slice(list.unusedCapacitySlice());2765 const dest = limit.slice(a.writer.buffer[a.writer.end..]);
2682 const n = try file_reader.read(dest);2766 const n = try file_reader.read(dest);
2683 list.items.len += n;2767 a.writer.end += n;
2684 return n;2768 return n;
2685 }2769 }
26862770
2687 fn growingRebase(w: *Writer, preserve: usize, minimum_len: usize) Error!void {2771 fn growingRebase(w: *Writer, preserve: usize, minimum_len: usize) Error!void {
2688 const a: *Allocating = @fieldParentPtr("writer", w);2772 const a: *Allocating = @fieldParentPtr("writer", w);
2689 const gpa = a.allocator;
2690 var list = a.toArrayList();
2691 defer setArrayList(a, list);
2692 const total = std.math.add(usize, preserve, minimum_len) catch return error.WriteFailed;2773 const total = std.math.add(usize, preserve, minimum_len) catch return error.WriteFailed;
2693 list.ensureTotalCapacity(gpa, total) catch return error.WriteFailed;2774 a.ensureTotalCapacity(total) catch return error.WriteFailed;
2694 list.ensureUnusedCapacity(gpa, minimum_len) catch return error.WriteFailed;2775 a.ensureUnusedCapacity(minimum_len) catch return error.WriteFailed;
2695 }
2696
2697 fn setArrayList(a: *Allocating, list: ArrayList(u8)) void {
2698 a.writer.buffer = list.allocatedSlice();
2699 a.writer.end = list.items.len;
2700 }2776 }
27012777
2702 test Allocating {2778 test Allocating {
lib/std/Io/fixed_buffer_stream.zig deleted-114
...@@ -1,114 +0,0 @@
1const std = @import("../std.zig");
2const io = std.io;
3const testing = std.testing;
4const mem = std.mem;
5const assert = std.debug.assert;
6
7/// Deprecated in favor of `std.Io.Reader.fixed` and `std.Io.Writer.fixed`.
8pub fn FixedBufferStream(comptime Buffer: type) type {
9 return struct {
10 /// `Buffer` is either a `[]u8` or `[]const u8`.
11 buffer: Buffer,
12 pos: usize,
13
14 pub const ReadError = error{};
15 pub const WriteError = error{NoSpaceLeft};
16 pub const SeekError = error{};
17 pub const GetSeekPosError = error{};
18
19 pub const Reader = io.GenericReader(*Self, ReadError, read);
20
21 const Self = @This();
22
23 pub fn reader(self: *Self) Reader {
24 return .{ .context = self };
25 }
26
27 pub fn read(self: *Self, dest: []u8) ReadError!usize {
28 const size = @min(dest.len, self.buffer.len - self.pos);
29 const end = self.pos + size;
30
31 @memcpy(dest[0..size], self.buffer[self.pos..end]);
32 self.pos = end;
33
34 return size;
35 }
36
37 pub fn seekTo(self: *Self, pos: u64) SeekError!void {
38 self.pos = @min(std.math.lossyCast(usize, pos), self.buffer.len);
39 }
40
41 pub fn seekBy(self: *Self, amt: i64) SeekError!void {
42 if (amt < 0) {
43 const abs_amt = @abs(amt);
44 const abs_amt_usize = std.math.cast(usize, abs_amt) orelse std.math.maxInt(usize);
45 if (abs_amt_usize > self.pos) {
46 self.pos = 0;
47 } else {
48 self.pos -= abs_amt_usize;
49 }
50 } else {
51 const amt_usize = std.math.cast(usize, amt) orelse std.math.maxInt(usize);
52 const new_pos = std.math.add(usize, self.pos, amt_usize) catch std.math.maxInt(usize);
53 self.pos = @min(self.buffer.len, new_pos);
54 }
55 }
56
57 pub fn getEndPos(self: *Self) GetSeekPosError!u64 {
58 return self.buffer.len;
59 }
60
61 pub fn getPos(self: *Self) GetSeekPosError!u64 {
62 return self.pos;
63 }
64
65 pub fn reset(self: *Self) void {
66 self.pos = 0;
67 }
68 };
69}
70
71pub fn fixedBufferStream(buffer: anytype) FixedBufferStream(Slice(@TypeOf(buffer))) {
72 return .{ .buffer = buffer, .pos = 0 };
73}
74
75fn Slice(comptime T: type) type {
76 switch (@typeInfo(T)) {
77 .pointer => |ptr_info| {
78 var new_ptr_info = ptr_info;
79 switch (ptr_info.size) {
80 .slice => {},
81 .one => switch (@typeInfo(ptr_info.child)) {
82 .array => |info| new_ptr_info.child = info.child,
83 else => @compileError("invalid type given to fixedBufferStream"),
84 },
85 else => @compileError("invalid type given to fixedBufferStream"),
86 }
87 new_ptr_info.size = .slice;
88 return @Type(.{ .pointer = new_ptr_info });
89 },
90 else => @compileError("invalid type given to fixedBufferStream"),
91 }
92}
93
94test "input" {
95 const bytes = [_]u8{ 1, 2, 3, 4, 5, 6, 7 };
96 var fbs = fixedBufferStream(&bytes);
97
98 var dest: [4]u8 = undefined;
99
100 var read = try fbs.reader().read(&dest);
101 try testing.expect(read == 4);
102 try testing.expect(mem.eql(u8, dest[0..4], bytes[0..4]));
103
104 read = try fbs.reader().read(&dest);
105 try testing.expect(read == 3);
106 try testing.expect(mem.eql(u8, dest[0..3], bytes[4..7]));
107
108 read = try fbs.reader().read(&dest);
109 try testing.expect(read == 0);
110
111 try fbs.seekTo((try fbs.getEndPos()) + 1);
112 read = try fbs.reader().read(&dest);
113 try testing.expect(read == 0);
114}
lib/std/Io/test.zig-22
...@@ -1,5 +1,4 @@...@@ -1,5 +1,4 @@
1const std = @import("std");1const std = @import("std");
2const io = std.io;
3const DefaultPrng = std.Random.DefaultPrng;2const DefaultPrng = std.Random.DefaultPrng;
4const expect = std.testing.expect;3const expect = std.testing.expect;
5const expectEqual = std.testing.expectEqual;4const expectEqual = std.testing.expectEqual;
...@@ -122,24 +121,3 @@ test "updateTimes" {...@@ -122,24 +121,3 @@ test "updateTimes" {
122 try expect(stat_new.atime < stat_old.atime);121 try expect(stat_new.atime < stat_old.atime);
123 try expect(stat_new.mtime < stat_old.mtime);122 try expect(stat_new.mtime < stat_old.mtime);
124}123}
125
126test "GenericReader methods can return error.EndOfStream" {
127 // https://github.com/ziglang/zig/issues/17733
128 var fbs = std.io.fixedBufferStream("");
129 try std.testing.expectError(
130 error.EndOfStream,
131 fbs.reader().readEnum(enum(u8) { a, b }, .little),
132 );
133 try std.testing.expectError(
134 error.EndOfStream,
135 fbs.reader().isBytes("foo"),
136 );
137}
138
139test "Adapted DeprecatedReader EndOfStream" {
140 var fbs: io.FixedBufferStream([]const u8) = .{ .buffer = &.{}, .pos = 0 };
141 const reader = fbs.reader();
142 var buf: [1]u8 = undefined;
143 var adapted = reader.adaptToNewApi(&buf);
144 try std.testing.expectError(error.EndOfStream, adapted.new_interface.takeByte());
145}
lib/std/Io/tty.zig+2-2
...@@ -76,9 +76,9 @@ pub const Config = union(enum) {...@@ -76,9 +76,9 @@ pub const Config = union(enum) {
76 reset_attributes: u16,76 reset_attributes: u16,
77 };77 };
7878
79 pub const SetColorError = std.os.windows.SetConsoleTextAttributeError || std.io.Writer.Error;79 pub const SetColorError = std.os.windows.SetConsoleTextAttributeError || std.Io.Writer.Error;
8080
81 pub fn setColor(conf: Config, w: *std.io.Writer, color: Color) SetColorError!void {81 pub fn setColor(conf: Config, w: *std.Io.Writer, color: Color) SetColorError!void {
82 nosuspend switch (conf) {82 nosuspend switch (conf) {
83 .no_color => return,83 .no_color => return,
84 .escape_codes => {84 .escape_codes => {
lib/std/Progress.zig+1-1
...@@ -9,7 +9,7 @@ const Progress = @This();...@@ -9,7 +9,7 @@ const Progress = @This();
9const posix = std.posix;9const posix = std.posix;
10const is_big_endian = builtin.cpu.arch.endian() == .big;10const is_big_endian = builtin.cpu.arch.endian() == .big;
11const is_windows = builtin.os.tag == .windows;11const is_windows = builtin.os.tag == .windows;
12const Writer = std.io.Writer;12const Writer = std.Io.Writer;
1313
14/// `null` if the current node (and its children) should14/// `null` if the current node (and its children) should
15/// not print on update()15/// not print on update()
lib/std/SemanticVersion.zig+1-1
...@@ -150,7 +150,7 @@ fn parseNum(text: []const u8) error{ InvalidVersion, Overflow }!usize {...@@ -150,7 +150,7 @@ fn parseNum(text: []const u8) error{ InvalidVersion, Overflow }!usize {
150 };150 };
151}151}
152152
153pub fn format(self: Version, w: *std.io.Writer) std.io.Writer.Error!void {153pub fn format(self: Version, w: *std.Io.Writer) std.Io.Writer.Error!void {
154 try w.print("{d}.{d}.{d}", .{ self.major, self.minor, self.patch });154 try w.print("{d}.{d}.{d}", .{ self.major, self.minor, self.patch });
155 if (self.pre) |pre| try w.print("-{s}", .{pre});155 if (self.pre) |pre| try w.print("-{s}", .{pre});
156 if (self.build) |build| try w.print("+{s}", .{build});156 if (self.build) |build| try w.print("+{s}", .{build});
lib/std/Target.zig+1-1
...@@ -311,7 +311,7 @@ pub const Os = struct {...@@ -311,7 +311,7 @@ pub const Os = struct {
311311
312 /// This function is defined to serialize a Zig source code representation of this312 /// This function is defined to serialize a Zig source code representation of this
313 /// type, that, when parsed, will deserialize into the same data.313 /// type, that, when parsed, will deserialize into the same data.
314 pub fn format(wv: WindowsVersion, w: *std.io.Writer) std.io.Writer.Error!void {314 pub fn format(wv: WindowsVersion, w: *std.Io.Writer) std.Io.Writer.Error!void {
315 if (std.enums.tagName(WindowsVersion, wv)) |name| {315 if (std.enums.tagName(WindowsVersion, wv)) |name| {
316 var vecs: [2][]const u8 = .{ ".", name };316 var vecs: [2][]const u8 = .{ ".", name };
317 return w.writeVecAll(&vecs);317 return w.writeVecAll(&vecs);
lib/std/Thread.zig+4-2
...@@ -280,8 +280,10 @@ pub fn getName(self: Thread, buffer_ptr: *[max_name_len:0]u8) GetNameError!?[]co...@@ -280,8 +280,10 @@ pub fn getName(self: Thread, buffer_ptr: *[max_name_len:0]u8) GetNameError!?[]co
280 const file = try std.fs.cwd().openFile(path, .{});280 const file = try std.fs.cwd().openFile(path, .{});
281 defer file.close();281 defer file.close();
282282
283 const data_len = try file.deprecatedReader().readAll(buffer_ptr[0 .. max_name_len + 1]);283 var file_reader = file.readerStreaming(&.{});
284284 const data_len = file_reader.interface.readSliceShort(buffer_ptr[0 .. max_name_len + 1]) catch |err| switch (err) {
285 error.ReadFailed => return file_reader.err.?,
286 };
285 return if (data_len >= 1) buffer[0 .. data_len - 1] else null;287 return if (data_len >= 1) buffer[0 .. data_len - 1] else null;
286 },288 },
287 .windows => {289 .windows => {
lib/std/array_list.zig+6-4
...@@ -405,6 +405,7 @@ pub fn AlignedManaged(comptime T: type, comptime alignment: ?mem.Alignment) type...@@ -405,6 +405,7 @@ pub fn AlignedManaged(comptime T: type, comptime alignment: ?mem.Alignment) type
405 return;405 return;
406 }406 }
407407
408 // Protects growing unnecessarily since better_capacity will be larger.
408 if (self.capacity >= new_capacity) return;409 if (self.capacity >= new_capacity) return;
409410
410 const better_capacity = Aligned(T, alignment).growCapacity(self.capacity, new_capacity);411 const better_capacity = Aligned(T, alignment).growCapacity(self.capacity, new_capacity);
...@@ -664,9 +665,10 @@ pub fn Aligned(comptime T: type, comptime alignment: ?mem.Alignment) type {...@@ -664,9 +665,10 @@ pub fn Aligned(comptime T: type, comptime alignment: ?mem.Alignment) type {
664665
665 /// The caller owns the returned memory. ArrayList becomes empty.666 /// The caller owns the returned memory. ArrayList becomes empty.
666 pub fn toOwnedSliceSentinel(self: *Self, gpa: Allocator, comptime sentinel: T) Allocator.Error!SentinelSlice(sentinel) {667 pub fn toOwnedSliceSentinel(self: *Self, gpa: Allocator, comptime sentinel: T) Allocator.Error!SentinelSlice(sentinel) {
667 // This addition can never overflow because `self.items` can never occupy the whole address space668 // This addition can never overflow because `self.items` can never occupy the whole address space.
668 try self.ensureTotalCapacityPrecise(gpa, self.items.len + 1);669 try self.ensureTotalCapacityPrecise(gpa, self.items.len + 1);
669 self.appendAssumeCapacity(sentinel);670 self.appendAssumeCapacity(sentinel);
671 errdefer self.items.len -= 1;
670 const result = try self.toOwnedSlice(gpa);672 const result = try self.toOwnedSlice(gpa);
671 return result[0 .. result.len - 1 :sentinel];673 return result[0 .. result.len - 1 :sentinel];
672 }674 }
...@@ -1038,14 +1040,14 @@ pub fn Aligned(comptime T: type, comptime alignment: ?mem.Alignment) type {...@@ -1038,14 +1040,14 @@ pub fn Aligned(comptime T: type, comptime alignment: ?mem.Alignment) type {
10381040
1039 pub fn printAssumeCapacity(self: *Self, comptime fmt: []const u8, args: anytype) void {1041 pub fn printAssumeCapacity(self: *Self, comptime fmt: []const u8, args: anytype) void {
1040 comptime assert(T == u8);1042 comptime assert(T == u8);
1041 var w: std.io.Writer = .fixed(self.unusedCapacitySlice());1043 var w: std.Io.Writer = .fixed(self.unusedCapacitySlice());
1042 w.print(fmt, args) catch unreachable;1044 w.print(fmt, args) catch unreachable;
1043 self.items.len += w.end;1045 self.items.len += w.end;
1044 }1046 }
10451047
1046 pub fn printBounded(self: *Self, comptime fmt: []const u8, args: anytype) error{OutOfMemory}!void {1048 pub fn printBounded(self: *Self, comptime fmt: []const u8, args: anytype) error{OutOfMemory}!void {
1047 comptime assert(T == u8);1049 comptime assert(T == u8);
1048 var w: std.io.Writer = .fixed(self.unusedCapacitySlice());1050 var w: std.Io.Writer = .fixed(self.unusedCapacitySlice());
1049 w.print(fmt, args) catch return error.OutOfMemory;1051 w.print(fmt, args) catch return error.OutOfMemory;
1050 self.items.len += w.end;1052 self.items.len += w.end;
1051 }1053 }
...@@ -1361,7 +1363,7 @@ pub fn Aligned(comptime T: type, comptime alignment: ?mem.Alignment) type {...@@ -1361,7 +1363,7 @@ pub fn Aligned(comptime T: type, comptime alignment: ?mem.Alignment) type {
13611363
1362 /// Called when memory growth is necessary. Returns a capacity larger than1364 /// Called when memory growth is necessary. Returns a capacity larger than
1363 /// minimum that grows super-linearly.1365 /// minimum that grows super-linearly.
1364 fn growCapacity(current: usize, minimum: usize) usize {1366 pub fn growCapacity(current: usize, minimum: usize) usize {
1365 var new = current;1367 var new = current;
1366 while (true) {1368 while (true) {
1367 new +|= new / 2 + init_capacity;1369 new +|= new / 2 + init_capacity;
lib/std/ascii.zig+1-1
...@@ -444,7 +444,7 @@ pub const HexEscape = struct {...@@ -444,7 +444,7 @@ pub const HexEscape = struct {
444 pub const upper_charset = "0123456789ABCDEF";444 pub const upper_charset = "0123456789ABCDEF";
445 pub const lower_charset = "0123456789abcdef";445 pub const lower_charset = "0123456789abcdef";
446446
447 pub fn format(se: HexEscape, w: *std.io.Writer) std.io.Writer.Error!void {447 pub fn format(se: HexEscape, w: *std.Io.Writer) std.Io.Writer.Error!void {
448 const charset = se.charset;448 const charset = se.charset;
449449
450 var buf: [4]u8 = undefined;450 var buf: [4]u8 = undefined;
lib/std/builtin.zig+2-2
...@@ -38,7 +38,7 @@ pub const StackTrace = struct {...@@ -38,7 +38,7 @@ pub const StackTrace = struct {
38 index: usize,38 index: usize,
39 instruction_addresses: []usize,39 instruction_addresses: []usize,
4040
41 pub fn format(self: StackTrace, writer: *std.io.Writer) std.io.Writer.Error!void {41 pub fn format(self: StackTrace, writer: *std.Io.Writer) std.Io.Writer.Error!void {
42 // TODO: re-evaluate whether to use format() methods at all.42 // TODO: re-evaluate whether to use format() methods at all.
43 // Until then, avoid an error when using GeneralPurposeAllocator with WebAssembly43 // Until then, avoid an error when using GeneralPurposeAllocator with WebAssembly
44 // where it tries to call detectTTYConfig here.44 // where it tries to call detectTTYConfig here.
...@@ -47,7 +47,7 @@ pub const StackTrace = struct {...@@ -47,7 +47,7 @@ pub const StackTrace = struct {
47 const debug_info = std.debug.getSelfDebugInfo() catch |err| {47 const debug_info = std.debug.getSelfDebugInfo() catch |err| {
48 return writer.print("\nUnable to print stack trace: Unable to open debug info: {s}\n", .{@errorName(err)});48 return writer.print("\nUnable to print stack trace: Unable to open debug info: {s}\n", .{@errorName(err)});
49 };49 };
50 const tty_config = std.io.tty.detectConfig(std.fs.File.stderr());50 const tty_config = std.Io.tty.detectConfig(std.fs.File.stderr());
51 try writer.writeAll("\n");51 try writer.writeAll("\n");
52 std.debug.writeStackTrace(self, writer, debug_info, tty_config) catch |err| {52 std.debug.writeStackTrace(self, writer, debug_info, tty_config) catch |err| {
53 try writer.print("Unable to print stack trace: {s}\n", .{@errorName(err)});53 try writer.print("Unable to print stack trace: {s}\n", .{@errorName(err)});
lib/std/coff.zig+15-20
...@@ -1087,14 +1087,11 @@ pub const Coff = struct {...@@ -1087,14 +1087,11 @@ pub const Coff = struct {
1087 const pe_pointer_offset = 0x3C;1087 const pe_pointer_offset = 0x3C;
1088 const pe_magic = "PE\x00\x00";1088 const pe_magic = "PE\x00\x00";
10891089
1090 var stream = std.io.fixedBufferStream(data);1090 var reader: std.Io.Reader = .fixed(data);
1091 const reader = stream.reader();1091 reader.seek = pe_pointer_offset;
1092 try stream.seekTo(pe_pointer_offset);1092 const coff_header_offset = try reader.takeInt(u32, .little);
1093 const coff_header_offset = try reader.readInt(u32, .little);1093 reader.seek = coff_header_offset;
1094 try stream.seekTo(coff_header_offset);1094 const is_image = mem.eql(u8, pe_magic, try reader.takeArray(4));
1095 var buf: [4]u8 = undefined;
1096 try reader.readNoEof(&buf);
1097 const is_image = mem.eql(u8, pe_magic, &buf);
10981095
1099 var coff = @This(){1096 var coff = @This(){
1100 .data = data,1097 .data = data,
...@@ -1123,16 +1120,15 @@ pub const Coff = struct {...@@ -1123,16 +1120,15 @@ pub const Coff = struct {
1123 if (@intFromEnum(DirectoryEntry.DEBUG) >= data_dirs.len) return null;1120 if (@intFromEnum(DirectoryEntry.DEBUG) >= data_dirs.len) return null;
11241121
1125 const debug_dir = data_dirs[@intFromEnum(DirectoryEntry.DEBUG)];1122 const debug_dir = data_dirs[@intFromEnum(DirectoryEntry.DEBUG)];
1126 var stream = std.io.fixedBufferStream(self.data);1123 var reader: std.Io.Reader = .fixed(self.data);
1127 const reader = stream.reader();
11281124
1129 if (self.is_loaded) {1125 if (self.is_loaded) {
1130 try stream.seekTo(debug_dir.virtual_address);1126 reader.seek = debug_dir.virtual_address;
1131 } else {1127 } else {
1132 // Find what section the debug_dir is in, in order to convert the RVA to a file offset1128 // Find what section the debug_dir is in, in order to convert the RVA to a file offset
1133 for (self.getSectionHeaders()) |*sect| {1129 for (self.getSectionHeaders()) |*sect| {
1134 if (debug_dir.virtual_address >= sect.virtual_address and debug_dir.virtual_address < sect.virtual_address + sect.virtual_size) {1130 if (debug_dir.virtual_address >= sect.virtual_address and debug_dir.virtual_address < sect.virtual_address + sect.virtual_size) {
1135 try stream.seekTo(sect.pointer_to_raw_data + (debug_dir.virtual_address - sect.virtual_address));1131 reader.seek = sect.pointer_to_raw_data + (debug_dir.virtual_address - sect.virtual_address);
1136 break;1132 break;
1137 }1133 }
1138 } else return error.InvalidDebugDirectory;1134 } else return error.InvalidDebugDirectory;
...@@ -1143,24 +1139,23 @@ pub const Coff = struct {...@@ -1143,24 +1139,23 @@ pub const Coff = struct {
1143 const debug_dir_entry_count = debug_dir.size / @sizeOf(DebugDirectoryEntry);1139 const debug_dir_entry_count = debug_dir.size / @sizeOf(DebugDirectoryEntry);
1144 var i: u32 = 0;1140 var i: u32 = 0;
1145 while (i < debug_dir_entry_count) : (i += 1) {1141 while (i < debug_dir_entry_count) : (i += 1) {
1146 const debug_dir_entry = try reader.readStruct(DebugDirectoryEntry);1142 const debug_dir_entry = try reader.takeStruct(DebugDirectoryEntry, .little);
1147 if (debug_dir_entry.type == .CODEVIEW) {1143 if (debug_dir_entry.type == .CODEVIEW) {
1148 const dir_offset = if (self.is_loaded) debug_dir_entry.address_of_raw_data else debug_dir_entry.pointer_to_raw_data;1144 const dir_offset = if (self.is_loaded) debug_dir_entry.address_of_raw_data else debug_dir_entry.pointer_to_raw_data;
1149 try stream.seekTo(dir_offset);1145 reader.seek = dir_offset;
1150 break;1146 break;
1151 }1147 }
1152 } else return null;1148 } else return null;
11531149
1154 var cv_signature: [4]u8 = undefined; // CodeView signature1150 const code_view_signature = try reader.takeArray(4);
1155 try reader.readNoEof(cv_signature[0..]);
1156 // 'RSDS' indicates PDB70 format, used by lld.1151 // 'RSDS' indicates PDB70 format, used by lld.
1157 if (!mem.eql(u8, &cv_signature, "RSDS"))1152 if (!mem.eql(u8, code_view_signature, "RSDS"))
1158 return error.InvalidPEMagic;1153 return error.InvalidPEMagic;
1159 try reader.readNoEof(self.guid[0..]);1154 try reader.readSliceAll(self.guid[0..]);
1160 self.age = try reader.readInt(u32, .little);1155 self.age = try reader.takeInt(u32, .little);
11611156
1162 // Finally read the null-terminated string.1157 // Finally read the null-terminated string.
1163 const start = reader.context.pos;1158 const start = reader.seek;
1164 const len = std.mem.indexOfScalar(u8, self.data[start..], 0) orelse return null;1159 const len = std.mem.indexOfScalar(u8, self.data[start..], 0) orelse return null;
1165 return self.data[start .. start + len];1160 return self.data[start .. start + len];
1166 }1161 }
lib/std/compress/flate/BlockWriter.zig+1-2
...@@ -1,9 +1,8 @@...@@ -1,9 +1,8 @@
1//! Accepts list of tokens, decides what is best block type to write. What block1//! Accepts list of tokens, decides what is best block type to write. What block
2//! type will provide best compression. Writes header and body of the block.2//! type will provide best compression. Writes header and body of the block.
3const std = @import("std");3const std = @import("std");
4const io = std.io;
5const assert = std.debug.assert;4const assert = std.debug.assert;
6const Writer = std.io.Writer;5const Writer = std.Io.Writer;
76
8const BlockWriter = @This();7const BlockWriter = @This();
9const flate = @import("../flate.zig");8const flate = @import("../flate.zig");
lib/std/compress/zstd/Decompress.zig+3-3
...@@ -1,10 +1,10 @@...@@ -1,10 +1,10 @@
1const Decompress = @This();1const Decompress = @This();
2const std = @import("std");2const std = @import("std");
3const assert = std.debug.assert;3const assert = std.debug.assert;
4const Reader = std.io.Reader;4const Reader = std.Io.Reader;
5const Limit = std.io.Limit;5const Limit = std.Io.Limit;
6const zstd = @import("../zstd.zig");6const zstd = @import("../zstd.zig");
7const Writer = std.io.Writer;7const Writer = std.Io.Writer;
88
9input: *Reader,9input: *Reader,
10reader: Reader,10reader: Reader,
lib/std/crypto/Certificate/Bundle/macos.zig+50-45
...@@ -11,76 +11,81 @@ pub fn rescanMac(cb: *Bundle, gpa: Allocator) RescanMacError!void {...@@ -11,76 +11,81 @@ pub fn rescanMac(cb: *Bundle, gpa: Allocator) RescanMacError!void {
11 cb.bytes.clearRetainingCapacity();11 cb.bytes.clearRetainingCapacity();
12 cb.map.clearRetainingCapacity();12 cb.map.clearRetainingCapacity();
1313
14 const keychainPaths = [2][]const u8{14 const keychain_paths = [2][]const u8{
15 "/System/Library/Keychains/SystemRootCertificates.keychain",15 "/System/Library/Keychains/SystemRootCertificates.keychain",
16 "/Library/Keychains/System.keychain",16 "/Library/Keychains/System.keychain",
17 };17 };
1818
19 for (keychainPaths) |keychainPath| {19 for (keychain_paths) |keychain_path| {
20 const file = try fs.openFileAbsolute(keychainPath, .{});20 const bytes = std.fs.cwd().readFileAlloc(keychain_path, gpa, .limited(std.math.maxInt(u32))) catch |err| switch (err) {
21 defer file.close();21 error.StreamTooLong => return error.FileTooBig,
2222 else => |e| return e,
23 const bytes = try file.readToEndAlloc(gpa, std.math.maxInt(u32));23 };
24 defer gpa.free(bytes);24 defer gpa.free(bytes);
2525
26 var stream = std.io.fixedBufferStream(bytes);26 var reader: std.Io.Reader = .fixed(bytes);
27 const reader = stream.reader();27 scanReader(cb, gpa, &reader) catch |err| switch (err) {
28 error.ReadFailed => unreachable, // prebuffered
29 else => |e| return e,
30 };
31 }
2832
29 const db_header = try reader.readStructEndian(ApplDbHeader, .big);33 cb.bytes.shrinkAndFree(gpa, cb.bytes.items.len);
30 assert(mem.eql(u8, &db_header.signature, "kych"));34}
3135
32 try stream.seekTo(db_header.schema_offset);36fn scanReader(cb: *Bundle, gpa: Allocator, reader: *std.Io.Reader) !void {
37 const db_header = try reader.takeStruct(ApplDbHeader, .big);
38 assert(mem.eql(u8, &db_header.signature, "kych"));
3339
34 const db_schema = try reader.readStructEndian(ApplDbSchema, .big);40 reader.seek = db_header.schema_offset;
3541
36 var table_list = try gpa.alloc(u32, db_schema.table_count);42 const db_schema = try reader.takeStruct(ApplDbSchema, .big);
37 defer gpa.free(table_list);
3843
39 var table_idx: u32 = 0;44 var table_list = try gpa.alloc(u32, db_schema.table_count);
40 while (table_idx < table_list.len) : (table_idx += 1) {45 defer gpa.free(table_list);
41 table_list[table_idx] = try reader.readInt(u32, .big);
42 }
4346
44 const now_sec = std.time.timestamp();47 var table_idx: u32 = 0;
48 while (table_idx < table_list.len) : (table_idx += 1) {
49 table_list[table_idx] = try reader.takeInt(u32, .big);
50 }
4551
46 for (table_list) |table_offset| {52 const now_sec = std.time.timestamp();
47 try stream.seekTo(db_header.schema_offset + table_offset);
4853
49 const table_header = try reader.readStructEndian(TableHeader, .big);54 for (table_list) |table_offset| {
55 reader.seek = db_header.schema_offset + table_offset;
5056
51 if (@as(std.c.DB_RECORDTYPE, @enumFromInt(table_header.table_id)) != .X509_CERTIFICATE) {57 const table_header = try reader.takeStruct(TableHeader, .big);
52 continue;
53 }
5458
55 var record_list = try gpa.alloc(u32, table_header.record_count);59 if (@as(std.c.DB_RECORDTYPE, @enumFromInt(table_header.table_id)) != .X509_CERTIFICATE) {
56 defer gpa.free(record_list);60 continue;
61 }
62
63 var record_list = try gpa.alloc(u32, table_header.record_count);
64 defer gpa.free(record_list);
5765
58 var record_idx: u32 = 0;66 var record_idx: u32 = 0;
59 while (record_idx < record_list.len) : (record_idx += 1) {67 while (record_idx < record_list.len) : (record_idx += 1) {
60 record_list[record_idx] = try reader.readInt(u32, .big);68 record_list[record_idx] = try reader.takeInt(u32, .big);
61 }69 }
6270
63 for (record_list) |record_offset| {71 for (record_list) |record_offset| {
64 // An offset of zero means that the record is not present.72 // An offset of zero means that the record is not present.
65 // An offset that is not 4-byte-aligned is invalid.73 // An offset that is not 4-byte-aligned is invalid.
66 if (record_offset == 0 or record_offset % 4 != 0) continue;74 if (record_offset == 0 or record_offset % 4 != 0) continue;
6775
68 try stream.seekTo(db_header.schema_offset + table_offset + record_offset);76 reader.seek = db_header.schema_offset + table_offset + record_offset;
6977
70 const cert_header = try reader.readStructEndian(X509CertHeader, .big);78 const cert_header = try reader.takeStruct(X509CertHeader, .big);
7179
72 if (cert_header.cert_size == 0) continue;80 if (cert_header.cert_size == 0) continue;
7381
74 const cert_start = @as(u32, @intCast(cb.bytes.items.len));82 const cert_start: u32 = @intCast(cb.bytes.items.len);
75 const dest_buf = try cb.bytes.addManyAsSlice(gpa, cert_header.cert_size);83 const dest_buf = try cb.bytes.addManyAsSlice(gpa, cert_header.cert_size);
76 try reader.readNoEof(dest_buf);84 try reader.readSliceAll(dest_buf);
7785
78 try cb.parseCert(gpa, cert_start, now_sec);86 try cb.parseCert(gpa, cert_start, now_sec);
79 }
80 }87 }
81 }88 }
82
83 cb.bytes.shrinkAndFree(gpa, cb.bytes.items.len);
84}89}
8590
86const ApplDbHeader = extern struct {91const ApplDbHeader = extern struct {
lib/std/crypto/codecs/asn1.zig+13-15
...@@ -69,15 +69,15 @@ pub const Tag = struct {...@@ -69,15 +69,15 @@ pub const Tag = struct {
69 return .{ .number = number, .constructed = constructed, .class = .universal };69 return .{ .number = number, .constructed = constructed, .class = .universal };
70 }70 }
7171
72 pub fn decode(reader: anytype) !Tag {72 pub fn decode(reader: *std.Io.Reader) !Tag {
73 const tag1: FirstTag = @bitCast(try reader.readByte());73 const tag1: FirstTag = @bitCast(try reader.takeByte());
74 var number: u14 = tag1.number;74 var number: u14 = tag1.number;
7575
76 if (tag1.number == 15) {76 if (tag1.number == 15) {
77 const tag2: NextTag = @bitCast(try reader.readByte());77 const tag2: NextTag = @bitCast(try reader.takeByte());
78 number = tag2.number;78 number = tag2.number;
79 if (tag2.continues) {79 if (tag2.continues) {
80 const tag3: NextTag = @bitCast(try reader.readByte());80 const tag3: NextTag = @bitCast(try reader.takeByte());
81 number = (number << 7) + tag3.number;81 number = (number << 7) + tag3.number;
82 if (tag3.continues) return error.InvalidLength;82 if (tag3.continues) return error.InvalidLength;
83 }83 }
...@@ -90,7 +90,7 @@ pub const Tag = struct {...@@ -90,7 +90,7 @@ pub const Tag = struct {
90 };90 };
91 }91 }
9292
93 pub fn encode(self: Tag, writer: anytype) @TypeOf(writer).Error!void {93 pub fn encode(self: Tag, writer: *std.Io.Writer) @TypeOf(writer).Error!void {
94 var tag1 = FirstTag{94 var tag1 = FirstTag{
95 .number = undefined,95 .number = undefined,
96 .constructed = self.constructed,96 .constructed = self.constructed,
...@@ -98,8 +98,7 @@ pub const Tag = struct {...@@ -98,8 +98,7 @@ pub const Tag = struct {
98 };98 };
9999
100 var buffer: [3]u8 = undefined;100 var buffer: [3]u8 = undefined;
101 var stream = std.io.fixedBufferStream(&buffer);101 var writer2: std.Io.Writer = .init(&buffer);
102 var writer2 = stream.writer();
103102
104 switch (@intFromEnum(self.number)) {103 switch (@intFromEnum(self.number)) {
105 0...std.math.maxInt(u5) => |n| {104 0...std.math.maxInt(u5) => |n| {
...@@ -122,7 +121,7 @@ pub const Tag = struct {...@@ -122,7 +121,7 @@ pub const Tag = struct {
122 },121 },
123 }122 }
124123
125 _ = try writer.write(stream.getWritten());124 _ = try writer.write(writer2.buffered());
126 }125 }
127126
128 const FirstTag = packed struct(u8) { number: u5, constructed: bool, class: Tag.Class };127 const FirstTag = packed struct(u8) { number: u5, constructed: bool, class: Tag.Class };
...@@ -161,8 +160,8 @@ pub const Tag = struct {...@@ -161,8 +160,8 @@ pub const Tag = struct {
161160
162test Tag {161test Tag {
163 const buf = [_]u8{0xa3};162 const buf = [_]u8{0xa3};
164 var stream = std.io.fixedBufferStream(&buf);163 var reader: std.Io.Reader = .fixed(&buf);
165 const t = Tag.decode(stream.reader());164 const t = Tag.decode(&reader);
166 try std.testing.expectEqual(Tag.init(@enumFromInt(3), true, .context_specific), t);165 try std.testing.expectEqual(Tag.init(@enumFromInt(3), true, .context_specific), t);
167}166}
168167
...@@ -191,11 +190,10 @@ pub const Element = struct {...@@ -191,11 +190,10 @@ pub const Element = struct {
191 /// - Ensures length is within `bytes`190 /// - Ensures length is within `bytes`
192 /// - Ensures length is less than `std.math.maxInt(Index)`191 /// - Ensures length is less than `std.math.maxInt(Index)`
193 pub fn decode(bytes: []const u8, index: Index) DecodeError!Element {192 pub fn decode(bytes: []const u8, index: Index) DecodeError!Element {
194 var stream = std.io.fixedBufferStream(bytes[index..]);193 var reader: std.Io.Reader = .fixed(bytes[index..]);
195 var reader = stream.reader();
196194
197 const tag = try Tag.decode(reader);195 const tag = try Tag.decode(&reader);
198 const size_or_len_size = try reader.readByte();196 const size_or_len_size = try reader.takeByte();
199197
200 var start = index + 2;198 var start = index + 2;
201 var end = start + size_or_len_size;199 var end = start + size_or_len_size;
...@@ -208,7 +206,7 @@ pub const Element = struct {...@@ -208,7 +206,7 @@ pub const Element = struct {
208 start += len_size;206 start += len_size;
209 if (len_size > @sizeOf(Index)) return error.InvalidLength;207 if (len_size > @sizeOf(Index)) return error.InvalidLength;
210208
211 const len = try reader.readVarInt(Index, .big, len_size);209 const len = try reader.takeVarInt(Index, .big, len_size);
212 if (len < 128) return error.InvalidLength; // should have used short form210 if (len < 128) return error.InvalidLength; // should have used short form
213211
214 end = std.math.add(Index, start, len) catch return error.InvalidLength;212 end = std.math.add(Index, start, len) catch return error.InvalidLength;
lib/std/crypto/codecs/asn1/Oid.zig+6-7
...@@ -4,7 +4,7 @@...@@ -4,7 +4,7 @@
4//! organizations, or policy documents.4//! organizations, or policy documents.
5encoded: []const u8,5encoded: []const u8,
66
7pub const InitError = std.fmt.ParseIntError || error{MissingPrefix} || std.io.FixedBufferStream(u8).WriteError;7pub const InitError = std.fmt.ParseIntError || error{MissingPrefix} || std.Io.Writer.Error;
88
9pub fn fromDot(dot_notation: []const u8, out: []u8) InitError!Oid {9pub fn fromDot(dot_notation: []const u8, out: []u8) InitError!Oid {
10 var split = std.mem.splitScalar(u8, dot_notation, '.');10 var split = std.mem.splitScalar(u8, dot_notation, '.');
...@@ -14,8 +14,7 @@ pub fn fromDot(dot_notation: []const u8, out: []u8) InitError!Oid {...@@ -14,8 +14,7 @@ pub fn fromDot(dot_notation: []const u8, out: []u8) InitError!Oid {
14 const first = try std.fmt.parseInt(u8, first_str, 10);14 const first = try std.fmt.parseInt(u8, first_str, 10);
15 const second = try std.fmt.parseInt(u8, second_str, 10);15 const second = try std.fmt.parseInt(u8, second_str, 10);
1616
17 var stream = std.io.fixedBufferStream(out);17 var writer: std.Io.Writer = .fixed(out);
18 var writer = stream.writer();
1918
20 try writer.writeByte(first * 40 + second);19 try writer.writeByte(first * 40 + second);
2120
...@@ -37,7 +36,7 @@ pub fn fromDot(dot_notation: []const u8, out: []u8) InitError!Oid {...@@ -37,7 +36,7 @@ pub fn fromDot(dot_notation: []const u8, out: []u8) InitError!Oid {
37 i += 1;36 i += 1;
38 }37 }
3938
40 return .{ .encoded = stream.getWritten() };39 return .{ .encoded = writer.buffered() };
41}40}
4241
43test fromDot {42test fromDot {
...@@ -80,9 +79,9 @@ test toDot {...@@ -80,9 +79,9 @@ test toDot {
80 var buf: [256]u8 = undefined;79 var buf: [256]u8 = undefined;
8180
82 for (test_cases) |t| {81 for (test_cases) |t| {
83 var stream = std.io.fixedBufferStream(&buf);82 var stream: std.Io.Writer = .fixed(&buf);
84 try toDot(Oid{ .encoded = t.encoded }, stream.writer());83 try toDot(Oid{ .encoded = t.encoded }, &stream);
85 try std.testing.expectEqualStrings(t.dot_notation, stream.getWritten());84 try std.testing.expectEqualStrings(t.dot_notation, stream.written());
86 }85 }
87}86}
8887
lib/std/crypto/ecdsa.zig+12-17
...@@ -2,7 +2,6 @@ const builtin = @import("builtin");...@@ -2,7 +2,6 @@ const builtin = @import("builtin");
2const std = @import("std");2const std = @import("std");
3const crypto = std.crypto;3const crypto = std.crypto;
4const fmt = std.fmt;4const fmt = std.fmt;
5const io = std.io;
6const mem = std.mem;5const mem = std.mem;
7const sha3 = crypto.hash.sha3;6const sha3 = crypto.hash.sha3;
8const testing = std.testing;7const testing = std.testing;
...@@ -135,8 +134,7 @@ pub fn Ecdsa(comptime Curve: type, comptime Hash: type) type {...@@ -135,8 +134,7 @@ pub fn Ecdsa(comptime Curve: type, comptime Hash: type) type {
135 /// The maximum length of the DER encoding is der_encoded_length_max.134 /// The maximum length of the DER encoding is der_encoded_length_max.
136 /// The function returns a slice, that can be shorter than der_encoded_length_max.135 /// The function returns a slice, that can be shorter than der_encoded_length_max.
137 pub fn toDer(sig: Signature, buf: *[der_encoded_length_max]u8) []u8 {136 pub fn toDer(sig: Signature, buf: *[der_encoded_length_max]u8) []u8 {
138 var fb = io.fixedBufferStream(buf);137 var w: std.Io.Writer = .fixed(buf);
139 const w = fb.writer();
140 const r_len = @as(u8, @intCast(sig.r.len + (sig.r[0] >> 7)));138 const r_len = @as(u8, @intCast(sig.r.len + (sig.r[0] >> 7)));
141 const s_len = @as(u8, @intCast(sig.s.len + (sig.s[0] >> 7)));139 const s_len = @as(u8, @intCast(sig.s.len + (sig.s[0] >> 7)));
142 const seq_len = @as(u8, @intCast(2 + r_len + 2 + s_len));140 const seq_len = @as(u8, @intCast(2 + r_len + 2 + s_len));
...@@ -151,24 +149,23 @@ pub fn Ecdsa(comptime Curve: type, comptime Hash: type) type {...@@ -151,24 +149,23 @@ pub fn Ecdsa(comptime Curve: type, comptime Hash: type) type {
151 w.writeByte(0x00) catch unreachable;149 w.writeByte(0x00) catch unreachable;
152 }150 }
153 w.writeAll(&sig.s) catch unreachable;151 w.writeAll(&sig.s) catch unreachable;
154 return fb.getWritten();152 return w.buffered();
155 }153 }
156154
157 // Read a DER-encoded integer.155 // Read a DER-encoded integer.
158 fn readDerInt(out: []u8, reader: anytype) EncodingError!void {156 fn readDerInt(out: []u8, reader: *std.Io.Reader) EncodingError!void {
159 var buf: [2]u8 = undefined;157 const buf = reader.takeArray(2) catch return error.InvalidEncoding;
160 _ = reader.readNoEof(&buf) catch return error.InvalidEncoding;
161 if (buf[0] != 0x02) return error.InvalidEncoding;158 if (buf[0] != 0x02) return error.InvalidEncoding;
162 var expected_len = @as(usize, buf[1]);159 var expected_len: usize = buf[1];
163 if (expected_len == 0 or expected_len > 1 + out.len) return error.InvalidEncoding;160 if (expected_len == 0 or expected_len > 1 + out.len) return error.InvalidEncoding;
164 var has_top_bit = false;161 var has_top_bit = false;
165 if (expected_len == 1 + out.len) {162 if (expected_len == 1 + out.len) {
166 if ((reader.readByte() catch return error.InvalidEncoding) != 0) return error.InvalidEncoding;163 if ((reader.takeByte() catch return error.InvalidEncoding) != 0) return error.InvalidEncoding;
167 expected_len -= 1;164 expected_len -= 1;
168 has_top_bit = true;165 has_top_bit = true;
169 }166 }
170 const out_slice = out[out.len - expected_len ..];167 const out_slice = out[out.len - expected_len ..];
171 reader.readNoEof(out_slice) catch return error.InvalidEncoding;168 reader.readSliceAll(out_slice) catch return error.InvalidEncoding;
172 if (@intFromBool(has_top_bit) != out[0] >> 7) return error.InvalidEncoding;169 if (@intFromBool(has_top_bit) != out[0] >> 7) return error.InvalidEncoding;
173 }170 }
174171
...@@ -176,16 +173,14 @@ pub fn Ecdsa(comptime Curve: type, comptime Hash: type) type {...@@ -176,16 +173,14 @@ pub fn Ecdsa(comptime Curve: type, comptime Hash: type) type {
176 /// Returns InvalidEncoding if the DER encoding is invalid.173 /// Returns InvalidEncoding if the DER encoding is invalid.
177 pub fn fromDer(der: []const u8) EncodingError!Signature {174 pub fn fromDer(der: []const u8) EncodingError!Signature {
178 var sig: Signature = mem.zeroInit(Signature, .{});175 var sig: Signature = mem.zeroInit(Signature, .{});
179 var fb = io.fixedBufferStream(der);176 var reader: std.Io.Reader = .fixed(der);
180 const reader = fb.reader();177 const buf = reader.takeArray(2) catch return error.InvalidEncoding;
181 var buf: [2]u8 = undefined;
182 _ = reader.readNoEof(&buf) catch return error.InvalidEncoding;
183 if (buf[0] != 0x30 or @as(usize, buf[1]) + 2 != der.len) {178 if (buf[0] != 0x30 or @as(usize, buf[1]) + 2 != der.len) {
184 return error.InvalidEncoding;179 return error.InvalidEncoding;
185 }180 }
186 try readDerInt(&sig.r, reader);181 try readDerInt(&sig.r, &reader);
187 try readDerInt(&sig.s, reader);182 try readDerInt(&sig.s, &reader);
188 if (fb.getPos() catch unreachable != der.len) return error.InvalidEncoding;183 if (reader.seek != der.len) return error.InvalidEncoding;
189184
190 return sig;185 return sig;
191 }186 }
lib/std/crypto/phc_encoding.zig-1
...@@ -2,7 +2,6 @@...@@ -2,7 +2,6 @@
22
3const std = @import("std");3const std = @import("std");
4const fmt = std.fmt;4const fmt = std.fmt;
5const io = std.io;
6const mem = std.mem;5const mem = std.mem;
7const meta = std.meta;6const meta = std.meta;
8const Writer = std.Io.Writer;7const Writer = std.Io.Writer;
lib/std/crypto/scrypt.zig-1
...@@ -5,7 +5,6 @@...@@ -5,7 +5,6 @@
5const std = @import("std");5const std = @import("std");
6const crypto = std.crypto;6const crypto = std.crypto;
7const fmt = std.fmt;7const fmt = std.fmt;
8const io = std.io;
9const math = std.math;8const math = std.math;
10const mem = std.mem;9const mem = std.mem;
11const meta = std.meta;10const meta = std.meta;
lib/std/crypto/tls.zig+2-2
...@@ -655,7 +655,7 @@ pub const Decoder = struct {...@@ -655,7 +655,7 @@ pub const Decoder = struct {
655 }655 }
656656
657 /// Use this function to increase `their_end`.657 /// Use this function to increase `their_end`.
658 pub fn readAtLeast(d: *Decoder, stream: *std.io.Reader, their_amt: usize) !void {658 pub fn readAtLeast(d: *Decoder, stream: *std.Io.Reader, their_amt: usize) !void {
659 assert(!d.disable_reads);659 assert(!d.disable_reads);
660 const existing_amt = d.cap - d.idx;660 const existing_amt = d.cap - d.idx;
661 d.their_end = d.idx + their_amt;661 d.their_end = d.idx + their_amt;
...@@ -672,7 +672,7 @@ pub const Decoder = struct {...@@ -672,7 +672,7 @@ pub const Decoder = struct {
672672
673 /// Same as `readAtLeast` but also increases `our_end` by exactly `our_amt`.673 /// Same as `readAtLeast` but also increases `our_end` by exactly `our_amt`.
674 /// Use when `our_amt` is calculated by us, not by them.674 /// Use when `our_amt` is calculated by us, not by them.
675 pub fn readAtLeastOurAmt(d: *Decoder, stream: *std.io.Reader, our_amt: usize) !void {675 pub fn readAtLeastOurAmt(d: *Decoder, stream: *std.Io.Reader, our_amt: usize) !void {
676 assert(!d.disable_reads);676 assert(!d.disable_reads);
677 try readAtLeast(d, stream, our_amt);677 try readAtLeast(d, stream, our_amt);
678 d.our_end = d.idx + our_amt;678 d.our_end = d.idx + our_amt;
lib/std/debug.zig+19-19
...@@ -2,7 +2,6 @@ const builtin = @import("builtin");...@@ -2,7 +2,6 @@ const builtin = @import("builtin");
2const std = @import("std.zig");2const std = @import("std.zig");
3const math = std.math;3const math = std.math;
4const mem = std.mem;4const mem = std.mem;
5const io = std.io;
6const posix = std.posix;5const posix = std.posix;
7const fs = std.fs;6const fs = std.fs;
8const testing = std.testing;7const testing = std.testing;
...@@ -12,7 +11,8 @@ const windows = std.os.windows;...@@ -12,7 +11,8 @@ const windows = std.os.windows;
12const native_arch = builtin.cpu.arch;11const native_arch = builtin.cpu.arch;
13const native_os = builtin.os.tag;12const native_os = builtin.os.tag;
14const native_endian = native_arch.endian();13const native_endian = native_arch.endian();
15const Writer = std.io.Writer;14const Writer = std.Io.Writer;
15const tty = std.Io.tty;
1616
17pub const Dwarf = @import("debug/Dwarf.zig");17pub const Dwarf = @import("debug/Dwarf.zig");
18pub const Pdb = @import("debug/Pdb.zig");18pub const Pdb = @import("debug/Pdb.zig");
...@@ -246,12 +246,12 @@ pub fn getSelfDebugInfo() !*SelfInfo {...@@ -246,12 +246,12 @@ pub fn getSelfDebugInfo() !*SelfInfo {
246pub fn dumpHex(bytes: []const u8) void {246pub fn dumpHex(bytes: []const u8) void {
247 const bw = lockStderrWriter(&.{});247 const bw = lockStderrWriter(&.{});
248 defer unlockStderrWriter();248 defer unlockStderrWriter();
249 const ttyconf = std.io.tty.detectConfig(.stderr());249 const ttyconf = tty.detectConfig(.stderr());
250 dumpHexFallible(bw, ttyconf, bytes) catch {};250 dumpHexFallible(bw, ttyconf, bytes) catch {};
251}251}
252252
253/// Prints a hexadecimal view of the bytes, returning any error that occurs.253/// Prints a hexadecimal view of the bytes, returning any error that occurs.
254pub fn dumpHexFallible(bw: *Writer, ttyconf: std.io.tty.Config, bytes: []const u8) !void {254pub fn dumpHexFallible(bw: *Writer, ttyconf: tty.Config, bytes: []const u8) !void {
255 var chunks = mem.window(u8, bytes, 16, 16);255 var chunks = mem.window(u8, bytes, 16, 16);
256 while (chunks.next()) |window| {256 while (chunks.next()) |window| {
257 // 1. Print the address.257 // 1. Print the address.
...@@ -302,7 +302,7 @@ pub fn dumpHexFallible(bw: *Writer, ttyconf: std.io.tty.Config, bytes: []const u...@@ -302,7 +302,7 @@ pub fn dumpHexFallible(bw: *Writer, ttyconf: std.io.tty.Config, bytes: []const u
302302
303test dumpHexFallible {303test dumpHexFallible {
304 const bytes: []const u8 = &.{ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x01, 0x12, 0x13 };304 const bytes: []const u8 = &.{ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x01, 0x12, 0x13 };
305 var aw: std.io.Writer.Allocating = .init(std.testing.allocator);305 var aw: Writer.Allocating = .init(std.testing.allocator);
306 defer aw.deinit();306 defer aw.deinit();
307307
308 try dumpHexFallible(&aw.writer, .no_color, bytes);308 try dumpHexFallible(&aw.writer, .no_color, bytes);
...@@ -342,7 +342,7 @@ pub fn dumpCurrentStackTraceToWriter(start_addr: ?usize, writer: *Writer) !void...@@ -342,7 +342,7 @@ pub fn dumpCurrentStackTraceToWriter(start_addr: ?usize, writer: *Writer) !void
342 try writer.print("Unable to dump stack trace: Unable to open debug info: {s}\n", .{@errorName(err)});342 try writer.print("Unable to dump stack trace: Unable to open debug info: {s}\n", .{@errorName(err)});
343 return;343 return;
344 };344 };
345 writeCurrentStackTrace(writer, debug_info, io.tty.detectConfig(.stderr()), start_addr) catch |err| {345 writeCurrentStackTrace(writer, debug_info, tty.detectConfig(.stderr()), start_addr) catch |err| {
346 try writer.print("Unable to dump stack trace: {s}\n", .{@errorName(err)});346 try writer.print("Unable to dump stack trace: {s}\n", .{@errorName(err)});
347 return;347 return;
348 };348 };
...@@ -427,7 +427,7 @@ pub fn dumpStackTraceFromBase(context: *ThreadContext, stderr: *Writer) void {...@@ -427,7 +427,7 @@ pub fn dumpStackTraceFromBase(context: *ThreadContext, stderr: *Writer) void {
427 stderr.print("Unable to dump stack trace: Unable to open debug info: {s}\n", .{@errorName(err)}) catch return;427 stderr.print("Unable to dump stack trace: Unable to open debug info: {s}\n", .{@errorName(err)}) catch return;
428 return;428 return;
429 };429 };
430 const tty_config = io.tty.detectConfig(.stderr());430 const tty_config = tty.detectConfig(.stderr());
431 if (native_os == .windows) {431 if (native_os == .windows) {
432 // On x86_64 and aarch64, the stack will be unwound using RtlVirtualUnwind using the context432 // On x86_64 and aarch64, the stack will be unwound using RtlVirtualUnwind using the context
433 // provided by the exception handler. On x86, RtlVirtualUnwind doesn't exist. Instead, a new backtrace433 // provided by the exception handler. On x86, RtlVirtualUnwind doesn't exist. Instead, a new backtrace
...@@ -533,7 +533,7 @@ pub fn dumpStackTrace(stack_trace: std.builtin.StackTrace) void {...@@ -533,7 +533,7 @@ pub fn dumpStackTrace(stack_trace: std.builtin.StackTrace) void {
533 stderr.print("Unable to dump stack trace: Unable to open debug info: {s}\n", .{@errorName(err)}) catch return;533 stderr.print("Unable to dump stack trace: Unable to open debug info: {s}\n", .{@errorName(err)}) catch return;
534 return;534 return;
535 };535 };
536 writeStackTrace(stack_trace, stderr, debug_info, io.tty.detectConfig(.stderr())) catch |err| {536 writeStackTrace(stack_trace, stderr, debug_info, tty.detectConfig(.stderr())) catch |err| {
537 stderr.print("Unable to dump stack trace: {s}\n", .{@errorName(err)}) catch return;537 stderr.print("Unable to dump stack trace: {s}\n", .{@errorName(err)}) catch return;
538 return;538 return;
539 };539 };
...@@ -738,7 +738,7 @@ pub fn writeStackTrace(...@@ -738,7 +738,7 @@ pub fn writeStackTrace(
738 stack_trace: std.builtin.StackTrace,738 stack_trace: std.builtin.StackTrace,
739 writer: *Writer,739 writer: *Writer,
740 debug_info: *SelfInfo,740 debug_info: *SelfInfo,
741 tty_config: io.tty.Config,741 tty_config: tty.Config,
742) !void {742) !void {
743 if (builtin.strip_debug_info) return error.MissingDebugInfo;743 if (builtin.strip_debug_info) return error.MissingDebugInfo;
744 var frame_index: usize = 0;744 var frame_index: usize = 0;
...@@ -959,7 +959,7 @@ pub const StackIterator = struct {...@@ -959,7 +959,7 @@ pub const StackIterator = struct {
959pub fn writeCurrentStackTrace(959pub fn writeCurrentStackTrace(
960 writer: *Writer,960 writer: *Writer,
961 debug_info: *SelfInfo,961 debug_info: *SelfInfo,
962 tty_config: io.tty.Config,962 tty_config: tty.Config,
963 start_addr: ?usize,963 start_addr: ?usize,
964) !void {964) !void {
965 if (native_os == .windows) {965 if (native_os == .windows) {
...@@ -1047,7 +1047,7 @@ pub noinline fn walkStackWindows(addresses: []usize, existing_context: ?*const w...@@ -1047,7 +1047,7 @@ pub noinline fn walkStackWindows(addresses: []usize, existing_context: ?*const w
1047pub fn writeStackTraceWindows(1047pub fn writeStackTraceWindows(
1048 writer: *Writer,1048 writer: *Writer,
1049 debug_info: *SelfInfo,1049 debug_info: *SelfInfo,
1050 tty_config: io.tty.Config,1050 tty_config: tty.Config,
1051 context: *const windows.CONTEXT,1051 context: *const windows.CONTEXT,
1052 start_addr: ?usize,1052 start_addr: ?usize,
1053) !void {1053) !void {
...@@ -1065,7 +1065,7 @@ pub fn writeStackTraceWindows(...@@ -1065,7 +1065,7 @@ pub fn writeStackTraceWindows(
1065 }1065 }
1066}1066}
10671067
1068fn printUnknownSource(debug_info: *SelfInfo, writer: *Writer, address: usize, tty_config: io.tty.Config) !void {1068fn printUnknownSource(debug_info: *SelfInfo, writer: *Writer, address: usize, tty_config: tty.Config) !void {
1069 const module_name = debug_info.getModuleNameForAddress(address);1069 const module_name = debug_info.getModuleNameForAddress(address);
1070 return printLineInfo(1070 return printLineInfo(
1071 writer,1071 writer,
...@@ -1078,14 +1078,14 @@ fn printUnknownSource(debug_info: *SelfInfo, writer: *Writer, address: usize, tt...@@ -1078,14 +1078,14 @@ fn printUnknownSource(debug_info: *SelfInfo, writer: *Writer, address: usize, tt
1078 );1078 );
1079}1079}
10801080
1081fn printLastUnwindError(it: *StackIterator, debug_info: *SelfInfo, writer: *Writer, tty_config: io.tty.Config) void {1081fn printLastUnwindError(it: *StackIterator, debug_info: *SelfInfo, writer: *Writer, tty_config: tty.Config) void {
1082 if (!have_ucontext) return;1082 if (!have_ucontext) return;
1083 if (it.getLastError()) |unwind_error| {1083 if (it.getLastError()) |unwind_error| {
1084 printUnwindError(debug_info, writer, unwind_error.address, unwind_error.err, tty_config) catch {};1084 printUnwindError(debug_info, writer, unwind_error.address, unwind_error.err, tty_config) catch {};
1085 }1085 }
1086}1086}
10871087
1088fn printUnwindError(debug_info: *SelfInfo, writer: *Writer, address: usize, err: UnwindError, tty_config: io.tty.Config) !void {1088fn printUnwindError(debug_info: *SelfInfo, writer: *Writer, address: usize, err: UnwindError, tty_config: tty.Config) !void {
1089 const module_name = debug_info.getModuleNameForAddress(address) orelse "???";1089 const module_name = debug_info.getModuleNameForAddress(address) orelse "???";
1090 try tty_config.setColor(writer, .dim);1090 try tty_config.setColor(writer, .dim);
1091 if (err == error.MissingDebugInfo) {1091 if (err == error.MissingDebugInfo) {
...@@ -1096,7 +1096,7 @@ fn printUnwindError(debug_info: *SelfInfo, writer: *Writer, address: usize, err:...@@ -1096,7 +1096,7 @@ fn printUnwindError(debug_info: *SelfInfo, writer: *Writer, address: usize, err:
1096 try tty_config.setColor(writer, .reset);1096 try tty_config.setColor(writer, .reset);
1097}1097}
10981098
1099pub fn printSourceAtAddress(debug_info: *SelfInfo, writer: *Writer, address: usize, tty_config: io.tty.Config) !void {1099pub fn printSourceAtAddress(debug_info: *SelfInfo, writer: *Writer, address: usize, tty_config: tty.Config) !void {
1100 const module = debug_info.getModuleForAddress(address) catch |err| switch (err) {1100 const module = debug_info.getModuleForAddress(address) catch |err| switch (err) {
1101 error.MissingDebugInfo, error.InvalidDebugInfo => return printUnknownSource(debug_info, writer, address, tty_config),1101 error.MissingDebugInfo, error.InvalidDebugInfo => return printUnknownSource(debug_info, writer, address, tty_config),
1102 else => return err,1102 else => return err,
...@@ -1125,7 +1125,7 @@ fn printLineInfo(...@@ -1125,7 +1125,7 @@ fn printLineInfo(
1125 address: usize,1125 address: usize,
1126 symbol_name: []const u8,1126 symbol_name: []const u8,
1127 compile_unit_name: []const u8,1127 compile_unit_name: []const u8,
1128 tty_config: io.tty.Config,1128 tty_config: tty.Config,
1129 comptime printLineFromFile: anytype,1129 comptime printLineFromFile: anytype,
1130) !void {1130) !void {
1131 nosuspend {1131 nosuspend {
...@@ -1597,10 +1597,10 @@ test "manage resources correctly" {...@@ -1597,10 +1597,10 @@ test "manage resources correctly" {
1597 // self-hosted debug info is still too buggy1597 // self-hosted debug info is still too buggy
1598 if (builtin.zig_backend != .stage2_llvm) return error.SkipZigTest;1598 if (builtin.zig_backend != .stage2_llvm) return error.SkipZigTest;
15991599
1600 var discarding: std.io.Writer.Discarding = .init(&.{});1600 var discarding: Writer.Discarding = .init(&.{});
1601 var di = try SelfInfo.open(testing.allocator);1601 var di = try SelfInfo.open(testing.allocator);
1602 defer di.deinit();1602 defer di.deinit();
1603 try printSourceAtAddress(&di, &discarding.writer, showMyTrace(), io.tty.detectConfig(.stderr()));1603 try printSourceAtAddress(&di, &discarding.writer, showMyTrace(), tty.detectConfig(.stderr()));
1604}1604}
16051605
1606noinline fn showMyTrace() usize {1606noinline fn showMyTrace() usize {
...@@ -1666,7 +1666,7 @@ pub fn ConfigurableTrace(comptime size: usize, comptime stack_frame_count: usize...@@ -1666,7 +1666,7 @@ pub fn ConfigurableTrace(comptime size: usize, comptime stack_frame_count: usize
1666 pub fn dump(t: @This()) void {1666 pub fn dump(t: @This()) void {
1667 if (!enabled) return;1667 if (!enabled) return;
16681668
1669 const tty_config = io.tty.detectConfig(.stderr());1669 const tty_config = tty.detectConfig(.stderr());
1670 const stderr = lockStderrWriter(&.{});1670 const stderr = lockStderrWriter(&.{});
1671 defer unlockStderrWriter();1671 defer unlockStderrWriter();
1672 const end = @min(t.index, size);1672 const end = @min(t.index, size);
lib/std/debug/Dwarf/call_frame.zig+37-44
...@@ -51,15 +51,9 @@ const Opcode = enum(u8) {...@@ -51,15 +51,9 @@ const Opcode = enum(u8) {
51 pub const hi_user = 0x3f;51 pub const hi_user = 0x3f;
52};52};
5353
54fn readBlock(stream: *std.io.FixedBufferStream([]const u8)) ![]const u8 {54fn readBlock(reader: *std.Io.Reader) ![]const u8 {
55 const reader = stream.reader();55 const block_len = try reader.takeLeb128(usize);
56 const block_len = try leb.readUleb128(usize, reader);56 return reader.take(block_len);
57 if (stream.pos + block_len > stream.buffer.len) return error.InvalidOperand;
58
59 const block = stream.buffer[stream.pos..][0..block_len];
60 reader.context.pos += block_len;
61
62 return block;
63}57}
6458
65pub const Instruction = union(Opcode) {59pub const Instruction = union(Opcode) {
...@@ -147,12 +141,11 @@ pub const Instruction = union(Opcode) {...@@ -147,12 +141,11 @@ pub const Instruction = union(Opcode) {
147 },141 },
148142
149 pub fn read(143 pub fn read(
150 stream: *std.io.FixedBufferStream([]const u8),144 reader: *std.Io.Reader,
151 addr_size_bytes: u8,145 addr_size_bytes: u8,
152 endian: std.builtin.Endian,146 endian: std.builtin.Endian,
153 ) !Instruction {147 ) !Instruction {
154 const reader = stream.reader();148 switch (try reader.takeByte()) {
155 switch (try reader.readByte()) {
156 Opcode.lo_inline...Opcode.hi_inline => |opcode| {149 Opcode.lo_inline...Opcode.hi_inline => |opcode| {
157 const e: Opcode = @enumFromInt(opcode & 0b11000000);150 const e: Opcode = @enumFromInt(opcode & 0b11000000);
158 const value: u6 = @intCast(opcode & 0b111111);151 const value: u6 = @intCast(opcode & 0b111111);
...@@ -163,7 +156,7 @@ pub const Instruction = union(Opcode) {...@@ -163,7 +156,7 @@ pub const Instruction = union(Opcode) {
163 .offset => .{156 .offset => .{
164 .offset = .{157 .offset = .{
165 .register = value,158 .register = value,
166 .offset = try leb.readUleb128(u64, reader),159 .offset = try reader.takeLeb128(u64),
167 },160 },
168 },161 },
169 .restore => .{162 .restore => .{
...@@ -183,111 +176,111 @@ pub const Instruction = union(Opcode) {...@@ -183,111 +176,111 @@ pub const Instruction = union(Opcode) {
183 .set_loc => .{176 .set_loc => .{
184 .set_loc = .{177 .set_loc = .{
185 .address = switch (addr_size_bytes) {178 .address = switch (addr_size_bytes) {
186 2 => try reader.readInt(u16, endian),179 2 => try reader.takeInt(u16, endian),
187 4 => try reader.readInt(u32, endian),180 4 => try reader.takeInt(u32, endian),
188 8 => try reader.readInt(u64, endian),181 8 => try reader.takeInt(u64, endian),
189 else => return error.InvalidAddrSize,182 else => return error.InvalidAddrSize,
190 },183 },
191 },184 },
192 },185 },
193 .advance_loc1 => .{186 .advance_loc1 => .{
194 .advance_loc1 = .{ .delta = try reader.readByte() },187 .advance_loc1 = .{ .delta = try reader.takeByte() },
195 },188 },
196 .advance_loc2 => .{189 .advance_loc2 => .{
197 .advance_loc2 = .{ .delta = try reader.readInt(u16, endian) },190 .advance_loc2 = .{ .delta = try reader.takeInt(u16, endian) },
198 },191 },
199 .advance_loc4 => .{192 .advance_loc4 => .{
200 .advance_loc4 = .{ .delta = try reader.readInt(u32, endian) },193 .advance_loc4 = .{ .delta = try reader.takeInt(u32, endian) },
201 },194 },
202 .offset_extended => .{195 .offset_extended => .{
203 .offset_extended = .{196 .offset_extended = .{
204 .register = try leb.readUleb128(u8, reader),197 .register = try reader.takeLeb128(u8),
205 .offset = try leb.readUleb128(u64, reader),198 .offset = try reader.takeLeb128(u64),
206 },199 },
207 },200 },
208 .restore_extended => .{201 .restore_extended => .{
209 .restore_extended = .{202 .restore_extended = .{
210 .register = try leb.readUleb128(u8, reader),203 .register = try reader.takeLeb128(u8),
211 },204 },
212 },205 },
213 .undefined => .{206 .undefined => .{
214 .undefined = .{207 .undefined = .{
215 .register = try leb.readUleb128(u8, reader),208 .register = try reader.takeLeb128(u8),
216 },209 },
217 },210 },
218 .same_value => .{211 .same_value => .{
219 .same_value = .{212 .same_value = .{
220 .register = try leb.readUleb128(u8, reader),213 .register = try reader.takeLeb128(u8),
221 },214 },
222 },215 },
223 .register => .{216 .register => .{
224 .register = .{217 .register = .{
225 .register = try leb.readUleb128(u8, reader),218 .register = try reader.takeLeb128(u8),
226 .target_register = try leb.readUleb128(u8, reader),219 .target_register = try reader.takeLeb128(u8),
227 },220 },
228 },221 },
229 .remember_state => .{ .remember_state = {} },222 .remember_state => .{ .remember_state = {} },
230 .restore_state => .{ .restore_state = {} },223 .restore_state => .{ .restore_state = {} },
231 .def_cfa => .{224 .def_cfa => .{
232 .def_cfa = .{225 .def_cfa = .{
233 .register = try leb.readUleb128(u8, reader),226 .register = try reader.takeLeb128(u8),
234 .offset = try leb.readUleb128(u64, reader),227 .offset = try reader.takeLeb128(u64),
235 },228 },
236 },229 },
237 .def_cfa_register => .{230 .def_cfa_register => .{
238 .def_cfa_register = .{231 .def_cfa_register = .{
239 .register = try leb.readUleb128(u8, reader),232 .register = try reader.takeLeb128(u8),
240 },233 },
241 },234 },
242 .def_cfa_offset => .{235 .def_cfa_offset => .{
243 .def_cfa_offset = .{236 .def_cfa_offset = .{
244 .offset = try leb.readUleb128(u64, reader),237 .offset = try reader.takeLeb128(u64),
245 },238 },
246 },239 },
247 .def_cfa_expression => .{240 .def_cfa_expression => .{
248 .def_cfa_expression = .{241 .def_cfa_expression = .{
249 .block = try readBlock(stream),242 .block = try readBlock(reader),
250 },243 },
251 },244 },
252 .expression => .{245 .expression => .{
253 .expression = .{246 .expression = .{
254 .register = try leb.readUleb128(u8, reader),247 .register = try reader.takeLeb128(u8),
255 .block = try readBlock(stream),248 .block = try readBlock(reader),
256 },249 },
257 },250 },
258 .offset_extended_sf => .{251 .offset_extended_sf => .{
259 .offset_extended_sf = .{252 .offset_extended_sf = .{
260 .register = try leb.readUleb128(u8, reader),253 .register = try reader.takeLeb128(u8),
261 .offset = try leb.readIleb128(i64, reader),254 .offset = try reader.takeLeb128(i64),
262 },255 },
263 },256 },
264 .def_cfa_sf => .{257 .def_cfa_sf => .{
265 .def_cfa_sf = .{258 .def_cfa_sf = .{
266 .register = try leb.readUleb128(u8, reader),259 .register = try reader.takeLeb128(u8),
267 .offset = try leb.readIleb128(i64, reader),260 .offset = try reader.takeLeb128(i64),
268 },261 },
269 },262 },
270 .def_cfa_offset_sf => .{263 .def_cfa_offset_sf => .{
271 .def_cfa_offset_sf = .{264 .def_cfa_offset_sf = .{
272 .offset = try leb.readIleb128(i64, reader),265 .offset = try reader.takeLeb128(i64),
273 },266 },
274 },267 },
275 .val_offset => .{268 .val_offset => .{
276 .val_offset = .{269 .val_offset = .{
277 .register = try leb.readUleb128(u8, reader),270 .register = try reader.takeLeb128(u8),
278 .offset = try leb.readUleb128(u64, reader),271 .offset = try reader.takeLeb128(u64),
279 },272 },
280 },273 },
281 .val_offset_sf => .{274 .val_offset_sf => .{
282 .val_offset_sf = .{275 .val_offset_sf = .{
283 .register = try leb.readUleb128(u8, reader),276 .register = try reader.takeLeb128(u8),
284 .offset = try leb.readIleb128(i64, reader),277 .offset = try reader.takeLeb128(i64),
285 },278 },
286 },279 },
287 .val_expression => .{280 .val_expression => .{
288 .val_expression = .{281 .val_expression = .{
289 .register = try leb.readUleb128(u8, reader),282 .register = try reader.takeLeb128(u8),
290 .block = try readBlock(stream),283 .block = try readBlock(reader),
291 },284 },
292 },285 },
293 };286 };
lib/std/debug/Dwarf/expression.zig+46-53
...@@ -62,7 +62,7 @@ pub const Error = error{...@@ -62,7 +62,7 @@ pub const Error = error{
62 InvalidTypeLength,62 InvalidTypeLength,
6363
64 TruncatedIntegralType,64 TruncatedIntegralType,
65} || abi.RegBytesError || error{ EndOfStream, Overflow, OutOfMemory, DivisionByZero };65} || abi.RegBytesError || error{ EndOfStream, Overflow, OutOfMemory, DivisionByZero, ReadFailed };
6666
67/// A stack machine that can decode and run DWARF expressions.67/// A stack machine that can decode and run DWARF expressions.
68/// Expressions can be decoded for non-native address size and endianness,68/// Expressions can be decoded for non-native address size and endianness,
...@@ -178,61 +178,60 @@ pub fn StackMachine(comptime options: Options) type {...@@ -178,61 +178,60 @@ pub fn StackMachine(comptime options: Options) type {
178 }178 }
179 }179 }
180180
181 pub fn readOperand(stream: *std.io.FixedBufferStream([]const u8), opcode: u8, context: Context) !?Operand {181 pub fn readOperand(reader: *std.Io.Reader, opcode: u8, context: Context) !?Operand {
182 const reader = stream.reader();
183 return switch (opcode) {182 return switch (opcode) {
184 OP.addr => generic(try reader.readInt(addr_type, options.endian)),183 OP.addr => generic(try reader.takeInt(addr_type, options.endian)),
185 OP.call_ref => switch (context.format) {184 OP.call_ref => switch (context.format) {
186 .@"32" => generic(try reader.readInt(u32, options.endian)),185 .@"32" => generic(try reader.takeInt(u32, options.endian)),
187 .@"64" => generic(try reader.readInt(u64, options.endian)),186 .@"64" => generic(try reader.takeInt(u64, options.endian)),
188 },187 },
189 OP.const1u,188 OP.const1u,
190 OP.pick,189 OP.pick,
191 => generic(try reader.readByte()),190 => generic(try reader.takeByte()),
192 OP.deref_size,191 OP.deref_size,
193 OP.xderef_size,192 OP.xderef_size,
194 => .{ .type_size = try reader.readByte() },193 => .{ .type_size = try reader.takeByte() },
195 OP.const1s => generic(try reader.readByteSigned()),194 OP.const1s => generic(try reader.takeByteSigned()),
196 OP.const2u,195 OP.const2u,
197 OP.call2,196 OP.call2,
198 => generic(try reader.readInt(u16, options.endian)),197 => generic(try reader.takeInt(u16, options.endian)),
199 OP.call4 => generic(try reader.readInt(u32, options.endian)),198 OP.call4 => generic(try reader.takeInt(u32, options.endian)),
200 OP.const2s => generic(try reader.readInt(i16, options.endian)),199 OP.const2s => generic(try reader.takeInt(i16, options.endian)),
201 OP.bra,200 OP.bra,
202 OP.skip,201 OP.skip,
203 => .{ .branch_offset = try reader.readInt(i16, options.endian) },202 => .{ .branch_offset = try reader.takeInt(i16, options.endian) },
204 OP.const4u => generic(try reader.readInt(u32, options.endian)),203 OP.const4u => generic(try reader.takeInt(u32, options.endian)),
205 OP.const4s => generic(try reader.readInt(i32, options.endian)),204 OP.const4s => generic(try reader.takeInt(i32, options.endian)),
206 OP.const8u => generic(try reader.readInt(u64, options.endian)),205 OP.const8u => generic(try reader.takeInt(u64, options.endian)),
207 OP.const8s => generic(try reader.readInt(i64, options.endian)),206 OP.const8s => generic(try reader.takeInt(i64, options.endian)),
208 OP.constu,207 OP.constu,
209 OP.plus_uconst,208 OP.plus_uconst,
210 OP.addrx,209 OP.addrx,
211 OP.constx,210 OP.constx,
212 OP.convert,211 OP.convert,
213 OP.reinterpret,212 OP.reinterpret,
214 => generic(try leb.readUleb128(u64, reader)),213 => generic(try reader.takeLeb128(u64)),
215 OP.consts,214 OP.consts,
216 OP.fbreg,215 OP.fbreg,
217 => generic(try leb.readIleb128(i64, reader)),216 => generic(try reader.takeLeb128(i64)),
218 OP.lit0...OP.lit31 => |n| generic(n - OP.lit0),217 OP.lit0...OP.lit31 => |n| generic(n - OP.lit0),
219 OP.reg0...OP.reg31 => |n| .{ .register = n - OP.reg0 },218 OP.reg0...OP.reg31 => |n| .{ .register = n - OP.reg0 },
220 OP.breg0...OP.breg31 => |n| .{ .base_register = .{219 OP.breg0...OP.breg31 => |n| .{ .base_register = .{
221 .base_register = n - OP.breg0,220 .base_register = n - OP.breg0,
222 .offset = try leb.readIleb128(i64, reader),221 .offset = try reader.takeLeb128(i64),
223 } },222 } },
224 OP.regx => .{ .register = try leb.readUleb128(u8, reader) },223 OP.regx => .{ .register = try reader.takeLeb128(u8) },
225 OP.bregx => blk: {224 OP.bregx => blk: {
226 const base_register = try leb.readUleb128(u8, reader);225 const base_register = try reader.takeLeb128(u8);
227 const offset = try leb.readIleb128(i64, reader);226 const offset = try reader.takeLeb128(i64);
228 break :blk .{ .base_register = .{227 break :blk .{ .base_register = .{
229 .base_register = base_register,228 .base_register = base_register,
230 .offset = offset,229 .offset = offset,
231 } };230 } };
232 },231 },
233 OP.regval_type => blk: {232 OP.regval_type => blk: {
234 const register = try leb.readUleb128(u8, reader);233 const register = try reader.takeLeb128(u8);
235 const type_offset = try leb.readUleb128(addr_type, reader);234 const type_offset = try reader.takeLeb128(addr_type);
236 break :blk .{ .register_type = .{235 break :blk .{ .register_type = .{
237 .register = register,236 .register = register,
238 .type_offset = type_offset,237 .type_offset = type_offset,
...@@ -240,33 +239,27 @@ pub fn StackMachine(comptime options: Options) type {...@@ -240,33 +239,27 @@ pub fn StackMachine(comptime options: Options) type {
240 },239 },
241 OP.piece => .{240 OP.piece => .{
242 .composite_location = .{241 .composite_location = .{
243 .size = try leb.readUleb128(u8, reader),242 .size = try reader.takeLeb128(u8),
244 .offset = 0,243 .offset = 0,
245 },244 },
246 },245 },
247 OP.bit_piece => blk: {246 OP.bit_piece => blk: {
248 const size = try leb.readUleb128(u8, reader);247 const size = try reader.takeLeb128(u8);
249 const offset = try leb.readIleb128(i64, reader);248 const offset = try reader.takeLeb128(i64);
250 break :blk .{ .composite_location = .{249 break :blk .{ .composite_location = .{
251 .size = size,250 .size = size,
252 .offset = offset,251 .offset = offset,
253 } };252 } };
254 },253 },
255 OP.implicit_value, OP.entry_value => blk: {254 OP.implicit_value, OP.entry_value => blk: {
256 const size = try leb.readUleb128(u8, reader);255 const size = try reader.takeLeb128(u8);
257 if (stream.pos + size > stream.buffer.len) return error.InvalidExpression;256 const block = try reader.take(size);
258 const block = stream.buffer[stream.pos..][0..size];257 break :blk .{ .block = block };
259 stream.pos += size;
260 break :blk .{
261 .block = block,
262 };
263 },258 },
264 OP.const_type => blk: {259 OP.const_type => blk: {
265 const type_offset = try leb.readUleb128(addr_type, reader);260 const type_offset = try reader.takeLeb128(addr_type);
266 const size = try reader.readByte();261 const size = try reader.takeByte();
267 if (stream.pos + size > stream.buffer.len) return error.InvalidExpression;262 const value_bytes = try reader.take(size);
268 const value_bytes = stream.buffer[stream.pos..][0..size];
269 stream.pos += size;
270 break :blk .{ .const_type = .{263 break :blk .{ .const_type = .{
271 .type_offset = type_offset,264 .type_offset = type_offset,
272 .value_bytes = value_bytes,265 .value_bytes = value_bytes,
...@@ -276,8 +269,8 @@ pub fn StackMachine(comptime options: Options) type {...@@ -276,8 +269,8 @@ pub fn StackMachine(comptime options: Options) type {
276 OP.xderef_type,269 OP.xderef_type,
277 => .{270 => .{
278 .deref_type = .{271 .deref_type = .{
279 .size = try reader.readByte(),272 .size = try reader.takeByte(),
280 .type_offset = try leb.readUleb128(addr_type, reader),273 .type_offset = try reader.takeLeb128(addr_type),
281 },274 },
282 },275 },
283 OP.lo_user...OP.hi_user => return error.UnimplementedUserOpcode,276 OP.lo_user...OP.hi_user => return error.UnimplementedUserOpcode,
...@@ -293,7 +286,7 @@ pub fn StackMachine(comptime options: Options) type {...@@ -293,7 +286,7 @@ pub fn StackMachine(comptime options: Options) type {
293 initial_value: ?usize,286 initial_value: ?usize,
294 ) Error!?Value {287 ) Error!?Value {
295 if (initial_value) |i| try self.stack.append(allocator, .{ .generic = i });288 if (initial_value) |i| try self.stack.append(allocator, .{ .generic = i });
296 var stream = std.io.fixedBufferStream(expression);289 var stream: std.Io.Reader = .fixed(expression);
297 while (try self.step(&stream, allocator, context)) {}290 while (try self.step(&stream, allocator, context)) {}
298 if (self.stack.items.len == 0) return null;291 if (self.stack.items.len == 0) return null;
299 return self.stack.items[self.stack.items.len - 1];292 return self.stack.items[self.stack.items.len - 1];
...@@ -302,14 +295,14 @@ pub fn StackMachine(comptime options: Options) type {...@@ -302,14 +295,14 @@ pub fn StackMachine(comptime options: Options) type {
302 /// Reads an opcode and its operands from `stream`, then executes it295 /// Reads an opcode and its operands from `stream`, then executes it
303 pub fn step(296 pub fn step(
304 self: *Self,297 self: *Self,
305 stream: *std.io.FixedBufferStream([]const u8),298 stream: *std.Io.Reader,
306 allocator: std.mem.Allocator,299 allocator: std.mem.Allocator,
307 context: Context,300 context: Context,
308 ) Error!bool {301 ) Error!bool {
309 if (@sizeOf(usize) != @sizeOf(addr_type) or options.endian != native_endian)302 if (@sizeOf(usize) != @sizeOf(addr_type) or options.endian != native_endian)
310 @compileError("Execution of non-native address sizes / endianness is not supported");303 @compileError("Execution of non-native address sizes / endianness is not supported");
311304
312 const opcode = try stream.reader().readByte();305 const opcode = try stream.takeByte();
313 if (options.call_frame_context and !isOpcodeValidInCFA(opcode)) return error.InvalidCFAOpcode;306 if (options.call_frame_context and !isOpcodeValidInCFA(opcode)) return error.InvalidCFAOpcode;
314 const operand = try readOperand(stream, opcode, context);307 const operand = try readOperand(stream, opcode, context);
315 switch (opcode) {308 switch (opcode) {
...@@ -663,11 +656,11 @@ pub fn StackMachine(comptime options: Options) type {...@@ -663,11 +656,11 @@ pub fn StackMachine(comptime options: Options) type {
663 if (condition) {656 if (condition) {
664 const new_pos = std.math.cast(657 const new_pos = std.math.cast(
665 usize,658 usize,
666 try std.math.add(isize, @as(isize, @intCast(stream.pos)), branch_offset),659 try std.math.add(isize, @as(isize, @intCast(stream.seek)), branch_offset),
667 ) orelse return error.InvalidExpression;660 ) orelse return error.InvalidExpression;
668661
669 if (new_pos < 0 or new_pos > stream.buffer.len) return error.InvalidExpression;662 if (new_pos < 0 or new_pos > stream.buffer.len) return error.InvalidExpression;
670 stream.pos = new_pos;663 stream.seek = new_pos;
671 }664 }
672 },665 },
673 OP.call2,666 OP.call2,
...@@ -746,7 +739,7 @@ pub fn StackMachine(comptime options: Options) type {...@@ -746,7 +739,7 @@ pub fn StackMachine(comptime options: Options) type {
746 if (isOpcodeRegisterLocation(block[0])) {739 if (isOpcodeRegisterLocation(block[0])) {
747 if (context.thread_context == null) return error.IncompleteExpressionContext;740 if (context.thread_context == null) return error.IncompleteExpressionContext;
748741
749 var block_stream = std.io.fixedBufferStream(block);742 var block_stream: std.Io.Reader = .fixed(block);
750 const register = (try readOperand(&block_stream, block[0], context)).?.register;743 const register = (try readOperand(&block_stream, block[0], context)).?.register;
751 const value = mem.readInt(usize, (try abi.regBytes(context.thread_context.?, register, context.reg_context))[0..@sizeOf(usize)], native_endian);744 const value = mem.readInt(usize, (try abi.regBytes(context.thread_context.?, register, context.reg_context))[0..@sizeOf(usize)], native_endian);
752 try self.stack.append(allocator, .{ .generic = value });745 try self.stack.append(allocator, .{ .generic = value });
...@@ -769,7 +762,7 @@ pub fn StackMachine(comptime options: Options) type {...@@ -769,7 +762,7 @@ pub fn StackMachine(comptime options: Options) type {
769 },762 },
770 }763 }
771764
772 return stream.pos < stream.buffer.len;765 return stream.seek < stream.buffer.len;
773 }766 }
774 };767 };
775}768}
...@@ -858,7 +851,7 @@ pub fn Builder(comptime options: Options) type {...@@ -858,7 +851,7 @@ pub fn Builder(comptime options: Options) type {
858 },851 },
859 .signed => {852 .signed => {
860 try writer.writeByte(OP.consts);853 try writer.writeByte(OP.consts);
861 try leb.writeIleb128(writer, value);854 try writer.writeLeb128(value);
862 },855 },
863 },856 },
864 }857 }
...@@ -892,19 +885,19 @@ pub fn Builder(comptime options: Options) type {...@@ -892,19 +885,19 @@ pub fn Builder(comptime options: Options) type {
892 // 2.5.1.2: Register Values885 // 2.5.1.2: Register Values
893 pub fn writeFbreg(writer: *Writer, offset: anytype) !void {886 pub fn writeFbreg(writer: *Writer, offset: anytype) !void {
894 try writer.writeByte(OP.fbreg);887 try writer.writeByte(OP.fbreg);
895 try leb.writeIleb128(writer, offset);888 try writer.writeSleb128(offset);
896 }889 }
897890
898 pub fn writeBreg(writer: *Writer, register: u8, offset: anytype) !void {891 pub fn writeBreg(writer: *Writer, register: u8, offset: anytype) !void {
899 if (register > 31) return error.InvalidRegister;892 if (register > 31) return error.InvalidRegister;
900 try writer.writeByte(OP.breg0 + register);893 try writer.writeByte(OP.breg0 + register);
901 try leb.writeIleb128(writer, offset);894 try writer.writeSleb128(offset);
902 }895 }
903896
904 pub fn writeBregx(writer: *Writer, register: anytype, offset: anytype) !void {897 pub fn writeBregx(writer: *Writer, register: anytype, offset: anytype) !void {
905 try writer.writeByte(OP.bregx);898 try writer.writeByte(OP.bregx);
906 try writer.writeUleb128(register);899 try writer.writeUleb128(register);
907 try leb.writeIleb128(writer, offset);900 try writer.writeSleb128(offset);
908 }901 }
909902
910 pub fn writeRegvalType(writer: *Writer, register: anytype, offset: anytype) !void {903 pub fn writeRegvalType(writer: *Writer, register: anytype, offset: anytype) !void {
lib/std/debug/SelfInfo.zig+4-7
...@@ -2017,15 +2017,12 @@ pub const VirtualMachine = struct {...@@ -2017,15 +2017,12 @@ pub const VirtualMachine = struct {
20172017
2018 var prev_row: Row = self.current_row;2018 var prev_row: Row = self.current_row;
20192019
2020 var cie_stream = std.io.fixedBufferStream(cie.initial_instructions);2020 var cie_stream: std.Io.Reader = .fixed(cie.initial_instructions);
2021 var fde_stream = std.io.fixedBufferStream(fde.instructions);2021 var fde_stream: std.Io.Reader = .fixed(fde.instructions);
2022 var streams = [_]*std.io.FixedBufferStream([]const u8){2022 const streams = [_]*std.Io.Reader{ &cie_stream, &fde_stream };
2023 &cie_stream,
2024 &fde_stream,
2025 };
20262023
2027 for (&streams, 0..) |stream, i| {2024 for (&streams, 0..) |stream, i| {
2028 while (stream.pos < stream.buffer.len) {2025 while (stream.seek < stream.buffer.len) {
2029 const instruction = try std.debug.Dwarf.call_frame.Instruction.read(stream, addr_size_bytes, endian);2026 const instruction = try std.debug.Dwarf.call_frame.Instruction.read(stream, addr_size_bytes, endian);
2030 prev_row = try self.step(allocator, cie, i == 0, instruction);2027 prev_row = try self.step(allocator, cie, i == 0, instruction);
2031 if (pc < fde.pc_begin + self.current_row.offset) return prev_row;2028 if (pc < fde.pc_begin + self.current_row.offset) return prev_row;
lib/std/elf.zig+1-1
...@@ -609,7 +609,7 @@ pub const ProgramHeaderBufferIterator = struct {...@@ -609,7 +609,7 @@ pub const ProgramHeaderBufferIterator = struct {
609 }609 }
610};610};
611611
612fn takePhdr(reader: *std.io.Reader, elf_header: Header) !?Elf64_Phdr {612fn takePhdr(reader: *std.Io.Reader, elf_header: Header) !?Elf64_Phdr {
613 if (elf_header.is_64) {613 if (elf_header.is_64) {
614 const phdr = try reader.takeStruct(Elf64_Phdr, elf_header.endian);614 const phdr = try reader.takeStruct(Elf64_Phdr, elf_header.endian);
615 return phdr;615 return phdr;
lib/std/fmt.zig+1-2
...@@ -3,7 +3,6 @@...@@ -3,7 +3,6 @@
3const builtin = @import("builtin");3const builtin = @import("builtin");
44
5const std = @import("std.zig");5const std = @import("std.zig");
6const io = std.io;
7const math = std.math;6const math = std.math;
8const assert = std.debug.assert;7const assert = std.debug.assert;
9const mem = std.mem;8const mem = std.mem;
...@@ -12,7 +11,7 @@ const lossyCast = math.lossyCast;...@@ -12,7 +11,7 @@ const lossyCast = math.lossyCast;
12const expectFmt = std.testing.expectFmt;11const expectFmt = std.testing.expectFmt;
13const testing = std.testing;12const testing = std.testing;
14const Allocator = std.mem.Allocator;13const Allocator = std.mem.Allocator;
15const Writer = std.io.Writer;14const Writer = std.Io.Writer;
1615
17pub const float = @import("fmt/float.zig");16pub const float = @import("fmt/float.zig");
1817
lib/std/fs/Dir.zig+48-30
...@@ -1977,41 +1977,59 @@ pub fn readFile(self: Dir, file_path: []const u8, buffer: []u8) ![]u8 {...@@ -1977,41 +1977,59 @@ pub fn readFile(self: Dir, file_path: []const u8, buffer: []u8) ![]u8 {
1977 return buffer[0..end_index];1977 return buffer[0..end_index];
1978}1978}
19791979
1980/// On success, caller owns returned buffer.1980pub const ReadFileAllocError = File.OpenError || File.ReadError || Allocator.Error || error{
1981/// If the file is larger than `max_bytes`, returns `error.FileTooBig`.1981 /// File size reached or exceeded the provided limit.
1982/// On Windows, `file_path` should be encoded as [WTF-8](https://simonsapin.github.io/wtf-8/).1982 StreamTooLong,
1983/// On WASI, `file_path` should be encoded as valid UTF-8.1983};
1984/// On other platforms, `file_path` is an opaque sequence of bytes with no particular encoding.1984
1985pub fn readFileAlloc(self: Dir, allocator: mem.Allocator, file_path: []const u8, max_bytes: usize) ![]u8 {1985/// Reads all the bytes from the named file. On success, caller owns returned
1986 return self.readFileAllocOptions(allocator, file_path, max_bytes, null, .of(u8), null);1986/// buffer.
1987///
1988/// If the file size is already known, a better alternative is to initialize a
1989/// `File.Reader`.
1990///
1991/// If the file size cannot be obtained, an error is returned. If
1992/// this is a realistic possibility, a better alternative is to initialize a
1993/// `File.Reader` which handles this seamlessly.
1994pub fn readFileAlloc(
1995 dir: Dir,
1996 /// On Windows, should be encoded as [WTF-8](https://simonsapin.github.io/wtf-8/).
1997 /// On WASI, should be encoded as valid UTF-8.
1998 /// On other platforms, an opaque sequence of bytes with no particular encoding.
1999 sub_path: []const u8,
2000 /// Used to allocate the result.
2001 gpa: Allocator,
2002 /// If reached or exceeded, `error.StreamTooLong` is returned instead.
2003 limit: std.Io.Limit,
2004) ReadFileAllocError![]u8 {
2005 return readFileAllocOptions(dir, sub_path, gpa, limit, .of(u8), null);
1987}2006}
19882007
1989/// On success, caller owns returned buffer.2008/// Reads all the bytes from the named file. On success, caller owns returned
1990/// If the file is larger than `max_bytes`, returns `error.FileTooBig`.2009/// buffer.
1991/// If `size_hint` is specified the initial buffer size is calculated using2010///
1992/// that value, otherwise the effective file size is used instead.2011/// If the file size is already known, a better alternative is to initialize a
1993/// Allows specifying alignment and a sentinel value.2012/// `File.Reader`.
1994/// On Windows, `file_path` should be encoded as [WTF-8](https://simonsapin.github.io/wtf-8/).
1995/// On WASI, `file_path` should be encoded as valid UTF-8.
1996/// On other platforms, `file_path` is an opaque sequence of bytes with no particular encoding.
1997pub fn readFileAllocOptions(2013pub fn readFileAllocOptions(
1998 self: Dir,2014 dir: Dir,
1999 allocator: mem.Allocator,2015 /// On Windows, should be encoded as [WTF-8](https://simonsapin.github.io/wtf-8/).
2000 file_path: []const u8,2016 /// On WASI, should be encoded as valid UTF-8.
2001 max_bytes: usize,2017 /// On other platforms, an opaque sequence of bytes with no particular encoding.
2002 size_hint: ?usize,2018 sub_path: []const u8,
2019 /// Used to allocate the result.
2020 gpa: Allocator,
2021 /// If reached or exceeded, `error.StreamTooLong` is returned instead.
2022 limit: std.Io.Limit,
2003 comptime alignment: std.mem.Alignment,2023 comptime alignment: std.mem.Alignment,
2004 comptime optional_sentinel: ?u8,2024 comptime sentinel: ?u8,
2005) !(if (optional_sentinel) |s| [:s]align(alignment.toByteUnits()) u8 else []align(alignment.toByteUnits()) u8) {2025) ReadFileAllocError!(if (sentinel) |s| [:s]align(alignment.toByteUnits()) u8 else []align(alignment.toByteUnits()) u8) {
2006 var file = try self.openFile(file_path, .{});2026 var file = try dir.openFile(sub_path, .{});
2007 defer file.close();2027 defer file.close();
20082028 var file_reader = file.reader(&.{});
2009 // If the file size doesn't fit a usize it'll be certainly greater than2029 return file_reader.interface.allocRemainingAlignedSentinel(gpa, limit, alignment, sentinel) catch |err| switch (err) {
2010 // `max_bytes`2030 error.ReadFailed => return file_reader.err.?,
2011 const stat_size = size_hint orelse std.math.cast(usize, try file.getEndPos()) orelse2031 error.OutOfMemory, error.StreamTooLong => |e| return e,
2012 return error.FileTooBig;2032 };
2013
2014 return file.readToEndAllocOptions(allocator, max_bytes, stat_size, alignment, optional_sentinel);
2015}2033}
20162034
2017pub const DeleteTreeError = error{2035pub const DeleteTreeError = error{
lib/std/fs/File.zig-45
...@@ -7,7 +7,6 @@ const File = @This();...@@ -7,7 +7,6 @@ const File = @This();
7const std = @import("../std.zig");7const std = @import("../std.zig");
8const Allocator = std.mem.Allocator;8const Allocator = std.mem.Allocator;
9const posix = std.posix;9const posix = std.posix;
10const io = std.io;
11const math = std.math;10const math = std.math;
12const assert = std.debug.assert;11const assert = std.debug.assert;
13const linux = std.os.linux;12const linux = std.os.linux;
...@@ -805,42 +804,6 @@ pub fn updateTimes(...@@ -805,42 +804,6 @@ pub fn updateTimes(
805 try posix.futimens(self.handle, &times);804 try posix.futimens(self.handle, &times);
806}805}
807806
808/// Deprecated in favor of `Reader`.
809pub fn readToEndAlloc(self: File, allocator: Allocator, max_bytes: usize) ![]u8 {
810 return self.readToEndAllocOptions(allocator, max_bytes, null, .of(u8), null);
811}
812
813/// Deprecated in favor of `Reader`.
814pub fn readToEndAllocOptions(
815 self: File,
816 allocator: Allocator,
817 max_bytes: usize,
818 size_hint: ?usize,
819 comptime alignment: Alignment,
820 comptime optional_sentinel: ?u8,
821) !(if (optional_sentinel) |s| [:s]align(alignment.toByteUnits()) u8 else []align(alignment.toByteUnits()) u8) {
822 // If no size hint is provided fall back to the size=0 code path
823 const size = size_hint orelse 0;
824
825 // The file size returned by stat is used as hint to set the buffer
826 // size. If the reported size is zero, as it happens on Linux for files
827 // in /proc, a small buffer is allocated instead.
828 const initial_cap = @min((if (size > 0) size else 1024), max_bytes) + @intFromBool(optional_sentinel != null);
829 var array_list = try std.array_list.AlignedManaged(u8, alignment).initCapacity(allocator, initial_cap);
830 defer array_list.deinit();
831
832 self.deprecatedReader().readAllArrayListAligned(alignment, &array_list, max_bytes) catch |err| switch (err) {
833 error.StreamTooLong => return error.FileTooBig,
834 else => |e| return e,
835 };
836
837 if (optional_sentinel) |sentinel| {
838 return try array_list.toOwnedSliceSentinel(sentinel);
839 } else {
840 return try array_list.toOwnedSlice();
841 }
842}
843
844pub const ReadError = posix.ReadError;807pub const ReadError = posix.ReadError;
845pub const PReadError = posix.PReadError;808pub const PReadError = posix.PReadError;
846809
...@@ -1089,14 +1052,6 @@ pub fn copyRangeAll(in: File, in_offset: u64, out: File, out_offset: u64, len: u...@@ -1089,14 +1052,6 @@ pub fn copyRangeAll(in: File, in_offset: u64, out: File, out_offset: u64, len: u
1089 return total_bytes_copied;1052 return total_bytes_copied;
1090}1053}
10911054
1092/// Deprecated in favor of `Reader`.
1093pub const DeprecatedReader = io.GenericReader(File, ReadError, read);
1094
1095/// Deprecated in favor of `Reader`.
1096pub fn deprecatedReader(file: File) DeprecatedReader {
1097 return .{ .context = file };
1098}
1099
1100/// Memoizes key information about a file handle such as:1055/// Memoizes key information about a file handle such as:
1101/// * The size from calling stat, or the error that occurred therein.1056/// * The size from calling stat, or the error that occurred therein.
1102/// * The current seek position.1057/// * The current seek position.
lib/std/fs/path.zig+1-1
...@@ -150,7 +150,7 @@ pub fn fmtJoin(paths: []const []const u8) std.fmt.Formatter([]const []const u8,...@@ -150,7 +150,7 @@ pub fn fmtJoin(paths: []const []const u8) std.fmt.Formatter([]const []const u8,
150 return .{ .data = paths };150 return .{ .data = paths };
151}151}
152152
153fn formatJoin(paths: []const []const u8, w: *std.io.Writer) std.io.Writer.Error!void {153fn formatJoin(paths: []const []const u8, w: *std.Io.Writer) std.Io.Writer.Error!void {
154 const first_path_idx = for (paths, 0..) |p, idx| {154 const first_path_idx = for (paths, 0..) |p, idx| {
155 if (p.len != 0) break idx;155 if (p.len != 0) break idx;
156 } else return;156 } else return;
lib/std/fs/test.zig+35-25
...@@ -676,37 +676,47 @@ test "Dir.realpath smoke test" {...@@ -676,37 +676,47 @@ test "Dir.realpath smoke test" {
676 }.impl);676 }.impl);
677}677}
678678
679test "readAllAlloc" {679test "readFileAlloc" {
680 var tmp_dir = tmpDir(.{});680 var tmp_dir = tmpDir(.{});
681 defer tmp_dir.cleanup();681 defer tmp_dir.cleanup();
682682
683 var file = try tmp_dir.dir.createFile("test_file", .{ .read = true });683 var file = try tmp_dir.dir.createFile("test_file", .{ .read = true });
684 defer file.close();684 defer file.close();
685685
686 const buf1 = try file.readToEndAlloc(testing.allocator, 1024);686 const buf1 = try tmp_dir.dir.readFileAlloc("test_file", testing.allocator, .limited(1024));
687 defer testing.allocator.free(buf1);687 defer testing.allocator.free(buf1);
688 try testing.expectEqual(@as(usize, 0), buf1.len);688 try testing.expectEqualStrings("", buf1);
689689
690 const write_buf: []const u8 = "this is a test.\nthis is a test.\nthis is a test.\nthis is a test.\n";690 const write_buf: []const u8 = "this is a test.\nthis is a test.\nthis is a test.\nthis is a test.\n";
691 try file.writeAll(write_buf);691 try file.writeAll(write_buf);
692 try file.seekTo(0);692
693693 {
694 // max_bytes > file_size694 // max_bytes > file_size
695 const buf2 = try file.readToEndAlloc(testing.allocator, 1024);695 const buf2 = try tmp_dir.dir.readFileAlloc("test_file", testing.allocator, .limited(1024));
696 defer testing.allocator.free(buf2);696 defer testing.allocator.free(buf2);
697 try testing.expectEqual(write_buf.len, buf2.len);697 try testing.expectEqualStrings(write_buf, buf2);
698 try testing.expectEqualStrings(write_buf, buf2);698 }
699 try file.seekTo(0);699
700700 {
701 // max_bytes == file_size701 // max_bytes == file_size
702 const buf3 = try file.readToEndAlloc(testing.allocator, write_buf.len);702 try testing.expectError(
703 defer testing.allocator.free(buf3);703 error.StreamTooLong,
704 try testing.expectEqual(write_buf.len, buf3.len);704 tmp_dir.dir.readFileAlloc("test_file", testing.allocator, .limited(write_buf.len)),
705 try testing.expectEqualStrings(write_buf, buf3);705 );
706 try file.seekTo(0);706 }
707
708 {
709 // max_bytes == file_size + 1
710 const buf2 = try tmp_dir.dir.readFileAlloc("test_file", testing.allocator, .limited(write_buf.len + 1));
711 defer testing.allocator.free(buf2);
712 try testing.expectEqualStrings(write_buf, buf2);
713 }
707714
708 // max_bytes < file_size715 // max_bytes < file_size
709 try testing.expectError(error.FileTooBig, file.readToEndAlloc(testing.allocator, write_buf.len - 1));716 try testing.expectError(
717 error.StreamTooLong,
718 tmp_dir.dir.readFileAlloc("test_file", testing.allocator, .limited(write_buf.len - 1)),
719 );
710}720}
711721
712test "Dir.statFile" {722test "Dir.statFile" {
...@@ -778,16 +788,16 @@ test "file operations on directories" {...@@ -778,16 +788,16 @@ test "file operations on directories" {
778 switch (native_os) {788 switch (native_os) {
779 .dragonfly, .netbsd => {789 .dragonfly, .netbsd => {
780 // no error when reading a directory. See https://github.com/ziglang/zig/issues/5732790 // no error when reading a directory. See https://github.com/ziglang/zig/issues/5732
781 const buf = try ctx.dir.readFileAlloc(testing.allocator, test_dir_name, std.math.maxInt(usize));791 const buf = try ctx.dir.readFileAlloc(test_dir_name, testing.allocator, .unlimited);
782 testing.allocator.free(buf);792 testing.allocator.free(buf);
783 },793 },
784 .wasi => {794 .wasi => {
785 // WASI return EBADF, which gets mapped to NotOpenForReading.795 // WASI return EBADF, which gets mapped to NotOpenForReading.
786 // See https://github.com/bytecodealliance/wasmtime/issues/1935796 // See https://github.com/bytecodealliance/wasmtime/issues/1935
787 try testing.expectError(error.NotOpenForReading, ctx.dir.readFileAlloc(testing.allocator, test_dir_name, std.math.maxInt(usize)));797 try testing.expectError(error.NotOpenForReading, ctx.dir.readFileAlloc(test_dir_name, testing.allocator, .unlimited));
788 },798 },
789 else => {799 else => {
790 try testing.expectError(error.IsDir, ctx.dir.readFileAlloc(testing.allocator, test_dir_name, std.math.maxInt(usize)));800 try testing.expectError(error.IsDir, ctx.dir.readFileAlloc(test_dir_name, testing.allocator, .unlimited));
791 },801 },
792 }802 }
793803
...@@ -1564,7 +1574,7 @@ test "copyFile" {...@@ -1564,7 +1574,7 @@ test "copyFile" {
1564}1574}
15651575
1566fn expectFileContents(dir: Dir, file_path: []const u8, data: []const u8) !void {1576fn expectFileContents(dir: Dir, file_path: []const u8, data: []const u8) !void {
1567 const contents = try dir.readFileAlloc(testing.allocator, file_path, 1000);1577 const contents = try dir.readFileAlloc(file_path, testing.allocator, .limited(1000));
1568 defer testing.allocator.free(contents);1578 defer testing.allocator.free(contents);
15691579
1570 try testing.expectEqualSlices(u8, data, contents);1580 try testing.expectEqualSlices(u8, data, contents);
...@@ -1587,7 +1597,7 @@ test "AtomicFile" {...@@ -1587,7 +1597,7 @@ test "AtomicFile" {
1587 try af.file_writer.interface.writeAll(test_content);1597 try af.file_writer.interface.writeAll(test_content);
1588 try af.finish();1598 try af.finish();
1589 }1599 }
1590 const content = try ctx.dir.readFileAlloc(allocator, test_out_file, 9999);1600 const content = try ctx.dir.readFileAlloc(test_out_file, allocator, .limited(9999));
1591 try testing.expectEqualStrings(test_content, content);1601 try testing.expectEqualStrings(test_content, content);
15921602
1593 try ctx.dir.deleteFile(test_out_file);1603 try ctx.dir.deleteFile(test_out_file);
...@@ -2004,7 +2014,7 @@ test "invalid UTF-8/WTF-8 paths" {...@@ -2004,7 +2014,7 @@ test "invalid UTF-8/WTF-8 paths" {
2004 }2014 }
20052015
2006 try testing.expectError(expected_err, ctx.dir.readFile(invalid_path, &[_]u8{}));2016 try testing.expectError(expected_err, ctx.dir.readFile(invalid_path, &[_]u8{}));
2007 try testing.expectError(expected_err, ctx.dir.readFileAlloc(testing.allocator, invalid_path, 0));2017 try testing.expectError(expected_err, ctx.dir.readFileAlloc(invalid_path, testing.allocator, .limited(0)));
20082018
2009 try testing.expectError(expected_err, ctx.dir.deleteTree(invalid_path));2019 try testing.expectError(expected_err, ctx.dir.deleteTree(invalid_path));
2010 try testing.expectError(expected_err, ctx.dir.deleteTreeMinStackSize(invalid_path));2020 try testing.expectError(expected_err, ctx.dir.deleteTreeMinStackSize(invalid_path));
lib/std/json.zig+2-2
...@@ -1,7 +1,7 @@...@@ -1,7 +1,7 @@
1//! JSON parsing and stringification conforming to RFC 8259. https://datatracker.ietf.org/doc/html/rfc82591//! JSON parsing and stringification conforming to RFC 8259. https://datatracker.ietf.org/doc/html/rfc8259
2//!2//!
3//! The low-level `Scanner` API produces `Token`s from an input slice or successive slices of inputs,3//! The low-level `Scanner` API produces `Token`s from an input slice or successive slices of inputs,
4//! The `Reader` API connects a `std.io.GenericReader` to a `Scanner`.4//! The `Reader` API connects a `std.Io.GenericReader` to a `Scanner`.
5//!5//!
6//! The high-level `parseFromSlice` and `parseFromTokenSource` deserialize a JSON document into a Zig type.6//! The high-level `parseFromSlice` and `parseFromTokenSource` deserialize a JSON document into a Zig type.
7//! Parse into a dynamically-typed `Value` to load any JSON value for runtime inspection.7//! Parse into a dynamically-typed `Value` to load any JSON value for runtime inspection.
...@@ -42,7 +42,7 @@ test Value {...@@ -42,7 +42,7 @@ test Value {
42}42}
4343
44test Stringify {44test Stringify {
45 var out: std.io.Writer.Allocating = .init(testing.allocator);45 var out: std.Io.Writer.Allocating = .init(testing.allocator);
46 var write_stream: Stringify = .{46 var write_stream: Stringify = .{
47 .writer = &out.writer,47 .writer = &out.writer,
48 .options = .{ .whitespace = .indent_2 },48 .options = .{ .whitespace = .indent_2 },
lib/std/json/Stringify.zig+3-3
...@@ -23,7 +23,7 @@ const Allocator = std.mem.Allocator;...@@ -23,7 +23,7 @@ const Allocator = std.mem.Allocator;
23const ArrayList = std.ArrayList;23const ArrayList = std.ArrayList;
24const BitStack = std.BitStack;24const BitStack = std.BitStack;
25const Stringify = @This();25const Stringify = @This();
26const Writer = std.io.Writer;26const Writer = std.Io.Writer;
2727
28const IndentationMode = enum(u1) {28const IndentationMode = enum(u1) {
29 object = 0,29 object = 0,
...@@ -576,7 +576,7 @@ pub fn value(v: anytype, options: Options, writer: *Writer) Error!void {...@@ -576,7 +576,7 @@ pub fn value(v: anytype, options: Options, writer: *Writer) Error!void {
576}576}
577577
578test value {578test value {
579 var out: std.io.Writer.Allocating = .init(std.testing.allocator);579 var out: Writer.Allocating = .init(std.testing.allocator);
580 const writer = &out.writer;580 const writer = &out.writer;
581 defer out.deinit();581 defer out.deinit();
582582
...@@ -616,7 +616,7 @@ test value {...@@ -616,7 +616,7 @@ test value {
616///616///
617/// Caller owns returned memory.617/// Caller owns returned memory.
618pub fn valueAlloc(gpa: Allocator, v: anytype, options: Options) error{OutOfMemory}![]u8 {618pub fn valueAlloc(gpa: Allocator, v: anytype, options: Options) error{OutOfMemory}![]u8 {
619 var aw: std.io.Writer.Allocating = .init(gpa);619 var aw: Writer.Allocating = .init(gpa);
620 defer aw.deinit();620 defer aw.deinit();
621 value(v, options, &aw.writer) catch return error.OutOfMemory;621 value(v, options, &aw.writer) catch return error.OutOfMemory;
622 return aw.toOwnedSlice();622 return aw.toOwnedSlice();
lib/std/json/dynamic_test.zig+1-1
...@@ -4,7 +4,7 @@ const mem = std.mem;...@@ -4,7 +4,7 @@ const mem = std.mem;
4const testing = std.testing;4const testing = std.testing;
5const ArenaAllocator = std.heap.ArenaAllocator;5const ArenaAllocator = std.heap.ArenaAllocator;
6const Allocator = std.mem.Allocator;6const Allocator = std.mem.Allocator;
7const Writer = std.io.Writer;7const Writer = std.Io.Writer;
88
9const ObjectMap = @import("dynamic.zig").ObjectMap;9const ObjectMap = @import("dynamic.zig").ObjectMap;
10const Array = @import("dynamic.zig").Array;10const Array = @import("dynamic.zig").Array;
lib/std/leb128.zig+22-251
...@@ -2,120 +2,6 @@ const builtin = @import("builtin");...@@ -2,120 +2,6 @@ const builtin = @import("builtin");
2const std = @import("std");2const std = @import("std");
3const testing = std.testing;3const testing = std.testing;
44
5/// Read a single unsigned LEB128 value from the given reader as type T,
6/// or error.Overflow if the value cannot fit.
7pub fn readUleb128(comptime T: type, reader: anytype) !T {
8 const U = if (@typeInfo(T).int.bits < 8) u8 else T;
9 const ShiftT = std.math.Log2Int(U);
10
11 const max_group = (@typeInfo(U).int.bits + 6) / 7;
12
13 var value: U = 0;
14 var group: ShiftT = 0;
15
16 while (group < max_group) : (group += 1) {
17 const byte = try reader.readByte();
18
19 const ov = @shlWithOverflow(@as(U, byte & 0x7f), group * 7);
20 if (ov[1] != 0) return error.Overflow;
21
22 value |= ov[0];
23 if (byte & 0x80 == 0) break;
24 } else {
25 return error.Overflow;
26 }
27
28 // only applies in the case that we extended to u8
29 if (U != T) {
30 if (value > std.math.maxInt(T)) return error.Overflow;
31 }
32
33 return @as(T, @truncate(value));
34}
35
36/// Read a single signed LEB128 value from the given reader as type T,
37/// or error.Overflow if the value cannot fit.
38pub fn readIleb128(comptime T: type, reader: anytype) !T {
39 const S = if (@typeInfo(T).int.bits < 8) i8 else T;
40 const U = std.meta.Int(.unsigned, @typeInfo(S).int.bits);
41 const ShiftU = std.math.Log2Int(U);
42
43 const max_group = (@typeInfo(U).int.bits + 6) / 7;
44
45 var value = @as(U, 0);
46 var group = @as(ShiftU, 0);
47
48 while (group < max_group) : (group += 1) {
49 const byte = try reader.readByte();
50
51 const shift = group * 7;
52 const ov = @shlWithOverflow(@as(U, byte & 0x7f), shift);
53 if (ov[1] != 0) {
54 // Overflow is ok so long as the sign bit is set and this is the last byte
55 if (byte & 0x80 != 0) return error.Overflow;
56 if (@as(S, @bitCast(ov[0])) >= 0) return error.Overflow;
57
58 // and all the overflowed bits are 1
59 const remaining_shift = @as(u3, @intCast(@typeInfo(U).int.bits - @as(u16, shift)));
60 const remaining_bits = @as(i8, @bitCast(byte | 0x80)) >> remaining_shift;
61 if (remaining_bits != -1) return error.Overflow;
62 } else {
63 // If we don't overflow and this is the last byte and the number being decoded
64 // is negative, check that the remaining bits are 1
65 if ((byte & 0x80 == 0) and (@as(S, @bitCast(ov[0])) < 0)) {
66 const remaining_shift = @as(u3, @intCast(@typeInfo(U).int.bits - @as(u16, shift)));
67 const remaining_bits = @as(i8, @bitCast(byte | 0x80)) >> remaining_shift;
68 if (remaining_bits != -1) return error.Overflow;
69 }
70 }
71
72 value |= ov[0];
73 if (byte & 0x80 == 0) {
74 const needs_sign_ext = group + 1 < max_group;
75 if (byte & 0x40 != 0 and needs_sign_ext) {
76 const ones = @as(S, -1);
77 value |= @as(U, @bitCast(ones)) << (shift + 7);
78 }
79 break;
80 }
81 } else {
82 return error.Overflow;
83 }
84
85 const result = @as(S, @bitCast(value));
86 // Only applies if we extended to i8
87 if (S != T) {
88 if (result > std.math.maxInt(T) or result < std.math.minInt(T)) return error.Overflow;
89 }
90
91 return @as(T, @truncate(result));
92}
93
94/// Write a single signed integer as signed LEB128 to the given writer.
95pub fn writeIleb128(writer: anytype, arg: anytype) !void {
96 const Arg = @TypeOf(arg);
97 const Int = switch (Arg) {
98 comptime_int => std.math.IntFittingRange(-@abs(arg), @abs(arg)),
99 else => Arg,
100 };
101 const Signed = if (@typeInfo(Int).int.bits < 8) i8 else Int;
102 const Unsigned = std.meta.Int(.unsigned, @typeInfo(Signed).int.bits);
103 var value: Signed = arg;
104
105 while (true) {
106 const unsigned: Unsigned = @bitCast(value);
107 const byte: u8 = @truncate(unsigned);
108 value >>= 6;
109 if (value == -1 or value == 0) {
110 try writer.writeByte(byte & 0x7F);
111 break;
112 } else {
113 value >>= 1;
114 try writer.writeByte(byte | 0x80);
115 }
116 }
117}
118
119/// This is an "advanced" function. It allows one to use a fixed amount of memory to store a5/// This is an "advanced" function. It allows one to use a fixed amount of memory to store a
120/// ULEB128. This defeats the entire purpose of using this data encoding; it will no longer use6/// ULEB128. This defeats the entire purpose of using this data encoding; it will no longer use
121/// fewer bytes to store smaller numbers. The advantage of using a fixed width is that it makes7/// fewer bytes to store smaller numbers. The advantage of using a fixed width is that it makes
...@@ -149,22 +35,26 @@ test writeUnsignedFixed {...@@ -149,22 +35,26 @@ test writeUnsignedFixed {
149 {35 {
150 var buf: [4]u8 = undefined;36 var buf: [4]u8 = undefined;
151 writeUnsignedFixed(4, &buf, 0);37 writeUnsignedFixed(4, &buf, 0);
152 try testing.expect((try test_read_uleb128(u64, &buf)) == 0);38 var reader: std.Io.Reader = .fixed(&buf);
39 try testing.expectEqual(0, try reader.takeLeb128(u64));
153 }40 }
154 {41 {
155 var buf: [4]u8 = undefined;42 var buf: [4]u8 = undefined;
156 writeUnsignedFixed(4, &buf, 1);43 writeUnsignedFixed(4, &buf, 1);
157 try testing.expect((try test_read_uleb128(u64, &buf)) == 1);44 var reader: std.Io.Reader = .fixed(&buf);
45 try testing.expectEqual(1, try reader.takeLeb128(u64));
158 }46 }
159 {47 {
160 var buf: [4]u8 = undefined;48 var buf: [4]u8 = undefined;
161 writeUnsignedFixed(4, &buf, 1000);49 writeUnsignedFixed(4, &buf, 1000);
162 try testing.expect((try test_read_uleb128(u64, &buf)) == 1000);50 var reader: std.Io.Reader = .fixed(&buf);
51 try testing.expectEqual(1000, try reader.takeLeb128(u64));
163 }52 }
164 {53 {
165 var buf: [4]u8 = undefined;54 var buf: [4]u8 = undefined;
166 writeUnsignedFixed(4, &buf, 10000000);55 writeUnsignedFixed(4, &buf, 10000000);
167 try testing.expect((try test_read_uleb128(u64, &buf)) == 10000000);56 var reader: std.Io.Reader = .fixed(&buf);
57 try testing.expectEqual(10000000, try reader.takeLeb128(u64));
168 }58 }
169}59}
17060
...@@ -193,162 +83,43 @@ test writeSignedFixed {...@@ -193,162 +83,43 @@ test writeSignedFixed {
193 {83 {
194 var buf: [4]u8 = undefined;84 var buf: [4]u8 = undefined;
195 writeSignedFixed(4, &buf, 0);85 writeSignedFixed(4, &buf, 0);
196 try testing.expect((try test_read_ileb128(i64, &buf)) == 0);86 var reader: std.Io.Reader = .fixed(&buf);
87 try testing.expectEqual(0, try reader.takeLeb128(i64));
197 }88 }
198 {89 {
199 var buf: [4]u8 = undefined;90 var buf: [4]u8 = undefined;
200 writeSignedFixed(4, &buf, 1);91 writeSignedFixed(4, &buf, 1);
201 try testing.expect((try test_read_ileb128(i64, &buf)) == 1);92 var reader: std.Io.Reader = .fixed(&buf);
93 try testing.expectEqual(1, try reader.takeLeb128(i64));
202 }94 }
203 {95 {
204 var buf: [4]u8 = undefined;96 var buf: [4]u8 = undefined;
205 writeSignedFixed(4, &buf, -1);97 writeSignedFixed(4, &buf, -1);
206 try testing.expect((try test_read_ileb128(i64, &buf)) == -1);98 var reader: std.Io.Reader = .fixed(&buf);
99 try testing.expectEqual(-1, try reader.takeLeb128(i64));
207 }100 }
208 {101 {
209 var buf: [4]u8 = undefined;102 var buf: [4]u8 = undefined;
210 writeSignedFixed(4, &buf, 1000);103 writeSignedFixed(4, &buf, 1000);
211 try testing.expect((try test_read_ileb128(i64, &buf)) == 1000);104 var reader: std.Io.Reader = .fixed(&buf);
105 try testing.expectEqual(1000, try reader.takeLeb128(i64));
212 }106 }
213 {107 {
214 var buf: [4]u8 = undefined;108 var buf: [4]u8 = undefined;
215 writeSignedFixed(4, &buf, -1000);109 writeSignedFixed(4, &buf, -1000);
216 try testing.expect((try test_read_ileb128(i64, &buf)) == -1000);110 var reader: std.Io.Reader = .fixed(&buf);
111 try testing.expectEqual(-1000, try reader.takeLeb128(i64));
217 }112 }
218 {113 {
219 var buf: [4]u8 = undefined;114 var buf: [4]u8 = undefined;
220 writeSignedFixed(4, &buf, -10000000);115 writeSignedFixed(4, &buf, -10000000);
221 try testing.expect((try test_read_ileb128(i64, &buf)) == -10000000);116 var reader: std.Io.Reader = .fixed(&buf);
117 try testing.expectEqual(-10000000, try reader.takeLeb128(i64));
222 }118 }
223 {119 {
224 var buf: [4]u8 = undefined;120 var buf: [4]u8 = undefined;
225 writeSignedFixed(4, &buf, 10000000);121 writeSignedFixed(4, &buf, 10000000);
226 try testing.expect((try test_read_ileb128(i64, &buf)) == 10000000);122 var reader: std.Io.Reader = .fixed(&buf);
123 try testing.expectEqual(10000000, try reader.takeLeb128(i64));
227 }124 }
228}125}
229
230// tests
231fn test_read_stream_ileb128(comptime T: type, encoded: []const u8) !T {
232 var reader = std.io.fixedBufferStream(encoded);
233 return try readIleb128(T, reader.reader());
234}
235
236fn test_read_stream_uleb128(comptime T: type, encoded: []const u8) !T {
237 var reader = std.io.fixedBufferStream(encoded);
238 return try readUleb128(T, reader.reader());
239}
240
241fn test_read_ileb128(comptime T: type, encoded: []const u8) !T {
242 var reader = std.io.fixedBufferStream(encoded);
243 const v1 = try readIleb128(T, reader.reader());
244 return v1;
245}
246
247fn test_read_uleb128(comptime T: type, encoded: []const u8) !T {
248 var reader = std.io.fixedBufferStream(encoded);
249 const v1 = try readUleb128(T, reader.reader());
250 return v1;
251}
252
253fn test_read_ileb128_seq(comptime T: type, comptime N: usize, encoded: []const u8) !void {
254 var reader = std.io.fixedBufferStream(encoded);
255 var i: usize = 0;
256 while (i < N) : (i += 1) {
257 _ = try readIleb128(T, reader.reader());
258 }
259}
260
261fn test_read_uleb128_seq(comptime T: type, comptime N: usize, encoded: []const u8) !void {
262 var reader = std.io.fixedBufferStream(encoded);
263 var i: usize = 0;
264 while (i < N) : (i += 1) {
265 _ = try readUleb128(T, reader.reader());
266 }
267}
268
269test "deserialize signed LEB128" {
270 // Truncated
271 try testing.expectError(error.EndOfStream, test_read_stream_ileb128(i64, "\x80"));
272
273 // Overflow
274 try testing.expectError(error.Overflow, test_read_ileb128(i8, "\x80\x80\x40"));
275 try testing.expectError(error.Overflow, test_read_ileb128(i16, "\x80\x80\x80\x40"));
276 try testing.expectError(error.Overflow, test_read_ileb128(i32, "\x80\x80\x80\x80\x40"));
277 try testing.expectError(error.Overflow, test_read_ileb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x40"));
278 try testing.expectError(error.Overflow, test_read_ileb128(i8, "\xff\x7e"));
279 try testing.expectError(error.Overflow, test_read_ileb128(i32, "\x80\x80\x80\x80\x08"));
280 try testing.expectError(error.Overflow, test_read_ileb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x01"));
281
282 // Decode SLEB128
283 try testing.expect((try test_read_ileb128(i64, "\x00")) == 0);
284 try testing.expect((try test_read_ileb128(i64, "\x01")) == 1);
285 try testing.expect((try test_read_ileb128(i64, "\x3f")) == 63);
286 try testing.expect((try test_read_ileb128(i64, "\x40")) == -64);
287 try testing.expect((try test_read_ileb128(i64, "\x41")) == -63);
288 try testing.expect((try test_read_ileb128(i64, "\x7f")) == -1);
289 try testing.expect((try test_read_ileb128(i64, "\x80\x01")) == 128);
290 try testing.expect((try test_read_ileb128(i64, "\x81\x01")) == 129);
291 try testing.expect((try test_read_ileb128(i64, "\xff\x7e")) == -129);
292 try testing.expect((try test_read_ileb128(i64, "\x80\x7f")) == -128);
293 try testing.expect((try test_read_ileb128(i64, "\x81\x7f")) == -127);
294 try testing.expect((try test_read_ileb128(i64, "\xc0\x00")) == 64);
295 try testing.expect((try test_read_ileb128(i64, "\xc7\x9f\x7f")) == -12345);
296 try testing.expect((try test_read_ileb128(i8, "\xff\x7f")) == -1);
297 try testing.expect((try test_read_ileb128(i16, "\xff\xff\x7f")) == -1);
298 try testing.expect((try test_read_ileb128(i32, "\xff\xff\xff\xff\x7f")) == -1);
299 try testing.expect((try test_read_ileb128(i32, "\x80\x80\x80\x80\x78")) == -0x80000000);
300 try testing.expect((try test_read_ileb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x7f")) == @as(i64, @bitCast(@as(u64, @intCast(0x8000000000000000)))));
301 try testing.expect((try test_read_ileb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x40")) == -0x4000000000000000);
302 try testing.expect((try test_read_ileb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x7f")) == -0x8000000000000000);
303
304 // Decode unnormalized SLEB128 with extra padding bytes.
305 try testing.expect((try test_read_ileb128(i64, "\x80\x00")) == 0);
306 try testing.expect((try test_read_ileb128(i64, "\x80\x80\x00")) == 0);
307 try testing.expect((try test_read_ileb128(i64, "\xff\x00")) == 0x7f);
308 try testing.expect((try test_read_ileb128(i64, "\xff\x80\x00")) == 0x7f);
309 try testing.expect((try test_read_ileb128(i64, "\x80\x81\x00")) == 0x80);
310 try testing.expect((try test_read_ileb128(i64, "\x80\x81\x80\x00")) == 0x80);
311
312 // Decode sequence of SLEB128 values
313 try test_read_ileb128_seq(i64, 4, "\x81\x01\x3f\x80\x7f\x80\x80\x80\x00");
314}
315
316test "deserialize unsigned LEB128" {
317 // Truncated
318 try testing.expectError(error.EndOfStream, test_read_stream_uleb128(u64, "\x80"));
319
320 // Overflow
321 try testing.expectError(error.Overflow, test_read_uleb128(u8, "\x80\x02"));
322 try testing.expectError(error.Overflow, test_read_uleb128(u8, "\x80\x80\x40"));
323 try testing.expectError(error.Overflow, test_read_uleb128(u16, "\x80\x80\x84"));
324 try testing.expectError(error.Overflow, test_read_uleb128(u16, "\x80\x80\x80\x40"));
325 try testing.expectError(error.Overflow, test_read_uleb128(u32, "\x80\x80\x80\x80\x90"));
326 try testing.expectError(error.Overflow, test_read_uleb128(u32, "\x80\x80\x80\x80\x40"));
327 try testing.expectError(error.Overflow, test_read_uleb128(u64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x40"));
328
329 // Decode ULEB128
330 try testing.expect((try test_read_uleb128(u64, "\x00")) == 0);
331 try testing.expect((try test_read_uleb128(u64, "\x01")) == 1);
332 try testing.expect((try test_read_uleb128(u64, "\x3f")) == 63);
333 try testing.expect((try test_read_uleb128(u64, "\x40")) == 64);
334 try testing.expect((try test_read_uleb128(u64, "\x7f")) == 0x7f);
335 try testing.expect((try test_read_uleb128(u64, "\x80\x01")) == 0x80);
336 try testing.expect((try test_read_uleb128(u64, "\x81\x01")) == 0x81);
337 try testing.expect((try test_read_uleb128(u64, "\x90\x01")) == 0x90);
338 try testing.expect((try test_read_uleb128(u64, "\xff\x01")) == 0xff);
339 try testing.expect((try test_read_uleb128(u64, "\x80\x02")) == 0x100);
340 try testing.expect((try test_read_uleb128(u64, "\x81\x02")) == 0x101);
341 try testing.expect((try test_read_uleb128(u64, "\x80\xc1\x80\x80\x10")) == 4294975616);
342 try testing.expect((try test_read_uleb128(u64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x01")) == 0x8000000000000000);
343
344 // Decode ULEB128 with extra padding bytes
345 try testing.expect((try test_read_uleb128(u64, "\x80\x00")) == 0);
346 try testing.expect((try test_read_uleb128(u64, "\x80\x80\x00")) == 0);
347 try testing.expect((try test_read_uleb128(u64, "\xff\x00")) == 0x7f);
348 try testing.expect((try test_read_uleb128(u64, "\xff\x80\x00")) == 0x7f);
349 try testing.expect((try test_read_uleb128(u64, "\x80\x81\x00")) == 0x80);
350 try testing.expect((try test_read_uleb128(u64, "\x80\x81\x80\x00")) == 0x80);
351
352 // Decode sequence of ULEB128 values
353 try test_read_uleb128_seq(u64, 4, "\x81\x01\x3f\x80\x7f\x80\x80\x80\x00");
354}
lib/std/macho.zig-1
...@@ -1,7 +1,6 @@...@@ -1,7 +1,6 @@
1const std = @import("std");1const std = @import("std");
2const builtin = @import("builtin");2const builtin = @import("builtin");
3const assert = std.debug.assert;3const assert = std.debug.assert;
4const io = std.io;
5const mem = std.mem;4const mem = std.mem;
6const meta = std.meta;5const meta = std.meta;
7const testing = std.testing;6const testing = std.testing;
lib/std/math/big/int.zig+5-5
...@@ -2029,11 +2029,11 @@ pub const Mutable = struct {...@@ -2029,11 +2029,11 @@ pub const Mutable = struct {
2029 r.len = llnormalize(r.limbs[0..length]);2029 r.len = llnormalize(r.limbs[0..length]);
2030 }2030 }
20312031
2032 pub fn format(self: Mutable, w: *std.io.Writer) std.io.Writer.Error!void {2032 pub fn format(self: Mutable, w: *std.Io.Writer) std.Io.Writer.Error!void {
2033 return formatNumber(self, w, .{});2033 return formatNumber(self, w, .{});
2034 }2034 }
20352035
2036 pub fn formatNumber(self: Const, w: *std.io.Writer, n: std.fmt.Number) std.io.Writer.Error!void {2036 pub fn formatNumber(self: Const, w: *std.Io.Writer, n: std.fmt.Number) std.Io.Writer.Error!void {
2037 return self.toConst().formatNumber(w, n);2037 return self.toConst().formatNumber(w, n);
2038 }2038 }
2039};2039};
...@@ -2326,7 +2326,7 @@ pub const Const = struct {...@@ -2326,7 +2326,7 @@ pub const Const = struct {
2326 /// this function will fail to print the string, printing "(BigInt)" instead of a number.2326 /// this function will fail to print the string, printing "(BigInt)" instead of a number.
2327 /// This is because the rendering algorithm requires reversing a string, which requires O(N) memory.2327 /// This is because the rendering algorithm requires reversing a string, which requires O(N) memory.
2328 /// See `toString` and `toStringAlloc` for a way to print big integers without failure.2328 /// See `toString` and `toStringAlloc` for a way to print big integers without failure.
2329 pub fn formatNumber(self: Const, w: *std.io.Writer, number: std.fmt.Number) std.io.Writer.Error!void {2329 pub fn formatNumber(self: Const, w: *std.Io.Writer, number: std.fmt.Number) std.Io.Writer.Error!void {
2330 const available_len = 64;2330 const available_len = 64;
2331 if (self.limbs.len > available_len)2331 if (self.limbs.len > available_len)
2332 return w.writeAll("(BigInt)");2332 return w.writeAll("(BigInt)");
...@@ -2907,7 +2907,7 @@ pub const Managed = struct {...@@ -2907,7 +2907,7 @@ pub const Managed = struct {
2907 }2907 }
29082908
2909 /// To allow `std.fmt.format` to work with `Managed`.2909 /// To allow `std.fmt.format` to work with `Managed`.
2910 pub fn format(self: Managed, w: *std.io.Writer) std.io.Writer.Error!void {2910 pub fn format(self: Managed, w: *std.Io.Writer) std.Io.Writer.Error!void {
2911 return formatNumber(self, w, .{});2911 return formatNumber(self, w, .{});
2912 }2912 }
29132913
...@@ -2915,7 +2915,7 @@ pub const Managed = struct {...@@ -2915,7 +2915,7 @@ pub const Managed = struct {
2915 /// this function will fail to print the string, printing "(BigInt)" instead of a number.2915 /// this function will fail to print the string, printing "(BigInt)" instead of a number.
2916 /// This is because the rendering algorithm requires reversing a string, which requires O(N) memory.2916 /// This is because the rendering algorithm requires reversing a string, which requires O(N) memory.
2917 /// See `toString` and `toStringAlloc` for a way to print big integers without failure.2917 /// See `toString` and `toStringAlloc` for a way to print big integers without failure.
2918 pub fn formatNumber(self: Managed, w: *std.io.Writer, n: std.fmt.Number) std.io.Writer.Error!void {2918 pub fn formatNumber(self: Managed, w: *std.Io.Writer, n: std.fmt.Number) std.Io.Writer.Error!void {
2919 return self.toConst().formatNumber(w, n);2919 return self.toConst().formatNumber(w, n);
2920 }2920 }
29212921
lib/std/os/uefi.zig+1-1
...@@ -106,7 +106,7 @@ pub const Guid = extern struct {...@@ -106,7 +106,7 @@ pub const Guid = extern struct {
106 node: [6]u8,106 node: [6]u8,
107107
108 /// Format GUID into hexadecimal lowercase xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx format108 /// Format GUID into hexadecimal lowercase xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx format
109 pub fn format(self: Guid, writer: *std.io.Writer) std.io.Writer.Error!void {109 pub fn format(self: Guid, writer: *std.Io.Writer) std.Io.Writer.Error!void {
110 const time_low = @byteSwap(self.time_low);110 const time_low = @byteSwap(self.time_low);
111 const time_mid = @byteSwap(self.time_mid);111 const time_mid = @byteSwap(self.time_mid);
112 const time_high_and_version = @byteSwap(self.time_high_and_version);112 const time_high_and_version = @byteSwap(self.time_high_and_version);
lib/std/os/uefi/protocol/file.zig-1
...@@ -1,6 +1,5 @@...@@ -1,6 +1,5 @@
1const std = @import("std");1const std = @import("std");
2const uefi = std.os.uefi;2const uefi = std.os.uefi;
3const io = std.io;
4const Guid = uefi.Guid;3const Guid = uefi.Guid;
5const Time = uefi.Time;4const Time = uefi.Time;
6const Status = uefi.Status;5const Status = uefi.Status;
lib/std/os/uefi/tables.zig+1-1
...@@ -90,7 +90,7 @@ pub const MemoryType = enum(u32) {...@@ -90,7 +90,7 @@ pub const MemoryType = enum(u32) {
90 return @truncate(as_int - vendor_start);90 return @truncate(as_int - vendor_start);
91 }91 }
9292
93 pub fn format(self: MemoryType, w: *std.io.Writer) std.io.Writer.Error!void {93 pub fn format(self: MemoryType, w: *std.Io.Writer) std.Io.Writer.Error!void {
94 if (self.toOem()) |oemval|94 if (self.toOem()) |oemval|
95 try w.print("OEM({X})", .{oemval})95 try w.print("OEM({X})", .{oemval})
96 else if (self.toVendor()) |vendorval|96 else if (self.toVendor()) |vendorval|
lib/std/pdb.zig-1
...@@ -8,7 +8,6 @@...@@ -8,7 +8,6 @@
8//! documentation and/or contributors.8//! documentation and/or contributors.
99
10const std = @import("std.zig");10const std = @import("std.zig");
11const io = std.io;
12const math = std.math;11const math = std.math;
13const mem = std.mem;12const mem = std.mem;
14const coff = std.coff;13const coff = std.coff;
lib/std/posix.zig+2-2
...@@ -671,8 +671,8 @@ fn getRandomBytesDevURandom(buf: []u8) !void {...@@ -671,8 +671,8 @@ fn getRandomBytesDevURandom(buf: []u8) !void {
671 }671 }
672672
673 const file: fs.File = .{ .handle = fd };673 const file: fs.File = .{ .handle = fd };
674 const stream = file.deprecatedReader();674 var file_reader = file.readerStreaming(&.{});
675 stream.readNoEof(buf) catch return error.Unexpected;675 file_reader.readSliceAll(buf) catch return error.Unexpected;
676}676}
677677
678/// Causes abnormal process termination.678/// Causes abnormal process termination.
lib/std/posix/test.zig+4-7
...@@ -4,7 +4,6 @@ const testing = std.testing;...@@ -4,7 +4,6 @@ const testing = std.testing;
4const expect = testing.expect;4const expect = testing.expect;
5const expectEqual = testing.expectEqual;5const expectEqual = testing.expectEqual;
6const expectError = testing.expectError;6const expectError = testing.expectError;
7const io = std.io;
8const fs = std.fs;7const fs = std.fs;
9const mem = std.mem;8const mem = std.mem;
10const elf = std.elf;9const elf = std.elf;
...@@ -706,12 +705,11 @@ test "mmap" {...@@ -706,12 +705,11 @@ test "mmap" {
706 );705 );
707 defer posix.munmap(data);706 defer posix.munmap(data);
708707
709 var mem_stream = io.fixedBufferStream(data);708 var stream: std.Io.Reader = .fixed(data);
710 const stream = mem_stream.reader();
711709
712 var i: usize = 0;710 var i: usize = 0;
713 while (i < alloc_size / @sizeOf(u32)) : (i += 1) {711 while (i < alloc_size / @sizeOf(u32)) : (i += 1) {
714 try testing.expectEqual(i, try stream.readInt(u32, .little));712 try testing.expectEqual(i, try stream.takeInt(u32, .little));
715 }713 }
716 }714 }
717715
...@@ -730,12 +728,11 @@ test "mmap" {...@@ -730,12 +728,11 @@ test "mmap" {
730 );728 );
731 defer posix.munmap(data);729 defer posix.munmap(data);
732730
733 var mem_stream = io.fixedBufferStream(data);731 var stream: std.Io.Reader = .fixed(data);
734 const stream = mem_stream.reader();
735732
736 var i: usize = alloc_size / 2 / @sizeOf(u32);733 var i: usize = alloc_size / 2 / @sizeOf(u32);
737 while (i < alloc_size / @sizeOf(u32)) : (i += 1) {734 while (i < alloc_size / @sizeOf(u32)) : (i += 1) {
738 try testing.expectEqual(i, try stream.readInt(u32, .little));735 try testing.expectEqual(i, try stream.takeInt(u32, .little));
739 }736 }
740 }737 }
741}738}
lib/std/process.zig+93-88
...@@ -1552,103 +1552,108 @@ pub fn getUserInfo(name: []const u8) !UserInfo {...@@ -1552,103 +1552,108 @@ pub fn getUserInfo(name: []const u8) !UserInfo {
1552pub fn posixGetUserInfo(name: []const u8) !UserInfo {1552pub fn posixGetUserInfo(name: []const u8) !UserInfo {
1553 const file = try std.fs.openFileAbsolute("/etc/passwd", .{});1553 const file = try std.fs.openFileAbsolute("/etc/passwd", .{});
1554 defer file.close();1554 defer file.close();
1555 var buffer: [4096]u8 = undefined;
1556 var file_reader = file.reader(&buffer);
1557 return posixGetUserInfoPasswdStream(name, &file_reader.interface) catch |err| switch (err) {
1558 error.ReadFailed => return file_reader.err.?,
1559 error.EndOfStream => return error.UserNotFound,
1560 error.CorruptPasswordFile => return error.CorruptPasswordFile,
1561 };
1562}
15551563
1556 const reader = file.deprecatedReader();1564fn posixGetUserInfoPasswdStream(name: []const u8, reader: *std.Io.Reader) !UserInfo {
1557
1558 const State = enum {1565 const State = enum {
1559 Start,1566 start,
1560 WaitForNextLine,1567 wait_for_next_line,
1561 SkipPassword,1568 skip_password,
1562 ReadUserId,1569 read_user_id,
1563 ReadGroupId,1570 read_group_id,
1564 };1571 };
15651572
1566 var buf: [std.heap.page_size_min]u8 = undefined;
1567 var name_index: usize = 0;1573 var name_index: usize = 0;
1568 var state = State.Start;
1569 var uid: posix.uid_t = 0;1574 var uid: posix.uid_t = 0;
1570 var gid: posix.gid_t = 0;1575 var gid: posix.gid_t = 0;
15711576
1572 while (true) {1577 sw: switch (State.start) {
1573 const amt_read = try reader.read(buf[0..]);1578 .start => switch (try reader.takeByte()) {
1574 for (buf[0..amt_read]) |byte| {1579 ':' => {
1575 switch (state) {1580 if (name_index == name.len) {
1576 .Start => switch (byte) {1581 continue :sw .skip_password;
1577 ':' => {1582 } else {
1578 state = if (name_index == name.len) State.SkipPassword else State.WaitForNextLine;1583 continue :sw .wait_for_next_line;
1579 },1584 }
1580 '\n' => return error.CorruptPasswordFile,1585 },
1581 else => {1586 '\n' => return error.CorruptPasswordFile,
1582 if (name_index == name.len or name[name_index] != byte) {1587 else => |byte| {
1583 state = .WaitForNextLine;1588 if (name_index == name.len or name[name_index] != byte) {
1584 }1589 continue :sw .wait_for_next_line;
1585 name_index += 1;1590 }
1586 },1591 name_index += 1;
1587 },1592 continue :sw .start;
1588 .WaitForNextLine => switch (byte) {1593 },
1589 '\n' => {1594 },
1590 name_index = 0;1595 .wait_for_next_line => switch (try reader.takeByte()) {
1591 state = .Start;1596 '\n' => {
1592 },1597 name_index = 0;
1593 else => continue,1598 continue :sw .start;
1594 },1599 },
1595 .SkipPassword => switch (byte) {1600 else => continue :sw .wait_for_next_line,
1596 '\n' => return error.CorruptPasswordFile,1601 },
1597 ':' => {1602 .skip_password => switch (try reader.takeByte()) {
1598 state = .ReadUserId;1603 '\n' => return error.CorruptPasswordFile,
1599 },1604 ':' => {
1600 else => continue,1605 continue :sw .read_user_id;
1601 },1606 },
1602 .ReadUserId => switch (byte) {1607 else => continue :sw .skip_password,
1603 ':' => {1608 },
1604 state = .ReadGroupId;1609 .read_user_id => switch (try reader.takeByte()) {
1605 },1610 ':' => {
1606 '\n' => return error.CorruptPasswordFile,1611 continue :sw .read_group_id;
1607 else => {1612 },
1608 const digit = switch (byte) {1613 '\n' => return error.CorruptPasswordFile,
1609 '0'...'9' => byte - '0',1614 else => |byte| {
1610 else => return error.CorruptPasswordFile,1615 const digit = switch (byte) {
1611 };1616 '0'...'9' => byte - '0',
1612 {1617 else => return error.CorruptPasswordFile,
1613 const ov = @mulWithOverflow(uid, 10);1618 };
1614 if (ov[1] != 0) return error.CorruptPasswordFile;1619 {
1615 uid = ov[0];1620 const ov = @mulWithOverflow(uid, 10);
1616 }1621 if (ov[1] != 0) return error.CorruptPasswordFile;
1617 {1622 uid = ov[0];
1618 const ov = @addWithOverflow(uid, digit);1623 }
1619 if (ov[1] != 0) return error.CorruptPasswordFile;1624 {
1620 uid = ov[0];1625 const ov = @addWithOverflow(uid, digit);
1621 }1626 if (ov[1] != 0) return error.CorruptPasswordFile;
1622 },1627 uid = ov[0];
1623 },1628 }
1624 .ReadGroupId => switch (byte) {1629 continue :sw .read_user_id;
1625 '\n', ':' => {1630 },
1626 return UserInfo{1631 },
1627 .uid = uid,1632 .read_group_id => switch (try reader.takeByte()) {
1628 .gid = gid,1633 '\n', ':' => return .{
1629 };1634 .uid = uid,
1630 },1635 .gid = gid,
1631 else => {1636 },
1632 const digit = switch (byte) {1637 else => |byte| {
1633 '0'...'9' => byte - '0',1638 const digit = switch (byte) {
1634 else => return error.CorruptPasswordFile,1639 '0'...'9' => byte - '0',
1635 };1640 else => return error.CorruptPasswordFile,
1636 {1641 };
1637 const ov = @mulWithOverflow(gid, 10);1642 {
1638 if (ov[1] != 0) return error.CorruptPasswordFile;1643 const ov = @mulWithOverflow(gid, 10);
1639 gid = ov[0];1644 if (ov[1] != 0) return error.CorruptPasswordFile;
1640 }1645 gid = ov[0];
1641 {1646 }
1642 const ov = @addWithOverflow(gid, digit);1647 {
1643 if (ov[1] != 0) return error.CorruptPasswordFile;1648 const ov = @addWithOverflow(gid, digit);
1644 gid = ov[0];1649 if (ov[1] != 0) return error.CorruptPasswordFile;
1645 }1650 gid = ov[0];
1646 },1651 }
1647 },1652 continue :sw .read_group_id;
1648 }1653 },
1649 }1654 },
1650 if (amt_read < buf.len) return error.UserNotFound;
1651 }1655 }
1656 comptime unreachable;
1652}1657}
16531658
1654pub fn getBaseAddress() usize {1659pub fn getBaseAddress() usize {
lib/std/std.zig-2
...@@ -78,8 +78,6 @@ pub const hash = @import("hash.zig");...@@ -78,8 +78,6 @@ pub const hash = @import("hash.zig");
78pub const hash_map = @import("hash_map.zig");78pub const hash_map = @import("hash_map.zig");
79pub const heap = @import("heap.zig");79pub const heap = @import("heap.zig");
80pub const http = @import("http.zig");80pub const http = @import("http.zig");
81/// Deprecated
82pub const io = Io;
83pub const json = @import("json.zig");81pub const json = @import("json.zig");
84pub const leb = @import("leb128.zig");82pub const leb = @import("leb128.zig");
85pub const log = @import("log.zig");83pub const log = @import("log.zig");
lib/std/tar/test.zig+5-5
...@@ -336,7 +336,7 @@ fn testCase(case: Case) !void {...@@ -336,7 +336,7 @@ fn testCase(case: Case) !void {
336 var file_name_buffer: [std.fs.max_path_bytes]u8 = undefined;336 var file_name_buffer: [std.fs.max_path_bytes]u8 = undefined;
337 var link_name_buffer: [std.fs.max_path_bytes]u8 = undefined;337 var link_name_buffer: [std.fs.max_path_bytes]u8 = undefined;
338338
339 var br: std.io.Reader = .fixed(case.data);339 var br: std.Io.Reader = .fixed(case.data);
340 var it: tar.Iterator = .init(&br, .{340 var it: tar.Iterator = .init(&br, .{
341 .file_name_buffer = &file_name_buffer,341 .file_name_buffer = &file_name_buffer,
342 .link_name_buffer = &link_name_buffer,342 .link_name_buffer = &link_name_buffer,
...@@ -387,7 +387,7 @@ fn testLongNameCase(case: Case) !void {...@@ -387,7 +387,7 @@ fn testLongNameCase(case: Case) !void {
387 var min_file_name_buffer: [256]u8 = undefined;387 var min_file_name_buffer: [256]u8 = undefined;
388 var min_link_name_buffer: [100]u8 = undefined;388 var min_link_name_buffer: [100]u8 = undefined;
389389
390 var br: std.io.Reader = .fixed(case.data);390 var br: std.Io.Reader = .fixed(case.data);
391 var iter: tar.Iterator = .init(&br, .{391 var iter: tar.Iterator = .init(&br, .{
392 .file_name_buffer = &min_file_name_buffer,392 .file_name_buffer = &min_file_name_buffer,
393 .link_name_buffer = &min_link_name_buffer,393 .link_name_buffer = &min_link_name_buffer,
...@@ -407,7 +407,7 @@ test "insufficient buffer in Header name filed" {...@@ -407,7 +407,7 @@ test "insufficient buffer in Header name filed" {
407 var min_file_name_buffer: [9]u8 = undefined;407 var min_file_name_buffer: [9]u8 = undefined;
408 var min_link_name_buffer: [100]u8 = undefined;408 var min_link_name_buffer: [100]u8 = undefined;
409409
410 var br: std.io.Reader = .fixed(gnu_case.data);410 var br: std.Io.Reader = .fixed(gnu_case.data);
411 var iter: tar.Iterator = .init(&br, .{411 var iter: tar.Iterator = .init(&br, .{
412 .file_name_buffer = &min_file_name_buffer,412 .file_name_buffer = &min_file_name_buffer,
413 .link_name_buffer = &min_link_name_buffer,413 .link_name_buffer = &min_link_name_buffer,
...@@ -462,7 +462,7 @@ test "should not overwrite existing file" {...@@ -462,7 +462,7 @@ test "should not overwrite existing file" {
462 // This ensures that file is not overwritten.462 // This ensures that file is not overwritten.
463 //463 //
464 const data = @embedFile("testdata/overwrite_file.tar");464 const data = @embedFile("testdata/overwrite_file.tar");
465 var r: std.io.Reader = .fixed(data);465 var r: std.Io.Reader = .fixed(data);
466466
467 // Unpack with strip_components = 1 should fail467 // Unpack with strip_components = 1 should fail
468 var root = std.testing.tmpDir(.{});468 var root = std.testing.tmpDir(.{});
...@@ -490,7 +490,7 @@ test "case sensitivity" {...@@ -490,7 +490,7 @@ test "case sensitivity" {
490 // 18089/alacritty/Darkermatrix.yml490 // 18089/alacritty/Darkermatrix.yml
491 //491 //
492 const data = @embedFile("testdata/18089.tar");492 const data = @embedFile("testdata/18089.tar");
493 var r: std.io.Reader = .fixed(data);493 var r: std.Io.Reader = .fixed(data);
494494
495 var root = std.testing.tmpDir(.{});495 var root = std.testing.tmpDir(.{});
496 defer root.cleanup();496 defer root.cleanup();
lib/std/testing.zig+8-8
...@@ -358,7 +358,7 @@ test expectApproxEqRel {...@@ -358,7 +358,7 @@ test expectApproxEqRel {
358/// This function is intended to be used only in tests. When the two slices are not358/// This function is intended to be used only in tests. When the two slices are not
359/// equal, prints diagnostics to stderr to show exactly how they are not equal (with359/// equal, prints diagnostics to stderr to show exactly how they are not equal (with
360/// the differences highlighted in red), then returns a test failure error.360/// the differences highlighted in red), then returns a test failure error.
361/// The colorized output is optional and controlled by the return of `std.io.tty.detectConfig()`.361/// The colorized output is optional and controlled by the return of `std.Io.tty.detectConfig()`.
362/// If your inputs are UTF-8 encoded strings, consider calling `expectEqualStrings` instead.362/// If your inputs are UTF-8 encoded strings, consider calling `expectEqualStrings` instead.
363pub fn expectEqualSlices(comptime T: type, expected: []const T, actual: []const T) !void {363pub fn expectEqualSlices(comptime T: type, expected: []const T, actual: []const T) !void {
364 const diff_index: usize = diff_index: {364 const diff_index: usize = diff_index: {
...@@ -381,7 +381,7 @@ fn failEqualSlices(...@@ -381,7 +381,7 @@ fn failEqualSlices(
381 expected: []const T,381 expected: []const T,
382 actual: []const T,382 actual: []const T,
383 diff_index: usize,383 diff_index: usize,
384 w: *std.io.Writer,384 w: *std.Io.Writer,
385) !void {385) !void {
386 try w.print("slices differ. first difference occurs at index {d} (0x{X})\n", .{ diff_index, diff_index });386 try w.print("slices differ. first difference occurs at index {d} (0x{X})\n", .{ diff_index, diff_index });
387387
...@@ -401,7 +401,7 @@ fn failEqualSlices(...@@ -401,7 +401,7 @@ fn failEqualSlices(
401 const actual_window = actual[window_start..@min(actual.len, window_start + max_window_size)];401 const actual_window = actual[window_start..@min(actual.len, window_start + max_window_size)];
402 const actual_truncated = window_start + actual_window.len < actual.len;402 const actual_truncated = window_start + actual_window.len < actual.len;
403403
404 const ttyconf = std.io.tty.detectConfig(.stderr());404 const ttyconf = std.Io.tty.detectConfig(.stderr());
405 var differ = if (T == u8) BytesDiffer{405 var differ = if (T == u8) BytesDiffer{
406 .expected = expected_window,406 .expected = expected_window,
407 .actual = actual_window,407 .actual = actual_window,
...@@ -467,11 +467,11 @@ fn SliceDiffer(comptime T: type) type {...@@ -467,11 +467,11 @@ fn SliceDiffer(comptime T: type) type {
467 start_index: usize,467 start_index: usize,
468 expected: []const T,468 expected: []const T,
469 actual: []const T,469 actual: []const T,
470 ttyconf: std.io.tty.Config,470 ttyconf: std.Io.tty.Config,
471471
472 const Self = @This();472 const Self = @This();
473473
474 pub fn write(self: Self, writer: *std.io.Writer) !void {474 pub fn write(self: Self, writer: *std.Io.Writer) !void {
475 for (self.expected, 0..) |value, i| {475 for (self.expected, 0..) |value, i| {
476 const full_index = self.start_index + i;476 const full_index = self.start_index + i;
477 const diff = if (i < self.actual.len) !std.meta.eql(self.actual[i], value) else true;477 const diff = if (i < self.actual.len) !std.meta.eql(self.actual[i], value) else true;
...@@ -490,9 +490,9 @@ fn SliceDiffer(comptime T: type) type {...@@ -490,9 +490,9 @@ fn SliceDiffer(comptime T: type) type {
490const BytesDiffer = struct {490const BytesDiffer = struct {
491 expected: []const u8,491 expected: []const u8,
492 actual: []const u8,492 actual: []const u8,
493 ttyconf: std.io.tty.Config,493 ttyconf: std.Io.tty.Config,
494494
495 pub fn write(self: BytesDiffer, writer: *std.io.Writer) !void {495 pub fn write(self: BytesDiffer, writer: *std.Io.Writer) !void {
496 var expected_iterator = std.mem.window(u8, self.expected, 16, 16);496 var expected_iterator = std.mem.window(u8, self.expected, 16, 16);
497 var row: usize = 0;497 var row: usize = 0;
498 while (expected_iterator.next()) |chunk| {498 while (expected_iterator.next()) |chunk| {
...@@ -538,7 +538,7 @@ const BytesDiffer = struct {...@@ -538,7 +538,7 @@ const BytesDiffer = struct {
538 }538 }
539 }539 }
540540
541 fn writeDiff(self: BytesDiffer, writer: *std.io.Writer, comptime fmt: []const u8, args: anytype, diff: bool) !void {541 fn writeDiff(self: BytesDiffer, writer: *std.Io.Writer, comptime fmt: []const u8, args: anytype, diff: bool) !void {
542 if (diff) try self.ttyconf.setColor(writer, .red);542 if (diff) try self.ttyconf.setColor(writer, .red);
543 try writer.print(fmt, args);543 try writer.print(fmt, args);
544 if (diff) try self.ttyconf.setColor(writer, .reset);544 if (diff) try self.ttyconf.setColor(writer, .reset);
lib/std/unicode.zig+2-2
...@@ -804,7 +804,7 @@ fn testDecode(bytes: []const u8) !u21 {...@@ -804,7 +804,7 @@ fn testDecode(bytes: []const u8) !u21 {
804/// Ill-formed UTF-8 byte sequences are replaced by the replacement character (U+FFFD)804/// Ill-formed UTF-8 byte sequences are replaced by the replacement character (U+FFFD)
805/// according to "U+FFFD Substitution of Maximal Subparts" from Chapter 3 of805/// according to "U+FFFD Substitution of Maximal Subparts" from Chapter 3 of
806/// the Unicode standard, and as specified by https://encoding.spec.whatwg.org/#utf-8-decoder806/// the Unicode standard, and as specified by https://encoding.spec.whatwg.org/#utf-8-decoder
807fn formatUtf8(utf8: []const u8, writer: *std.io.Writer) std.io.Writer.Error!void {807fn formatUtf8(utf8: []const u8, writer: *std.Io.Writer) std.Io.Writer.Error!void {
808 var buf: [300]u8 = undefined; // just an arbitrary size808 var buf: [300]u8 = undefined; // just an arbitrary size
809 var u8len: usize = 0;809 var u8len: usize = 0;
810810
...@@ -1464,7 +1464,7 @@ test calcWtf16LeLen {...@@ -1464,7 +1464,7 @@ test calcWtf16LeLen {
14641464
1465/// Print the given `utf16le` string, encoded as UTF-8 bytes.1465/// Print the given `utf16le` string, encoded as UTF-8 bytes.
1466/// Unpaired surrogates are replaced by the replacement character (U+FFFD).1466/// Unpaired surrogates are replaced by the replacement character (U+FFFD).
1467fn formatUtf16Le(utf16le: []const u16, writer: *std.io.Writer) std.io.Writer.Error!void {1467fn formatUtf16Le(utf16le: []const u16, writer: *std.Io.Writer) std.Io.Writer.Error!void {
1468 var buf: [300]u8 = undefined; // just an arbitrary size1468 var buf: [300]u8 = undefined; // just an arbitrary size
1469 var it = Utf16LeIterator.init(utf16le);1469 var it = Utf16LeIterator.init(utf16le);
1470 var u8len: usize = 0;1470 var u8len: usize = 0;
lib/std/zig.zig+3-3
...@@ -51,9 +51,9 @@ pub const Color = enum {...@@ -51,9 +51,9 @@ pub const Color = enum {
51 /// Assume stderr is a terminal.51 /// Assume stderr is a terminal.
52 on,52 on,
5353
54 pub fn get_tty_conf(color: Color) std.io.tty.Config {54 pub fn get_tty_conf(color: Color) std.Io.tty.Config {
55 return switch (color) {55 return switch (color) {
56 .auto => std.io.tty.detectConfig(std.fs.File.stderr()),56 .auto => std.Io.tty.detectConfig(std.fs.File.stderr()),
57 .on => .escape_codes,57 .on => .escape_codes,
58 .off => .no_color,58 .off => .no_color,
59 };59 };
...@@ -322,7 +322,7 @@ pub const BuildId = union(enum) {...@@ -322,7 +322,7 @@ pub const BuildId = union(enum) {
322 try std.testing.expectError(error.InvalidBuildIdStyle, parse("yaddaxxx"));322 try std.testing.expectError(error.InvalidBuildIdStyle, parse("yaddaxxx"));
323 }323 }
324324
325 pub fn format(id: BuildId, writer: *std.io.Writer) std.io.Writer.Error!void {325 pub fn format(id: BuildId, writer: *std.Io.Writer) std.Io.Writer.Error!void {
326 switch (id) {326 switch (id) {
327 .none, .fast, .uuid, .sha1, .md5 => {327 .none, .fast, .uuid, .sha1, .md5 => {
328 try writer.writeAll(@tagName(id));328 try writer.writeAll(@tagName(id));
lib/std/zig/Ast.zig+1-1
...@@ -204,7 +204,7 @@ pub fn parse(gpa: Allocator, source: [:0]const u8, mode: Mode) Allocator.Error!A...@@ -204,7 +204,7 @@ pub fn parse(gpa: Allocator, source: [:0]const u8, mode: Mode) Allocator.Error!A
204/// `gpa` is used for allocating the resulting formatted source code.204/// `gpa` is used for allocating the resulting formatted source code.
205/// Caller owns the returned slice of bytes, allocated with `gpa`.205/// Caller owns the returned slice of bytes, allocated with `gpa`.
206pub fn renderAlloc(tree: Ast, gpa: Allocator) error{OutOfMemory}![]u8 {206pub fn renderAlloc(tree: Ast, gpa: Allocator) error{OutOfMemory}![]u8 {
207 var aw: std.io.Writer.Allocating = .init(gpa);207 var aw: std.Io.Writer.Allocating = .init(gpa);
208 defer aw.deinit();208 defer aw.deinit();
209 render(tree, gpa, &aw.writer, .{}) catch |err| switch (err) {209 render(tree, gpa, &aw.writer, .{}) catch |err| switch (err) {
210 error.WriteFailed, error.OutOfMemory => return error.OutOfMemory,210 error.WriteFailed, error.OutOfMemory => return error.OutOfMemory,
lib/std/zig/Ast/Render.zig+2-2
...@@ -6,7 +6,7 @@ const meta = std.meta;...@@ -6,7 +6,7 @@ const meta = std.meta;
6const Ast = std.zig.Ast;6const Ast = std.zig.Ast;
7const Token = std.zig.Token;7const Token = std.zig.Token;
8const primitives = std.zig.primitives;8const primitives = std.zig.primitives;
9const Writer = std.io.Writer;9const Writer = std.Io.Writer;
1010
11const Render = @This();11const Render = @This();
1212
...@@ -2169,7 +2169,7 @@ fn renderArrayInit(...@@ -2169,7 +2169,7 @@ fn renderArrayInit(
21692169
2170 const section_exprs = row_exprs[0..section_end];2170 const section_exprs = row_exprs[0..section_end];
21712171
2172 var sub_expr_buffer: std.io.Writer.Allocating = .init(gpa);2172 var sub_expr_buffer: Writer.Allocating = .init(gpa);
2173 defer sub_expr_buffer.deinit();2173 defer sub_expr_buffer.deinit();
21742174
2175 const sub_expr_buffer_starts = try gpa.alloc(usize, section_exprs.len + 1);2175 const sub_expr_buffer_starts = try gpa.alloc(usize, section_exprs.len + 1);
lib/std/zig/AstGen.zig+2-2
...@@ -11339,7 +11339,7 @@ fn parseStrLit(...@@ -11339,7 +11339,7 @@ fn parseStrLit(
11339) InnerError!void {11339) InnerError!void {
11340 const raw_string = bytes[offset..];11340 const raw_string = bytes[offset..];
11341 const result = r: {11341 const result = r: {
11342 var aw: std.io.Writer.Allocating = .fromArrayList(astgen.gpa, buf);11342 var aw: std.Io.Writer.Allocating = .fromArrayList(astgen.gpa, buf);
11343 defer buf.* = aw.toArrayList();11343 defer buf.* = aw.toArrayList();
11344 break :r std.zig.string_literal.parseWrite(&aw.writer, raw_string) catch |err| switch (err) {11344 break :r std.zig.string_literal.parseWrite(&aw.writer, raw_string) catch |err| switch (err) {
11345 error.WriteFailed => return error.OutOfMemory,11345 error.WriteFailed => return error.OutOfMemory,
...@@ -13785,7 +13785,7 @@ fn lowerAstErrors(astgen: *AstGen) error{OutOfMemory}!void {...@@ -13785,7 +13785,7 @@ fn lowerAstErrors(astgen: *AstGen) error{OutOfMemory}!void {
13785 const tree = astgen.tree;13785 const tree = astgen.tree;
13786 assert(tree.errors.len > 0);13786 assert(tree.errors.len > 0);
1378713787
13788 var msg: std.io.Writer.Allocating = .init(gpa);13788 var msg: std.Io.Writer.Allocating = .init(gpa);
13789 defer msg.deinit();13789 defer msg.deinit();
13790 const msg_w = &msg.writer;13790 const msg_w = &msg.writer;
1379113791
lib/std/zig/ErrorBundle.zig+7-7
...@@ -11,7 +11,7 @@ const std = @import("std");...@@ -11,7 +11,7 @@ const std = @import("std");
11const ErrorBundle = @This();11const ErrorBundle = @This();
12const Allocator = std.mem.Allocator;12const Allocator = std.mem.Allocator;
13const assert = std.debug.assert;13const assert = std.debug.assert;
14const Writer = std.io.Writer;14const Writer = std.Io.Writer;
1515
16string_bytes: []const u8,16string_bytes: []const u8,
17/// The first thing in this array is an `ErrorMessageList`.17/// The first thing in this array is an `ErrorMessageList`.
...@@ -156,7 +156,7 @@ pub fn nullTerminatedString(eb: ErrorBundle, index: String) [:0]const u8 {...@@ -156,7 +156,7 @@ pub fn nullTerminatedString(eb: ErrorBundle, index: String) [:0]const u8 {
156}156}
157157
158pub const RenderOptions = struct {158pub const RenderOptions = struct {
159 ttyconf: std.io.tty.Config,159 ttyconf: std.Io.tty.Config,
160 include_reference_trace: bool = true,160 include_reference_trace: bool = true,
161 include_source_line: bool = true,161 include_source_line: bool = true,
162 include_log_text: bool = true,162 include_log_text: bool = true,
...@@ -190,14 +190,14 @@ fn renderErrorMessageToWriter(...@@ -190,14 +190,14 @@ fn renderErrorMessageToWriter(
190 err_msg_index: MessageIndex,190 err_msg_index: MessageIndex,
191 w: *Writer,191 w: *Writer,
192 kind: []const u8,192 kind: []const u8,
193 color: std.io.tty.Color,193 color: std.Io.tty.Color,
194 indent: usize,194 indent: usize,
195) (Writer.Error || std.posix.UnexpectedError)!void {195) (Writer.Error || std.posix.UnexpectedError)!void {
196 const ttyconf = options.ttyconf;196 const ttyconf = options.ttyconf;
197 const err_msg = eb.getErrorMessage(err_msg_index);197 const err_msg = eb.getErrorMessage(err_msg_index);
198 if (err_msg.src_loc != .none) {198 if (err_msg.src_loc != .none) {
199 const src = eb.extraData(SourceLocation, @intFromEnum(err_msg.src_loc));199 const src = eb.extraData(SourceLocation, @intFromEnum(err_msg.src_loc));
200 var prefix: std.io.Writer.Discarding = .init(&.{});200 var prefix: Writer.Discarding = .init(&.{});
201 try w.splatByteAll(' ', indent);201 try w.splatByteAll(' ', indent);
202 prefix.count += indent;202 prefix.count += indent;
203 try ttyconf.setColor(w, .bold);203 try ttyconf.setColor(w, .bold);
...@@ -794,9 +794,9 @@ pub const Wip = struct {...@@ -794,9 +794,9 @@ pub const Wip = struct {
794 };794 };
795 defer bundle.deinit(std.testing.allocator);795 defer bundle.deinit(std.testing.allocator);
796796
797 const ttyconf: std.io.tty.Config = .no_color;797 const ttyconf: std.Io.tty.Config = .no_color;
798798
799 var bundle_buf: std.io.Writer.Allocating = .init(std.testing.allocator);799 var bundle_buf: Writer.Allocating = .init(std.testing.allocator);
800 const bundle_bw = &bundle_buf.interface;800 const bundle_bw = &bundle_buf.interface;
801 defer bundle_buf.deinit();801 defer bundle_buf.deinit();
802 try bundle.renderToWriter(.{ .ttyconf = ttyconf }, bundle_bw);802 try bundle.renderToWriter(.{ .ttyconf = ttyconf }, bundle_bw);
...@@ -812,7 +812,7 @@ pub const Wip = struct {...@@ -812,7 +812,7 @@ pub const Wip = struct {
812 };812 };
813 defer copy.deinit(std.testing.allocator);813 defer copy.deinit(std.testing.allocator);
814814
815 var copy_buf: std.io.Writer.Allocating = .init(std.testing.allocator);815 var copy_buf: Writer.Allocating = .init(std.testing.allocator);
816 const copy_bw = &copy_buf.interface;816 const copy_bw = &copy_buf.interface;
817 defer copy_buf.deinit();817 defer copy_buf.deinit();
818 try copy.renderToWriter(.{ .ttyconf = ttyconf }, copy_bw);818 try copy.renderToWriter(.{ .ttyconf = ttyconf }, copy_bw);
lib/std/zig/LibCInstallation.zig+1-1
...@@ -43,7 +43,7 @@ pub fn parse(...@@ -43,7 +43,7 @@ pub fn parse(
43 }43 }
44 }44 }
4545
46 const contents = try std.fs.cwd().readFileAlloc(allocator, libc_file, std.math.maxInt(usize));46 const contents = try std.fs.cwd().readFileAlloc(libc_file, allocator, .limited(std.math.maxInt(usize)));
47 defer allocator.free(contents);47 defer allocator.free(contents);
4848
49 var it = std.mem.tokenizeScalar(u8, contents, '\n');49 var it = std.mem.tokenizeScalar(u8, contents, '\n');
lib/std/zig/WindowsSdk.zig+1-1
...@@ -766,7 +766,7 @@ const MsvcLibDir = struct {...@@ -766,7 +766,7 @@ const MsvcLibDir = struct {
766 writer.writeByte(std.fs.path.sep) catch unreachable;766 writer.writeByte(std.fs.path.sep) catch unreachable;
767 writer.writeAll("state.json") catch unreachable;767 writer.writeAll("state.json") catch unreachable;
768768
769 const json_contents = instances_dir.readFileAlloc(allocator, writer.buffered(), std.math.maxInt(usize)) catch continue;769 const json_contents = instances_dir.readFileAlloc(writer.buffered(), allocator, .limited(std.math.maxInt(usize))) catch continue;
770 defer allocator.free(json_contents);770 defer allocator.free(json_contents);
771771
772 var parsed = std.json.parseFromSlice(std.json.Value, allocator, json_contents, .{}) catch continue;772 var parsed = std.json.parseFromSlice(std.json.Value, allocator, json_contents, .{}) catch continue;
lib/std/zig/ZonGen.zig+4-4
...@@ -9,7 +9,7 @@ const StringIndexContext = std.hash_map.StringIndexContext;...@@ -9,7 +9,7 @@ const StringIndexContext = std.hash_map.StringIndexContext;
9const ZonGen = @This();9const ZonGen = @This();
10const Zoir = @import("Zoir.zig");10const Zoir = @import("Zoir.zig");
11const Ast = @import("Ast.zig");11const Ast = @import("Ast.zig");
12const Writer = std.io.Writer;12const Writer = std.Io.Writer;
1313
14gpa: Allocator,14gpa: Allocator,
15tree: Ast,15tree: Ast,
...@@ -472,7 +472,7 @@ fn appendIdentStr(zg: *ZonGen, ident_token: Ast.TokenIndex) error{ OutOfMemory,...@@ -472,7 +472,7 @@ fn appendIdentStr(zg: *ZonGen, ident_token: Ast.TokenIndex) error{ OutOfMemory,
472 const raw_string = zg.tree.tokenSlice(ident_token)[offset..];472 const raw_string = zg.tree.tokenSlice(ident_token)[offset..];
473 try zg.string_bytes.ensureUnusedCapacity(gpa, raw_string.len);473 try zg.string_bytes.ensureUnusedCapacity(gpa, raw_string.len);
474 const result = r: {474 const result = r: {
475 var aw: std.io.Writer.Allocating = .fromArrayList(gpa, &zg.string_bytes);475 var aw: Writer.Allocating = .fromArrayList(gpa, &zg.string_bytes);
476 defer zg.string_bytes = aw.toArrayList();476 defer zg.string_bytes = aw.toArrayList();
477 break :r std.zig.string_literal.parseWrite(&aw.writer, raw_string) catch |err| switch (err) {477 break :r std.zig.string_literal.parseWrite(&aw.writer, raw_string) catch |err| switch (err) {
478 error.WriteFailed => return error.OutOfMemory,478 error.WriteFailed => return error.OutOfMemory,
...@@ -570,7 +570,7 @@ fn strLitAsString(zg: *ZonGen, str_node: Ast.Node.Index) error{ OutOfMemory, Bad...@@ -570,7 +570,7 @@ fn strLitAsString(zg: *ZonGen, str_node: Ast.Node.Index) error{ OutOfMemory, Bad
570 const size_hint = strLitSizeHint(zg.tree, str_node);570 const size_hint = strLitSizeHint(zg.tree, str_node);
571 try string_bytes.ensureUnusedCapacity(gpa, size_hint);571 try string_bytes.ensureUnusedCapacity(gpa, size_hint);
572 const result = r: {572 const result = r: {
573 var aw: std.io.Writer.Allocating = .fromArrayList(gpa, &zg.string_bytes);573 var aw: Writer.Allocating = .fromArrayList(gpa, &zg.string_bytes);
574 defer zg.string_bytes = aw.toArrayList();574 defer zg.string_bytes = aw.toArrayList();
575 break :r parseStrLit(zg.tree, str_node, &aw.writer) catch |err| switch (err) {575 break :r parseStrLit(zg.tree, str_node, &aw.writer) catch |err| switch (err) {
576 error.WriteFailed => return error.OutOfMemory,576 error.WriteFailed => return error.OutOfMemory,
...@@ -885,7 +885,7 @@ fn lowerAstErrors(zg: *ZonGen) Allocator.Error!void {...@@ -885,7 +885,7 @@ fn lowerAstErrors(zg: *ZonGen) Allocator.Error!void {
885 const tree = zg.tree;885 const tree = zg.tree;
886 assert(tree.errors.len > 0);886 assert(tree.errors.len > 0);
887887
888 var msg: std.io.Writer.Allocating = .init(gpa);888 var msg: Writer.Allocating = .init(gpa);
889 defer msg.deinit();889 defer msg.deinit();
890 const msg_bw = &msg.writer;890 const msg_bw = &msg.writer;
891891
lib/std/zig/llvm/Builder.zig+1-1
...@@ -7,7 +7,7 @@ const builtin = @import("builtin");...@@ -7,7 +7,7 @@ const builtin = @import("builtin");
7const DW = std.dwarf;7const DW = std.dwarf;
8const ir = @import("ir.zig");8const ir = @import("ir.zig");
9const log = std.log.scoped(.llvm);9const log = std.log.scoped(.llvm);
10const Writer = std.io.Writer;10const Writer = std.Io.Writer;
1111
12gpa: Allocator,12gpa: Allocator,
13strip: bool,13strip: bool,
lib/std/zig/parser_test.zig-1
...@@ -1,7 +1,6 @@...@@ -1,7 +1,6 @@
1const std = @import("std");1const std = @import("std");
2const mem = std.mem;2const mem = std.mem;
3const print = std.debug.print;3const print = std.debug.print;
4const io = std.io;
5const maxInt = std.math.maxInt;4const maxInt = std.math.maxInt;
65
7test "zig fmt: remove extra whitespace at start and end of file with comment between" {6test "zig fmt: remove extra whitespace at start and end of file with comment between" {
lib/std/zig/string_literal.zig+3-3
...@@ -1,7 +1,7 @@...@@ -1,7 +1,7 @@
1const std = @import("../std.zig");1const std = @import("../std.zig");
2const assert = std.debug.assert;2const assert = std.debug.assert;
3const utf8Encode = std.unicode.utf8Encode;3const utf8Encode = std.unicode.utf8Encode;
4const Writer = std.io.Writer;4const Writer = std.Io.Writer;
55
6pub const ParseError = error{6pub const ParseError = error{
7 OutOfMemory,7 OutOfMemory,
...@@ -45,7 +45,7 @@ pub const Error = union(enum) {...@@ -45,7 +45,7 @@ pub const Error = union(enum) {
45 raw_string: []const u8,45 raw_string: []const u8,
46 };46 };
4747
48 fn formatMessage(self: FormatMessage, writer: *std.io.Writer) std.io.Writer.Error!void {48 fn formatMessage(self: FormatMessage, writer: *Writer) Writer.Error!void {
49 switch (self.err) {49 switch (self.err) {
50 .invalid_escape_character => |bad_index| try writer.print(50 .invalid_escape_character => |bad_index| try writer.print(
51 "invalid escape character: '{c}'",51 "invalid escape character: '{c}'",
...@@ -358,7 +358,7 @@ pub fn parseWrite(writer: *Writer, bytes: []const u8) Writer.Error!Result {...@@ -358,7 +358,7 @@ pub fn parseWrite(writer: *Writer, bytes: []const u8) Writer.Error!Result {
358/// Higher level API. Does not return extra info about parse errors.358/// Higher level API. Does not return extra info about parse errors.
359/// Caller owns returned memory.359/// Caller owns returned memory.
360pub fn parseAlloc(allocator: std.mem.Allocator, bytes: []const u8) ParseError![]u8 {360pub fn parseAlloc(allocator: std.mem.Allocator, bytes: []const u8) ParseError![]u8 {
361 var aw: std.io.Writer.Allocating = .init(allocator);361 var aw: Writer.Allocating = .init(allocator);
362 defer aw.deinit();362 defer aw.deinit();
363 const result = parseWrite(&aw.writer, bytes) catch |err| switch (err) {363 const result = parseWrite(&aw.writer, bytes) catch |err| switch (err) {
364 error.WriteFailed => return error.OutOfMemory,364 error.WriteFailed => return error.OutOfMemory,
lib/std/zip.zig+2-2
...@@ -195,12 +195,12 @@ pub const Decompress = struct {...@@ -195,12 +195,12 @@ pub const Decompress = struct {
195 };195 };
196 }196 }
197197
198 fn streamStore(r: *Reader, w: *Writer, limit: std.io.Limit) Reader.StreamError!usize {198 fn streamStore(r: *Reader, w: *Writer, limit: std.Io.Limit) Reader.StreamError!usize {
199 const d: *Decompress = @fieldParentPtr("interface", r);199 const d: *Decompress = @fieldParentPtr("interface", r);
200 return d.store.read(w, limit);200 return d.store.read(w, limit);
201 }201 }
202202
203 fn streamDeflate(r: *Reader, w: *Writer, limit: std.io.Limit) Reader.StreamError!usize {203 fn streamDeflate(r: *Reader, w: *Writer, limit: std.Io.Limit) Reader.StreamError!usize {
204 const d: *Decompress = @fieldParentPtr("interface", r);204 const d: *Decompress = @fieldParentPtr("interface", r);
205 return flate.Decompress.read(&d.inflate, w, limit);205 return flate.Decompress.read(&d.inflate, w, limit);
206 }206 }
lib/ubsan_rt.zig+1-1
...@@ -119,7 +119,7 @@ const Value = extern struct {...@@ -119,7 +119,7 @@ const Value = extern struct {
119 }119 }
120 }120 }
121121
122 pub fn format(value: Value, writer: *std.io.Writer) std.io.Writer.Error!void {122 pub fn format(value: Value, writer: *std.Io.Writer) std.Io.Writer.Error!void {
123 // Work around x86_64 backend limitation.123 // Work around x86_64 backend limitation.
124 if (builtin.zig_backend == .stage2_x86_64 and builtin.os.tag == .windows) {124 if (builtin.zig_backend == .stage2_x86_64 and builtin.os.tag == .windows) {
125 try writer.writeAll("(unknown)");125 try writer.writeAll("(unknown)");
src/Air.zig+1-1
...@@ -961,7 +961,7 @@ pub const Inst = struct {...@@ -961,7 +961,7 @@ pub const Inst = struct {
961 return index.unwrap().target;961 return index.unwrap().target;
962 }962 }
963963
964 pub fn format(index: Index, w: *std.io.Writer) std.io.Writer.Error!void {964 pub fn format(index: Index, w: *std.Io.Writer) std.Io.Writer.Error!void {
965 try w.writeByte('%');965 try w.writeByte('%');
966 switch (index.unwrap()) {966 switch (index.unwrap()) {
967 .ref => {},967 .ref => {},
src/Air/Liveness.zig+3-2
...@@ -10,6 +10,7 @@ const log = std.log.scoped(.liveness);...@@ -10,6 +10,7 @@ const log = std.log.scoped(.liveness);
10const assert = std.debug.assert;10const assert = std.debug.assert;
11const Allocator = std.mem.Allocator;11const Allocator = std.mem.Allocator;
12const Log2Int = std.math.Log2Int;12const Log2Int = std.math.Log2Int;
13const Writer = std.Io.Writer;
1314
14const Liveness = @This();15const Liveness = @This();
15const trace = @import("../tracy.zig").trace;16const trace = @import("../tracy.zig").trace;
...@@ -2037,7 +2038,7 @@ fn fmtInstSet(set: *const std.AutoHashMapUnmanaged(Air.Inst.Index, void)) FmtIns...@@ -2037,7 +2038,7 @@ fn fmtInstSet(set: *const std.AutoHashMapUnmanaged(Air.Inst.Index, void)) FmtIns
2037const FmtInstSet = struct {2038const FmtInstSet = struct {
2038 set: *const std.AutoHashMapUnmanaged(Air.Inst.Index, void),2039 set: *const std.AutoHashMapUnmanaged(Air.Inst.Index, void),
20392040
2040 pub fn format(val: FmtInstSet, w: *std.io.Writer) std.io.Writer.Error!void {2041 pub fn format(val: FmtInstSet, w: *Writer) Writer.Error!void {
2041 if (val.set.count() == 0) {2042 if (val.set.count() == 0) {
2042 try w.writeAll("[no instructions]");2043 try w.writeAll("[no instructions]");
2043 return;2044 return;
...@@ -2057,7 +2058,7 @@ fn fmtInstList(list: []const Air.Inst.Index) FmtInstList {...@@ -2057,7 +2058,7 @@ fn fmtInstList(list: []const Air.Inst.Index) FmtInstList {
2057const FmtInstList = struct {2058const FmtInstList = struct {
2058 list: []const Air.Inst.Index,2059 list: []const Air.Inst.Index,
20592060
2060 pub fn format(val: FmtInstList, w: *std.io.Writer) std.io.Writer.Error!void {2061 pub fn format(val: FmtInstList, w: *Writer) Writer.Error!void {
2061 if (val.list.len == 0) {2062 if (val.list.len == 0) {
2062 try w.writeAll("[no instructions]");2063 try w.writeAll("[no instructions]");
2063 return;2064 return;
src/Air/print.zig+48-48
...@@ -9,7 +9,7 @@ const Type = @import("../Type.zig");...@@ -9,7 +9,7 @@ const Type = @import("../Type.zig");
9const Air = @import("../Air.zig");9const Air = @import("../Air.zig");
10const InternPool = @import("../InternPool.zig");10const InternPool = @import("../InternPool.zig");
1111
12pub fn write(air: Air, stream: *std.io.Writer, pt: Zcu.PerThread, liveness: ?Air.Liveness) void {12pub fn write(air: Air, stream: *std.Io.Writer, pt: Zcu.PerThread, liveness: ?Air.Liveness) void {
13 comptime assert(build_options.enable_debug_extensions);13 comptime assert(build_options.enable_debug_extensions);
14 const instruction_bytes = air.instructions.len *14 const instruction_bytes = air.instructions.len *
15 // Here we don't use @sizeOf(Air.Inst.Data) because it would include15 // Here we don't use @sizeOf(Air.Inst.Data) because it would include
...@@ -55,7 +55,7 @@ pub fn write(air: Air, stream: *std.io.Writer, pt: Zcu.PerThread, liveness: ?Air...@@ -55,7 +55,7 @@ pub fn write(air: Air, stream: *std.io.Writer, pt: Zcu.PerThread, liveness: ?Air
5555
56pub fn writeInst(56pub fn writeInst(
57 air: Air,57 air: Air,
58 stream: *std.io.Writer,58 stream: *std.Io.Writer,
59 inst: Air.Inst.Index,59 inst: Air.Inst.Index,
60 pt: Zcu.PerThread,60 pt: Zcu.PerThread,
61 liveness: ?Air.Liveness,61 liveness: ?Air.Liveness,
...@@ -92,16 +92,16 @@ const Writer = struct {...@@ -92,16 +92,16 @@ const Writer = struct {
92 indent: usize,92 indent: usize,
93 skip_body: bool,93 skip_body: bool,
9494
95 const Error = std.io.Writer.Error;95 const Error = std.Io.Writer.Error;
9696
97 fn writeBody(w: *Writer, s: *std.io.Writer, body: []const Air.Inst.Index) Error!void {97 fn writeBody(w: *Writer, s: *std.Io.Writer, body: []const Air.Inst.Index) Error!void {
98 for (body) |inst| {98 for (body) |inst| {
99 try w.writeInst(s, inst);99 try w.writeInst(s, inst);
100 try s.writeByte('\n');100 try s.writeByte('\n');
101 }101 }
102 }102 }
103103
104 fn writeInst(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {104 fn writeInst(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
105 const tag = w.air.instructions.items(.tag)[@intFromEnum(inst)];105 const tag = w.air.instructions.items(.tag)[@intFromEnum(inst)];
106 try s.splatByteAll(' ', w.indent);106 try s.splatByteAll(' ', w.indent);
107 try s.print("{f}{c}= {s}(", .{107 try s.print("{f}{c}= {s}(", .{
...@@ -341,48 +341,48 @@ const Writer = struct {...@@ -341,48 +341,48 @@ const Writer = struct {
341 try s.writeByte(')');341 try s.writeByte(')');
342 }342 }
343343
344 fn writeBinOp(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {344 fn writeBinOp(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
345 const bin_op = w.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;345 const bin_op = w.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
346 try w.writeOperand(s, inst, 0, bin_op.lhs);346 try w.writeOperand(s, inst, 0, bin_op.lhs);
347 try s.writeAll(", ");347 try s.writeAll(", ");
348 try w.writeOperand(s, inst, 1, bin_op.rhs);348 try w.writeOperand(s, inst, 1, bin_op.rhs);
349 }349 }
350350
351 fn writeUnOp(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {351 fn writeUnOp(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
352 const un_op = w.air.instructions.items(.data)[@intFromEnum(inst)].un_op;352 const un_op = w.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
353 try w.writeOperand(s, inst, 0, un_op);353 try w.writeOperand(s, inst, 0, un_op);
354 }354 }
355355
356 fn writeNoOp(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {356 fn writeNoOp(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
357 _ = w;357 _ = w;
358 _ = s;358 _ = s;
359 _ = inst;359 _ = inst;
360 // no-op, no argument to write360 // no-op, no argument to write
361 }361 }
362362
363 fn writeType(w: *Writer, s: *std.io.Writer, ty: Type) !void {363 fn writeType(w: *Writer, s: *std.Io.Writer, ty: Type) !void {
364 return ty.print(s, w.pt);364 return ty.print(s, w.pt);
365 }365 }
366366
367 fn writeTy(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {367 fn writeTy(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
368 const ty = w.air.instructions.items(.data)[@intFromEnum(inst)].ty;368 const ty = w.air.instructions.items(.data)[@intFromEnum(inst)].ty;
369 try w.writeType(s, ty);369 try w.writeType(s, ty);
370 }370 }
371371
372 fn writeArg(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {372 fn writeArg(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
373 const arg = w.air.instructions.items(.data)[@intFromEnum(inst)].arg;373 const arg = w.air.instructions.items(.data)[@intFromEnum(inst)].arg;
374 try w.writeType(s, arg.ty.toType());374 try w.writeType(s, arg.ty.toType());
375 try s.print(", {d}", .{arg.zir_param_index});375 try s.print(", {d}", .{arg.zir_param_index});
376 }376 }
377377
378 fn writeTyOp(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {378 fn writeTyOp(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
379 const ty_op = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;379 const ty_op = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
380 try w.writeType(s, ty_op.ty.toType());380 try w.writeType(s, ty_op.ty.toType());
381 try s.writeAll(", ");381 try s.writeAll(", ");
382 try w.writeOperand(s, inst, 0, ty_op.operand);382 try w.writeOperand(s, inst, 0, ty_op.operand);
383 }383 }
384384
385 fn writeBlock(w: *Writer, s: *std.io.Writer, tag: Air.Inst.Tag, inst: Air.Inst.Index) Error!void {385 fn writeBlock(w: *Writer, s: *std.Io.Writer, tag: Air.Inst.Tag, inst: Air.Inst.Index) Error!void {
386 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;386 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
387 try w.writeType(s, ty_pl.ty.toType());387 try w.writeType(s, ty_pl.ty.toType());
388 const body: []const Air.Inst.Index = @ptrCast(switch (tag) {388 const body: []const Air.Inst.Index = @ptrCast(switch (tag) {
...@@ -423,7 +423,7 @@ const Writer = struct {...@@ -423,7 +423,7 @@ const Writer = struct {
423 }423 }
424 }424 }
425425
426 fn writeLoop(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {426 fn writeLoop(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
427 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;427 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
428 const extra = w.air.extraData(Air.Block, ty_pl.payload);428 const extra = w.air.extraData(Air.Block, ty_pl.payload);
429 const body: []const Air.Inst.Index = @ptrCast(w.air.extra.items[extra.end..][0..extra.data.body_len]);429 const body: []const Air.Inst.Index = @ptrCast(w.air.extra.items[extra.end..][0..extra.data.body_len]);
...@@ -439,7 +439,7 @@ const Writer = struct {...@@ -439,7 +439,7 @@ const Writer = struct {
439 try s.writeAll("}");439 try s.writeAll("}");
440 }440 }
441441
442 fn writeAggregateInit(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {442 fn writeAggregateInit(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
443 const zcu = w.pt.zcu;443 const zcu = w.pt.zcu;
444 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;444 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
445 const vector_ty = ty_pl.ty.toType();445 const vector_ty = ty_pl.ty.toType();
...@@ -455,7 +455,7 @@ const Writer = struct {...@@ -455,7 +455,7 @@ const Writer = struct {
455 try s.writeAll("]");455 try s.writeAll("]");
456 }456 }
457457
458 fn writeUnionInit(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {458 fn writeUnionInit(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
459 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;459 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
460 const extra = w.air.extraData(Air.UnionInit, ty_pl.payload).data;460 const extra = w.air.extraData(Air.UnionInit, ty_pl.payload).data;
461461
...@@ -463,7 +463,7 @@ const Writer = struct {...@@ -463,7 +463,7 @@ const Writer = struct {
463 try w.writeOperand(s, inst, 0, extra.init);463 try w.writeOperand(s, inst, 0, extra.init);
464 }464 }
465465
466 fn writeStructField(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {466 fn writeStructField(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
467 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;467 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
468 const extra = w.air.extraData(Air.StructField, ty_pl.payload).data;468 const extra = w.air.extraData(Air.StructField, ty_pl.payload).data;
469469
...@@ -471,7 +471,7 @@ const Writer = struct {...@@ -471,7 +471,7 @@ const Writer = struct {
471 try s.print(", {d}", .{extra.field_index});471 try s.print(", {d}", .{extra.field_index});
472 }472 }
473473
474 fn writeTyPlBin(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {474 fn writeTyPlBin(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
475 const data = w.air.instructions.items(.data);475 const data = w.air.instructions.items(.data);
476 const ty_pl = data[@intFromEnum(inst)].ty_pl;476 const ty_pl = data[@intFromEnum(inst)].ty_pl;
477 const extra = w.air.extraData(Air.Bin, ty_pl.payload).data;477 const extra = w.air.extraData(Air.Bin, ty_pl.payload).data;
...@@ -484,7 +484,7 @@ const Writer = struct {...@@ -484,7 +484,7 @@ const Writer = struct {
484 try w.writeOperand(s, inst, 1, extra.rhs);484 try w.writeOperand(s, inst, 1, extra.rhs);
485 }485 }
486486
487 fn writeCmpxchg(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {487 fn writeCmpxchg(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
488 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;488 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
489 const extra = w.air.extraData(Air.Cmpxchg, ty_pl.payload).data;489 const extra = w.air.extraData(Air.Cmpxchg, ty_pl.payload).data;
490490
...@@ -498,7 +498,7 @@ const Writer = struct {...@@ -498,7 +498,7 @@ const Writer = struct {
498 });498 });
499 }499 }
500500
501 fn writeMulAdd(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {501 fn writeMulAdd(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
502 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;502 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
503 const extra = w.air.extraData(Air.Bin, pl_op.payload).data;503 const extra = w.air.extraData(Air.Bin, pl_op.payload).data;
504504
...@@ -509,7 +509,7 @@ const Writer = struct {...@@ -509,7 +509,7 @@ const Writer = struct {
509 try w.writeOperand(s, inst, 2, pl_op.operand);509 try w.writeOperand(s, inst, 2, pl_op.operand);
510 }510 }
511511
512 fn writeShuffleOne(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {512 fn writeShuffleOne(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
513 const unwrapped = w.air.unwrapShuffleOne(w.pt.zcu, inst);513 const unwrapped = w.air.unwrapShuffleOne(w.pt.zcu, inst);
514 try w.writeType(s, unwrapped.result_ty);514 try w.writeType(s, unwrapped.result_ty);
515 try s.writeAll(", ");515 try s.writeAll(", ");
...@@ -525,7 +525,7 @@ const Writer = struct {...@@ -525,7 +525,7 @@ const Writer = struct {
525 try s.writeByte(']');525 try s.writeByte(']');
526 }526 }
527527
528 fn writeShuffleTwo(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {528 fn writeShuffleTwo(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
529 const unwrapped = w.air.unwrapShuffleTwo(w.pt.zcu, inst);529 const unwrapped = w.air.unwrapShuffleTwo(w.pt.zcu, inst);
530 try w.writeType(s, unwrapped.result_ty);530 try w.writeType(s, unwrapped.result_ty);
531 try s.writeAll(", ");531 try s.writeAll(", ");
...@@ -544,7 +544,7 @@ const Writer = struct {...@@ -544,7 +544,7 @@ const Writer = struct {
544 try s.writeByte(']');544 try s.writeByte(']');
545 }545 }
546546
547 fn writeSelect(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {547 fn writeSelect(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
548 const zcu = w.pt.zcu;548 const zcu = w.pt.zcu;
549 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;549 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
550 const extra = w.air.extraData(Air.Bin, pl_op.payload).data;550 const extra = w.air.extraData(Air.Bin, pl_op.payload).data;
...@@ -559,14 +559,14 @@ const Writer = struct {...@@ -559,14 +559,14 @@ const Writer = struct {
559 try w.writeOperand(s, inst, 2, extra.rhs);559 try w.writeOperand(s, inst, 2, extra.rhs);
560 }560 }
561561
562 fn writeReduce(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {562 fn writeReduce(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
563 const reduce = w.air.instructions.items(.data)[@intFromEnum(inst)].reduce;563 const reduce = w.air.instructions.items(.data)[@intFromEnum(inst)].reduce;
564564
565 try w.writeOperand(s, inst, 0, reduce.operand);565 try w.writeOperand(s, inst, 0, reduce.operand);
566 try s.print(", {s}", .{@tagName(reduce.operation)});566 try s.print(", {s}", .{@tagName(reduce.operation)});
567 }567 }
568568
569 fn writeCmpVector(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {569 fn writeCmpVector(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
570 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;570 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
571 const extra = w.air.extraData(Air.VectorCmp, ty_pl.payload).data;571 const extra = w.air.extraData(Air.VectorCmp, ty_pl.payload).data;
572572
...@@ -576,7 +576,7 @@ const Writer = struct {...@@ -576,7 +576,7 @@ const Writer = struct {
576 try w.writeOperand(s, inst, 1, extra.rhs);576 try w.writeOperand(s, inst, 1, extra.rhs);
577 }577 }
578578
579 fn writeVectorStoreElem(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {579 fn writeVectorStoreElem(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
580 const data = w.air.instructions.items(.data)[@intFromEnum(inst)].vector_store_elem;580 const data = w.air.instructions.items(.data)[@intFromEnum(inst)].vector_store_elem;
581 const extra = w.air.extraData(Air.VectorCmp, data.payload).data;581 const extra = w.air.extraData(Air.VectorCmp, data.payload).data;
582582
...@@ -587,21 +587,21 @@ const Writer = struct {...@@ -587,21 +587,21 @@ const Writer = struct {
587 try w.writeOperand(s, inst, 2, extra.rhs);587 try w.writeOperand(s, inst, 2, extra.rhs);
588 }588 }
589589
590 fn writeRuntimeNavPtr(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {590 fn writeRuntimeNavPtr(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
591 const ip = &w.pt.zcu.intern_pool;591 const ip = &w.pt.zcu.intern_pool;
592 const ty_nav = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_nav;592 const ty_nav = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_nav;
593 try w.writeType(s, .fromInterned(ty_nav.ty));593 try w.writeType(s, .fromInterned(ty_nav.ty));
594 try s.print(", '{f}'", .{ip.getNav(ty_nav.nav).fqn.fmt(ip)});594 try s.print(", '{f}'", .{ip.getNav(ty_nav.nav).fqn.fmt(ip)});
595 }595 }
596596
597 fn writeAtomicLoad(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {597 fn writeAtomicLoad(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
598 const atomic_load = w.air.instructions.items(.data)[@intFromEnum(inst)].atomic_load;598 const atomic_load = w.air.instructions.items(.data)[@intFromEnum(inst)].atomic_load;
599599
600 try w.writeOperand(s, inst, 0, atomic_load.ptr);600 try w.writeOperand(s, inst, 0, atomic_load.ptr);
601 try s.print(", {s}", .{@tagName(atomic_load.order)});601 try s.print(", {s}", .{@tagName(atomic_load.order)});
602 }602 }
603603
604 fn writePrefetch(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {604 fn writePrefetch(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
605 const prefetch = w.air.instructions.items(.data)[@intFromEnum(inst)].prefetch;605 const prefetch = w.air.instructions.items(.data)[@intFromEnum(inst)].prefetch;
606606
607 try w.writeOperand(s, inst, 0, prefetch.ptr);607 try w.writeOperand(s, inst, 0, prefetch.ptr);
...@@ -612,7 +612,7 @@ const Writer = struct {...@@ -612,7 +612,7 @@ const Writer = struct {
612612
613 fn writeAtomicStore(613 fn writeAtomicStore(
614 w: *Writer,614 w: *Writer,
615 s: *std.io.Writer,615 s: *std.Io.Writer,
616 inst: Air.Inst.Index,616 inst: Air.Inst.Index,
617 order: std.builtin.AtomicOrder,617 order: std.builtin.AtomicOrder,
618 ) Error!void {618 ) Error!void {
...@@ -623,7 +623,7 @@ const Writer = struct {...@@ -623,7 +623,7 @@ const Writer = struct {
623 try s.print(", {s}", .{@tagName(order)});623 try s.print(", {s}", .{@tagName(order)});
624 }624 }
625625
626 fn writeAtomicRmw(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {626 fn writeAtomicRmw(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
627 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;627 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
628 const extra = w.air.extraData(Air.AtomicRmw, pl_op.payload).data;628 const extra = w.air.extraData(Air.AtomicRmw, pl_op.payload).data;
629629
...@@ -633,7 +633,7 @@ const Writer = struct {...@@ -633,7 +633,7 @@ const Writer = struct {
633 try s.print(", {s}, {s}", .{ @tagName(extra.op()), @tagName(extra.ordering()) });633 try s.print(", {s}, {s}", .{ @tagName(extra.op()), @tagName(extra.ordering()) });
634 }634 }
635635
636 fn writeFieldParentPtr(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {636 fn writeFieldParentPtr(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
637 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;637 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
638 const extra = w.air.extraData(Air.FieldParentPtr, ty_pl.payload).data;638 const extra = w.air.extraData(Air.FieldParentPtr, ty_pl.payload).data;
639639
...@@ -641,7 +641,7 @@ const Writer = struct {...@@ -641,7 +641,7 @@ const Writer = struct {
641 try s.print(", {d}", .{extra.field_index});641 try s.print(", {d}", .{extra.field_index});
642 }642 }
643643
644 fn writeAssembly(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {644 fn writeAssembly(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
645 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;645 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
646 const extra = w.air.extraData(Air.Asm, ty_pl.payload);646 const extra = w.air.extraData(Air.Asm, ty_pl.payload);
647 const is_volatile = extra.data.flags.is_volatile;647 const is_volatile = extra.data.flags.is_volatile;
...@@ -730,19 +730,19 @@ const Writer = struct {...@@ -730,19 +730,19 @@ const Writer = struct {
730 try s.print(", \"{f}\"", .{std.zig.fmtString(asm_source)});730 try s.print(", \"{f}\"", .{std.zig.fmtString(asm_source)});
731 }731 }
732732
733 fn writeDbgStmt(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {733 fn writeDbgStmt(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
734 const dbg_stmt = w.air.instructions.items(.data)[@intFromEnum(inst)].dbg_stmt;734 const dbg_stmt = w.air.instructions.items(.data)[@intFromEnum(inst)].dbg_stmt;
735 try s.print("{d}:{d}", .{ dbg_stmt.line + 1, dbg_stmt.column + 1 });735 try s.print("{d}:{d}", .{ dbg_stmt.line + 1, dbg_stmt.column + 1 });
736 }736 }
737737
738 fn writeDbgVar(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {738 fn writeDbgVar(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
739 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;739 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
740 try w.writeOperand(s, inst, 0, pl_op.operand);740 try w.writeOperand(s, inst, 0, pl_op.operand);
741 const name: Air.NullTerminatedString = @enumFromInt(pl_op.payload);741 const name: Air.NullTerminatedString = @enumFromInt(pl_op.payload);
742 try s.print(", \"{f}\"", .{std.zig.fmtString(name.toSlice(w.air))});742 try s.print(", \"{f}\"", .{std.zig.fmtString(name.toSlice(w.air))});
743 }743 }
744744
745 fn writeCall(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {745 fn writeCall(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
746 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;746 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
747 const extra = w.air.extraData(Air.Call, pl_op.payload);747 const extra = w.air.extraData(Air.Call, pl_op.payload);
748 const args = @as([]const Air.Inst.Ref, @ptrCast(w.air.extra.items[extra.end..][0..extra.data.args_len]));748 const args = @as([]const Air.Inst.Ref, @ptrCast(w.air.extra.items[extra.end..][0..extra.data.args_len]));
...@@ -755,19 +755,19 @@ const Writer = struct {...@@ -755,19 +755,19 @@ const Writer = struct {
755 try s.writeAll("]");755 try s.writeAll("]");
756 }756 }
757757
758 fn writeBr(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {758 fn writeBr(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
759 const br = w.air.instructions.items(.data)[@intFromEnum(inst)].br;759 const br = w.air.instructions.items(.data)[@intFromEnum(inst)].br;
760 try w.writeInstIndex(s, br.block_inst, false);760 try w.writeInstIndex(s, br.block_inst, false);
761 try s.writeAll(", ");761 try s.writeAll(", ");
762 try w.writeOperand(s, inst, 0, br.operand);762 try w.writeOperand(s, inst, 0, br.operand);
763 }763 }
764764
765 fn writeRepeat(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {765 fn writeRepeat(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
766 const repeat = w.air.instructions.items(.data)[@intFromEnum(inst)].repeat;766 const repeat = w.air.instructions.items(.data)[@intFromEnum(inst)].repeat;
767 try w.writeInstIndex(s, repeat.loop_inst, false);767 try w.writeInstIndex(s, repeat.loop_inst, false);
768 }768 }
769769
770 fn writeTry(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {770 fn writeTry(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
771 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;771 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
772 const extra = w.air.extraData(Air.Try, pl_op.payload);772 const extra = w.air.extraData(Air.Try, pl_op.payload);
773 const body: []const Air.Inst.Index = @ptrCast(w.air.extra.items[extra.end..][0..extra.data.body_len]);773 const body: []const Air.Inst.Index = @ptrCast(w.air.extra.items[extra.end..][0..extra.data.body_len]);
...@@ -801,7 +801,7 @@ const Writer = struct {...@@ -801,7 +801,7 @@ const Writer = struct {
801 }801 }
802 }802 }
803803
804 fn writeTryPtr(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {804 fn writeTryPtr(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
805 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;805 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
806 const extra = w.air.extraData(Air.TryPtr, ty_pl.payload);806 const extra = w.air.extraData(Air.TryPtr, ty_pl.payload);
807 const body: []const Air.Inst.Index = @ptrCast(w.air.extra.items[extra.end..][0..extra.data.body_len]);807 const body: []const Air.Inst.Index = @ptrCast(w.air.extra.items[extra.end..][0..extra.data.body_len]);
...@@ -838,7 +838,7 @@ const Writer = struct {...@@ -838,7 +838,7 @@ const Writer = struct {
838 }838 }
839 }839 }
840840
841 fn writeCondBr(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {841 fn writeCondBr(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
842 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;842 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
843 const extra = w.air.extraData(Air.CondBr, pl_op.payload);843 const extra = w.air.extraData(Air.CondBr, pl_op.payload);
844 const then_body: []const Air.Inst.Index = @ptrCast(w.air.extra.items[extra.end..][0..extra.data.then_body_len]);844 const then_body: []const Air.Inst.Index = @ptrCast(w.air.extra.items[extra.end..][0..extra.data.then_body_len]);
...@@ -897,7 +897,7 @@ const Writer = struct {...@@ -897,7 +897,7 @@ const Writer = struct {
897 try s.writeAll("}");897 try s.writeAll("}");
898 }898 }
899899
900 fn writeSwitchBr(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {900 fn writeSwitchBr(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
901 const switch_br = w.air.unwrapSwitch(inst);901 const switch_br = w.air.unwrapSwitch(inst);
902902
903 const liveness: Air.Liveness.SwitchBrTable = if (w.liveness) |liveness|903 const liveness: Air.Liveness.SwitchBrTable = if (w.liveness) |liveness|
...@@ -983,25 +983,25 @@ const Writer = struct {...@@ -983,25 +983,25 @@ const Writer = struct {
983 try s.splatByteAll(' ', old_indent);983 try s.splatByteAll(' ', old_indent);
984 }984 }
985985
986 fn writeWasmMemorySize(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {986 fn writeWasmMemorySize(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
987 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;987 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
988 try s.print("{d}", .{pl_op.payload});988 try s.print("{d}", .{pl_op.payload});
989 }989 }
990990
991 fn writeWasmMemoryGrow(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {991 fn writeWasmMemoryGrow(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
992 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;992 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
993 try s.print("{d}, ", .{pl_op.payload});993 try s.print("{d}, ", .{pl_op.payload});
994 try w.writeOperand(s, inst, 0, pl_op.operand);994 try w.writeOperand(s, inst, 0, pl_op.operand);
995 }995 }
996996
997 fn writeWorkDimension(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {997 fn writeWorkDimension(w: *Writer, s: *std.Io.Writer, inst: Air.Inst.Index) Error!void {
998 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;998 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
999 try s.print("{d}", .{pl_op.payload});999 try s.print("{d}", .{pl_op.payload});
1000 }1000 }
10011001
1002 fn writeOperand(1002 fn writeOperand(
1003 w: *Writer,1003 w: *Writer,
1004 s: *std.io.Writer,1004 s: *std.Io.Writer,
1005 inst: Air.Inst.Index,1005 inst: Air.Inst.Index,
1006 op_index: usize,1006 op_index: usize,
1007 operand: Air.Inst.Ref,1007 operand: Air.Inst.Ref,
...@@ -1027,7 +1027,7 @@ const Writer = struct {...@@ -1027,7 +1027,7 @@ const Writer = struct {
10271027
1028 fn writeInstRef(1028 fn writeInstRef(
1029 w: *Writer,1029 w: *Writer,
1030 s: *std.io.Writer,1030 s: *std.Io.Writer,
1031 operand: Air.Inst.Ref,1031 operand: Air.Inst.Ref,
1032 dies: bool,1032 dies: bool,
1033 ) Error!void {1033 ) Error!void {
...@@ -1047,7 +1047,7 @@ const Writer = struct {...@@ -1047,7 +1047,7 @@ const Writer = struct {
10471047
1048 fn writeInstIndex(1048 fn writeInstIndex(
1049 w: *Writer,1049 w: *Writer,
1050 s: *std.io.Writer,1050 s: *std.Io.Writer,
1051 inst: Air.Inst.Index,1051 inst: Air.Inst.Index,
1052 dies: bool,1052 dies: bool,
1053 ) Error!void {1053 ) Error!void {
src/Compilation.zig+5-5
...@@ -12,7 +12,7 @@ const ThreadPool = std.Thread.Pool;...@@ -12,7 +12,7 @@ const ThreadPool = std.Thread.Pool;
12const WaitGroup = std.Thread.WaitGroup;12const WaitGroup = std.Thread.WaitGroup;
13const ErrorBundle = std.zig.ErrorBundle;13const ErrorBundle = std.zig.ErrorBundle;
14const fatal = std.process.fatal;14const fatal = std.process.fatal;
15const Writer = std.io.Writer;15const Writer = std.Io.Writer;
1616
17const Value = @import("Value.zig");17const Value = @import("Value.zig");
18const Type = @import("Type.zig");18const Type = @import("Type.zig");
...@@ -468,7 +468,7 @@ pub const Path = struct {...@@ -468,7 +468,7 @@ pub const Path = struct {
468 const Formatter = struct {468 const Formatter = struct {
469 p: Path,469 p: Path,
470 comp: *Compilation,470 comp: *Compilation,
471 pub fn format(f: Formatter, w: *std.io.Writer) std.io.Writer.Error!void {471 pub fn format(f: Formatter, w: *Writer) Writer.Error!void {
472 const root_path: []const u8 = switch (f.p.root) {472 const root_path: []const u8 = switch (f.p.root) {
473 .zig_lib => f.comp.dirs.zig_lib.path orelse ".",473 .zig_lib => f.comp.dirs.zig_lib.path orelse ".",
474 .global_cache => f.comp.dirs.global_cache.path orelse ".",474 .global_cache => f.comp.dirs.global_cache.path orelse ".",
...@@ -1883,7 +1883,7 @@ pub const CreateDiagnostic = union(enum) {...@@ -1883,7 +1883,7 @@ pub const CreateDiagnostic = union(enum) {
1883 sub: []const u8,1883 sub: []const u8,
1884 err: (fs.Dir.MakeError || fs.Dir.OpenError || fs.Dir.StatFileError),1884 err: (fs.Dir.MakeError || fs.Dir.OpenError || fs.Dir.StatFileError),
1885 };1885 };
1886 pub fn format(diag: CreateDiagnostic, w: *std.Io.Writer) std.Io.Writer.Error!void {1886 pub fn format(diag: CreateDiagnostic, w: *Writer) Writer.Error!void {
1887 switch (diag) {1887 switch (diag) {
1888 .export_table_import_table_conflict => try w.writeAll("'--import-table' and '--export-table' cannot be used together"),1888 .export_table_import_table_conflict => try w.writeAll("'--import-table' and '--export-table' cannot be used together"),
1889 .emit_h_without_zcu => try w.writeAll("cannot emit C header with no Zig source files"),1889 .emit_h_without_zcu => try w.writeAll("cannot emit C header with no Zig source files"),
...@@ -6457,7 +6457,7 @@ fn updateWin32Resource(comp: *Compilation, win32_resource: *Win32Resource, win32...@@ -6457,7 +6457,7 @@ fn updateWin32Resource(comp: *Compilation, win32_resource: *Win32Resource, win32
64576457
6458 // In .rc files, a " within a quoted string is escaped as ""6458 // In .rc files, a " within a quoted string is escaped as ""
6459 const fmtRcEscape = struct {6459 const fmtRcEscape = struct {
6460 fn formatRcEscape(bytes: []const u8, writer: *std.io.Writer) std.io.Writer.Error!void {6460 fn formatRcEscape(bytes: []const u8, writer: *Writer) Writer.Error!void {
6461 for (bytes) |byte| switch (byte) {6461 for (bytes) |byte| switch (byte) {
6462 '"' => try writer.writeAll("\"\""),6462 '"' => try writer.writeAll("\"\""),
6463 '\\' => try writer.writeAll("\\\\"),6463 '\\' => try writer.writeAll("\\\\"),
...@@ -6576,7 +6576,7 @@ fn updateWin32Resource(comp: *Compilation, win32_resource: *Win32Resource, win32...@@ -6576,7 +6576,7 @@ fn updateWin32Resource(comp: *Compilation, win32_resource: *Win32Resource, win32
6576 // Read depfile and update cache manifest6576 // Read depfile and update cache manifest
6577 {6577 {
6578 const dep_basename = fs.path.basename(out_dep_path);6578 const dep_basename = fs.path.basename(out_dep_path);
6579 const dep_file_contents = try zig_cache_tmp_dir.readFileAlloc(arena, dep_basename, 50 * 1024 * 1024);6579 const dep_file_contents = try zig_cache_tmp_dir.readFileAlloc(dep_basename, arena, .limited(50 * 1024 * 1024));
6580 defer arena.free(dep_file_contents);6580 defer arena.free(dep_file_contents);
65816581
6582 const value = try std.json.parseFromSliceLeaky(std.json.Value, arena, dep_file_contents, .{});6582 const value = try std.json.parseFromSliceLeaky(std.json.Value, arena, dep_file_contents, .{});
src/InternPool.zig+15-15
...@@ -1,6 +1,20 @@...@@ -1,6 +1,20 @@
1//! All interned objects have both a value and a type.1//! All interned objects have both a value and a type.
2//! This data structure is self-contained.2//! This data structure is self-contained.
33
4const builtin = @import("builtin");
5const std = @import("std");
6const Allocator = std.mem.Allocator;
7const assert = std.debug.assert;
8const BigIntConst = std.math.big.int.Const;
9const BigIntMutable = std.math.big.int.Mutable;
10const Cache = std.Build.Cache;
11const Limb = std.math.big.Limb;
12const Hash = std.hash.Wyhash;
13
14const InternPool = @This();
15const Zcu = @import("Zcu.zig");
16const Zir = std.zig.Zir;
17
4/// One item per thread, indexed by `tid`, which is dense and unique per thread.18/// One item per thread, indexed by `tid`, which is dense and unique per thread.
5locals: []Local,19locals: []Local,
6/// Length must be a power of two and represents the number of simultaneous20/// Length must be a power of two and represents the number of simultaneous
...@@ -1606,20 +1620,6 @@ fn getIndexMask(ip: *const InternPool, comptime BackingInt: type) u32 {...@@ -1606,20 +1620,6 @@ fn getIndexMask(ip: *const InternPool, comptime BackingInt: type) u32 {
16061620
1607const FieldMap = std.ArrayHashMapUnmanaged(void, void, std.array_hash_map.AutoContext(void), false);1621const FieldMap = std.ArrayHashMapUnmanaged(void, void, std.array_hash_map.AutoContext(void), false);
16081622
1609const builtin = @import("builtin");
1610const std = @import("std");
1611const Allocator = std.mem.Allocator;
1612const assert = std.debug.assert;
1613const BigIntConst = std.math.big.int.Const;
1614const BigIntMutable = std.math.big.int.Mutable;
1615const Cache = std.Build.Cache;
1616const Limb = std.math.big.Limb;
1617const Hash = std.hash.Wyhash;
1618
1619const InternPool = @This();
1620const Zcu = @import("Zcu.zig");
1621const Zir = std.zig.Zir;
1622
1623/// An index into `maps` which might be `none`.1623/// An index into `maps` which might be `none`.
1624pub const OptionalMapIndex = enum(u32) {1624pub const OptionalMapIndex = enum(u32) {
1625 none = std.math.maxInt(u32),1625 none = std.math.maxInt(u32),
...@@ -1895,7 +1895,7 @@ pub const NullTerminatedString = enum(u32) {...@@ -1895,7 +1895,7 @@ pub const NullTerminatedString = enum(u32) {
1895 ip: *const InternPool,1895 ip: *const InternPool,
1896 id: bool,1896 id: bool,
1897 };1897 };
1898 fn format(data: FormatData, writer: *std.io.Writer) std.io.Writer.Error!void {1898 fn format(data: FormatData, writer: *std.Io.Writer) std.Io.Writer.Error!void {
1899 const slice = data.string.toSlice(data.ip);1899 const slice = data.string.toSlice(data.ip);
1900 if (!data.id) {1900 if (!data.id) {
1901 try writer.writeAll(slice);1901 try writer.writeAll(slice);
src/Package/Fetch.zig+4-5
...@@ -655,10 +655,9 @@ fn loadManifest(f: *Fetch, pkg_root: Cache.Path) RunError!void {...@@ -655,10 +655,9 @@ fn loadManifest(f: *Fetch, pkg_root: Cache.Path) RunError!void {
655 const eb = &f.error_bundle;655 const eb = &f.error_bundle;
656 const arena = f.arena.allocator();656 const arena = f.arena.allocator();
657 const manifest_bytes = pkg_root.root_dir.handle.readFileAllocOptions(657 const manifest_bytes = pkg_root.root_dir.handle.readFileAllocOptions(
658 arena,
659 try fs.path.join(arena, &.{ pkg_root.sub_path, Manifest.basename }),658 try fs.path.join(arena, &.{ pkg_root.sub_path, Manifest.basename }),
660 Manifest.max_bytes,659 arena,
661 null,660 .limited(Manifest.max_bytes),
662 .@"1",661 .@"1",
663 0,662 0,
664 ) catch |err| switch (err) {663 ) catch |err| switch (err) {
...@@ -2020,7 +2019,7 @@ const UnpackResult = struct {...@@ -2020,7 +2019,7 @@ const UnpackResult = struct {
2020 // output errors to string2019 // output errors to string
2021 var errors = try fetch.error_bundle.toOwnedBundle("");2020 var errors = try fetch.error_bundle.toOwnedBundle("");
2022 defer errors.deinit(gpa);2021 defer errors.deinit(gpa);
2023 var aw: std.io.Writer.Allocating = .init(gpa);2022 var aw: std.Io.Writer.Allocating = .init(gpa);
2024 defer aw.deinit();2023 defer aw.deinit();
2025 try errors.renderToWriter(.{ .ttyconf = .no_color }, &aw.writer);2024 try errors.renderToWriter(.{ .ttyconf = .no_color }, &aw.writer);
2026 try std.testing.expectEqualStrings(2025 try std.testing.expectEqualStrings(
...@@ -2329,7 +2328,7 @@ const TestFetchBuilder = struct {...@@ -2329,7 +2328,7 @@ const TestFetchBuilder = struct {
2329 if (notes_len > 0) {2328 if (notes_len > 0) {
2330 try std.testing.expectEqual(notes_len, em.notes_len);2329 try std.testing.expectEqual(notes_len, em.notes_len);
2331 }2330 }
2332 var aw: std.io.Writer.Allocating = .init(std.testing.allocator);2331 var aw: std.Io.Writer.Allocating = .init(std.testing.allocator);
2333 defer aw.deinit();2332 defer aw.deinit();
2334 try errors.renderToWriter(.{ .ttyconf = .no_color }, &aw.writer);2333 try errors.renderToWriter(.{ .ttyconf = .no_color }, &aw.writer);
2335 try std.testing.expectEqualStrings(msg, aw.written());2334 try std.testing.expectEqualStrings(msg, aw.written());
src/Package/Fetch/git.zig+3-3
...@@ -146,7 +146,7 @@ pub const Oid = union(Format) {...@@ -146,7 +146,7 @@ pub const Oid = union(Format) {
146 } else error.InvalidOid;146 } else error.InvalidOid;
147 }147 }
148148
149 pub fn format(oid: Oid, writer: *std.io.Writer) std.io.Writer.Error!void {149 pub fn format(oid: Oid, writer: *std.Io.Writer) std.Io.Writer.Error!void {
150 try writer.print("{x}", .{oid.slice()});150 try writer.print("{x}", .{oid.slice()});
151 }151 }
152152
...@@ -1599,7 +1599,7 @@ fn runRepositoryTest(comptime format: Oid.Format, head_commit: []const u8) !void...@@ -1599,7 +1599,7 @@ fn runRepositoryTest(comptime format: Oid.Format, head_commit: []const u8) !void
1599 const max_file_size = 8192;1599 const max_file_size = 8192;
16001600
1601 if (!skip_checksums) {1601 if (!skip_checksums) {
1602 const index_file_data = try git_dir.dir.readFileAlloc(testing.allocator, "testrepo.idx", max_file_size);1602 const index_file_data = try git_dir.dir.readFileAlloc("testrepo.idx", testing.allocator, .limited(max_file_size));
1603 defer testing.allocator.free(index_file_data);1603 defer testing.allocator.free(index_file_data);
1604 // testrepo.idx is generated by Git. The index created by this file should1604 // testrepo.idx is generated by Git. The index created by this file should
1605 // match it exactly. Running `git verify-pack -v testrepo.pack` can verify1605 // match it exactly. Running `git verify-pack -v testrepo.pack` can verify
...@@ -1675,7 +1675,7 @@ fn runRepositoryTest(comptime format: Oid.Format, head_commit: []const u8) !void...@@ -1675,7 +1675,7 @@ fn runRepositoryTest(comptime format: Oid.Format, head_commit: []const u8) !void
1675 \\revision 191675 \\revision 19
1676 \\1676 \\
1677 ;1677 ;
1678 const actual_file_contents = try worktree.dir.readFileAlloc(testing.allocator, "file", max_file_size);1678 const actual_file_contents = try worktree.dir.readFileAlloc("file", testing.allocator, .limited(max_file_size));
1679 defer testing.allocator.free(actual_file_contents);1679 defer testing.allocator.free(actual_file_contents);
1680 try testing.expectEqualStrings(expected_file_contents, actual_file_contents);1680 try testing.expectEqualStrings(expected_file_contents, actual_file_contents);
1681}1681}
src/Package/Manifest.zig+1-1
...@@ -472,7 +472,7 @@ const Parse = struct {...@@ -472,7 +472,7 @@ const Parse = struct {
472 ) InnerError!void {472 ) InnerError!void {
473 const raw_string = bytes[offset..];473 const raw_string = bytes[offset..];
474 const result = r: {474 const result = r: {
475 var aw: std.io.Writer.Allocating = .fromArrayList(p.gpa, buf);475 var aw: std.Io.Writer.Allocating = .fromArrayList(p.gpa, buf);
476 defer buf.* = aw.toArrayList();476 defer buf.* = aw.toArrayList();
477 break :r std.zig.string_literal.parseWrite(&aw.writer, raw_string) catch |err| switch (err) {477 break :r std.zig.string_literal.parseWrite(&aw.writer, raw_string) catch |err| switch (err) {
478 error.WriteFailed => return error.OutOfMemory,478 error.WriteFailed => return error.OutOfMemory,
src/Sema.zig+5-5
...@@ -3080,7 +3080,7 @@ pub fn createTypeName(...@@ -3080,7 +3080,7 @@ pub fn createTypeName(
3080 const fn_info = sema.code.getFnInfo(ip.funcZirBodyInst(sema.func_index).resolve(ip) orelse return error.AnalysisFail);3080 const fn_info = sema.code.getFnInfo(ip.funcZirBodyInst(sema.func_index).resolve(ip) orelse return error.AnalysisFail);
3081 const zir_tags = sema.code.instructions.items(.tag);3081 const zir_tags = sema.code.instructions.items(.tag);
30823082
3083 var aw: std.io.Writer.Allocating = .init(gpa);3083 var aw: std.Io.Writer.Allocating = .init(gpa);
3084 defer aw.deinit();3084 defer aw.deinit();
3085 const w = &aw.writer;3085 const w = &aw.writer;
3086 w.print("{f}(", .{block.type_name_ctx.fmt(ip)}) catch return error.OutOfMemory;3086 w.print("{f}(", .{block.type_name_ctx.fmt(ip)}) catch return error.OutOfMemory;
...@@ -5508,7 +5508,7 @@ fn zirCompileLog(...@@ -5508,7 +5508,7 @@ fn zirCompileLog(
5508 const zcu = pt.zcu;5508 const zcu = pt.zcu;
5509 const gpa = zcu.gpa;5509 const gpa = zcu.gpa;
55105510
5511 var aw: std.io.Writer.Allocating = .init(gpa);5511 var aw: std.Io.Writer.Allocating = .init(gpa);
5512 defer aw.deinit();5512 defer aw.deinit();
5513 const writer = &aw.writer;5513 const writer = &aw.writer;
55145514
...@@ -9080,7 +9080,7 @@ fn callConvSupportsVarArgs(cc: std.builtin.CallingConvention.Tag) bool {...@@ -9080,7 +9080,7 @@ fn callConvSupportsVarArgs(cc: std.builtin.CallingConvention.Tag) bool {
9080fn checkCallConvSupportsVarArgs(sema: *Sema, block: *Block, src: LazySrcLoc, cc: std.builtin.CallingConvention.Tag) CompileError!void {9080fn checkCallConvSupportsVarArgs(sema: *Sema, block: *Block, src: LazySrcLoc, cc: std.builtin.CallingConvention.Tag) CompileError!void {
9081 const CallingConventionsSupportingVarArgsList = struct {9081 const CallingConventionsSupportingVarArgsList = struct {
9082 arch: std.Target.Cpu.Arch,9082 arch: std.Target.Cpu.Arch,
9083 pub fn format(ctx: @This(), w: *std.io.Writer) std.io.Writer.Error!void {9083 pub fn format(ctx: @This(), w: *std.Io.Writer) std.Io.Writer.Error!void {
9084 var first = true;9084 var first = true;
9085 for (calling_conventions_supporting_var_args) |cc_inner| {9085 for (calling_conventions_supporting_var_args) |cc_inner| {
9086 for (std.Target.Cpu.Arch.fromCallingConvention(cc_inner)) |supported_arch| {9086 for (std.Target.Cpu.Arch.fromCallingConvention(cc_inner)) |supported_arch| {
...@@ -9521,7 +9521,7 @@ fn finishFunc(...@@ -9521,7 +9521,7 @@ fn finishFunc(
9521 .bad_arch => |allowed_archs| {9521 .bad_arch => |allowed_archs| {
9522 const ArchListFormatter = struct {9522 const ArchListFormatter = struct {
9523 archs: []const std.Target.Cpu.Arch,9523 archs: []const std.Target.Cpu.Arch,
9524 pub fn format(formatter: @This(), w: *std.io.Writer) std.io.Writer.Error!void {9524 pub fn format(formatter: @This(), w: *std.Io.Writer) std.Io.Writer.Error!void {
9525 for (formatter.archs, 0..) |arch, i| {9525 for (formatter.archs, 0..) |arch, i| {
9526 if (i != 0)9526 if (i != 0)
9527 try w.writeAll(", ");9527 try w.writeAll(", ");
...@@ -36962,7 +36962,7 @@ fn notePathToComptimeAllocPtr(...@@ -36962,7 +36962,7 @@ fn notePathToComptimeAllocPtr(
36962 error.AnalysisFail => unreachable,36962 error.AnalysisFail => unreachable,
36963 };36963 };
3696436964
36965 var second_path_aw: std.io.Writer.Allocating = .init(arena);36965 var second_path_aw: std.Io.Writer.Allocating = .init(arena);
36966 defer second_path_aw.deinit();36966 defer second_path_aw.deinit();
36967 const inter_name = try std.fmt.allocPrint(arena, "v{d}", .{intermediate_value_count});36967 const inter_name = try std.fmt.allocPrint(arena, "v{d}", .{intermediate_value_count});
36968 const deriv_start = @import("print_value.zig").printPtrDerivation(36968 const deriv_start = @import("print_value.zig").printPtrDerivation(
src/Type.zig+4-4
...@@ -121,7 +121,7 @@ pub fn eql(a: Type, b: Type, zcu: *const Zcu) bool {...@@ -121,7 +121,7 @@ pub fn eql(a: Type, b: Type, zcu: *const Zcu) bool {
121 return a.toIntern() == b.toIntern();121 return a.toIntern() == b.toIntern();
122}122}
123123
124pub fn format(ty: Type, writer: *std.io.Writer) !void {124pub fn format(ty: Type, writer: *std.Io.Writer) !void {
125 _ = ty;125 _ = ty;
126 _ = writer;126 _ = writer;
127 @compileError("do not format types directly; use either ty.fmtDebug() or ty.fmt()");127 @compileError("do not format types directly; use either ty.fmtDebug() or ty.fmt()");
...@@ -140,7 +140,7 @@ const Format = struct {...@@ -140,7 +140,7 @@ const Format = struct {
140 ty: Type,140 ty: Type,
141 pt: Zcu.PerThread,141 pt: Zcu.PerThread,
142142
143 fn default(f: Format, writer: *std.io.Writer) std.io.Writer.Error!void {143 fn default(f: Format, writer: *std.Io.Writer) std.Io.Writer.Error!void {
144 return print(f.ty, writer, f.pt);144 return print(f.ty, writer, f.pt);
145 }145 }
146};146};
...@@ -151,13 +151,13 @@ pub fn fmtDebug(ty: Type) std.fmt.Formatter(Type, dump) {...@@ -151,13 +151,13 @@ pub fn fmtDebug(ty: Type) std.fmt.Formatter(Type, dump) {
151151
152/// This is a debug function. In order to print types in a meaningful way152/// This is a debug function. In order to print types in a meaningful way
153/// we also need access to the module.153/// we also need access to the module.
154pub fn dump(start_type: Type, writer: *std.io.Writer) std.io.Writer.Error!void {154pub fn dump(start_type: Type, writer: *std.Io.Writer) std.Io.Writer.Error!void {
155 return writer.print("{any}", .{start_type.ip_index});155 return writer.print("{any}", .{start_type.ip_index});
156}156}
157157
158/// Prints a name suitable for `@typeName`.158/// Prints a name suitable for `@typeName`.
159/// TODO: take an `opt_sema` to pass to `fmtValue` when printing sentinels.159/// TODO: take an `opt_sema` to pass to `fmtValue` when printing sentinels.
160pub fn print(ty: Type, writer: *std.io.Writer, pt: Zcu.PerThread) std.io.Writer.Error!void {160pub fn print(ty: Type, writer: *std.Io.Writer, pt: Zcu.PerThread) std.Io.Writer.Error!void {
161 const zcu = pt.zcu;161 const zcu = pt.zcu;
162 const ip = &zcu.intern_pool;162 const ip = &zcu.intern_pool;
163 switch (ip.indexToKey(ty.toIntern())) {163 switch (ip.indexToKey(ty.toIntern())) {
src/Value.zig+2-2
...@@ -15,7 +15,7 @@ const Value = @This();...@@ -15,7 +15,7 @@ const Value = @This();
1515
16ip_index: InternPool.Index,16ip_index: InternPool.Index,
1717
18pub fn format(val: Value, writer: *std.io.Writer) !void {18pub fn format(val: Value, writer: *std.Io.Writer) !void {
19 _ = val;19 _ = val;
20 _ = writer;20 _ = writer;
21 @compileError("do not use format values directly; use either fmtDebug or fmtValue");21 @compileError("do not use format values directly; use either fmtDebug or fmtValue");
...@@ -23,7 +23,7 @@ pub fn format(val: Value, writer: *std.io.Writer) !void {...@@ -23,7 +23,7 @@ pub fn format(val: Value, writer: *std.io.Writer) !void {
2323
24/// This is a debug function. In order to print values in a meaningful way24/// This is a debug function. In order to print values in a meaningful way
25/// we also need access to the type.25/// we also need access to the type.
26pub fn dump(start_val: Value, w: std.io.Writer) std.io.Writer.Error!void {26pub fn dump(start_val: Value, w: std.Io.Writer) std.Io.Writer.Error!void {
27 try w.print("(interned: {})", .{start_val.toIntern()});27 try w.print("(interned: {})", .{start_val.toIntern()});
28}28}
2929
src/Zcu.zig+5-5
...@@ -15,7 +15,7 @@ const BigIntConst = std.math.big.int.Const;...@@ -15,7 +15,7 @@ const BigIntConst = std.math.big.int.Const;
15const BigIntMutable = std.math.big.int.Mutable;15const BigIntMutable = std.math.big.int.Mutable;
16const Target = std.Target;16const Target = std.Target;
17const Ast = std.zig.Ast;17const Ast = std.zig.Ast;
18const Writer = std.io.Writer;18const Writer = std.Io.Writer;
1919
20const Zcu = @This();20const Zcu = @This();
21const Compilation = @import("Compilation.zig");21const Compilation = @import("Compilation.zig");
...@@ -2872,7 +2872,7 @@ pub fn loadZirCache(gpa: Allocator, cache_file: std.fs.File) !Zir {...@@ -2872,7 +2872,7 @@ pub fn loadZirCache(gpa: Allocator, cache_file: std.fs.File) !Zir {
2872 };2872 };
2873}2873}
28742874
2875pub fn loadZirCacheBody(gpa: Allocator, header: Zir.Header, cache_br: *std.io.Reader) !Zir {2875pub fn loadZirCacheBody(gpa: Allocator, header: Zir.Header, cache_br: *std.Io.Reader) !Zir {
2876 var instructions: std.MultiArrayList(Zir.Inst) = .{};2876 var instructions: std.MultiArrayList(Zir.Inst) = .{};
2877 errdefer instructions.deinit(gpa);2877 errdefer instructions.deinit(gpa);
28782878
...@@ -2989,7 +2989,7 @@ pub fn saveZoirCache(cache_file: std.fs.File, stat: std.fs.File.Stat, zoir: Zoir...@@ -2989,7 +2989,7 @@ pub fn saveZoirCache(cache_file: std.fs.File, stat: std.fs.File.Stat, zoir: Zoir
2989 };2989 };
2990}2990}
29912991
2992pub fn loadZoirCacheBody(gpa: Allocator, header: Zoir.Header, cache_br: *std.io.Reader) !Zoir {2992pub fn loadZoirCacheBody(gpa: Allocator, header: Zoir.Header, cache_br: *std.Io.Reader) !Zoir {
2993 var zoir: Zoir = .{2993 var zoir: Zoir = .{
2994 .nodes = .empty,2994 .nodes = .empty,
2995 .extra = &.{},2995 .extra = &.{},
...@@ -4318,7 +4318,7 @@ const FormatAnalUnit = struct {...@@ -4318,7 +4318,7 @@ const FormatAnalUnit = struct {
4318 zcu: *Zcu,4318 zcu: *Zcu,
4319};4319};
43204320
4321fn formatAnalUnit(data: FormatAnalUnit, writer: *std.io.Writer) std.io.Writer.Error!void {4321fn formatAnalUnit(data: FormatAnalUnit, writer: *std.Io.Writer) std.Io.Writer.Error!void {
4322 const zcu = data.zcu;4322 const zcu = data.zcu;
4323 const ip = &zcu.intern_pool;4323 const ip = &zcu.intern_pool;
4324 switch (data.unit.unwrap()) {4324 switch (data.unit.unwrap()) {
...@@ -4344,7 +4344,7 @@ fn formatAnalUnit(data: FormatAnalUnit, writer: *std.io.Writer) std.io.Writer.Er...@@ -4344,7 +4344,7 @@ fn formatAnalUnit(data: FormatAnalUnit, writer: *std.io.Writer) std.io.Writer.Er
43444344
4345const FormatDependee = struct { dependee: InternPool.Dependee, zcu: *Zcu };4345const FormatDependee = struct { dependee: InternPool.Dependee, zcu: *Zcu };
43464346
4347fn formatDependee(data: FormatDependee, writer: *std.io.Writer) std.io.Writer.Error!void {4347fn formatDependee(data: FormatDependee, writer: *std.Io.Writer) std.Io.Writer.Error!void {
4348 const zcu = data.zcu;4348 const zcu = data.zcu;
4349 const ip = &zcu.intern_pool;4349 const ip = &zcu.intern_pool;
4350 switch (data.dependee) {4350 switch (data.dependee) {
src/arch/riscv64/CodeGen.zig+5-5
...@@ -566,7 +566,7 @@ const InstTracking = struct {...@@ -566,7 +566,7 @@ const InstTracking = struct {
566 }566 }
567 }567 }
568568
569 pub fn format(inst_tracking: InstTracking, writer: *std.io.Writer) std.io.Writer.Error!void {569 pub fn format(inst_tracking: InstTracking, writer: *std.Io.Writer) std.Io.Writer.Error!void {
570 if (!std.meta.eql(inst_tracking.long, inst_tracking.short)) try writer.print("|{}| ", .{inst_tracking.long});570 if (!std.meta.eql(inst_tracking.long, inst_tracking.short)) try writer.print("|{}| ", .{inst_tracking.long});
571 try writer.print("{}", .{inst_tracking.short});571 try writer.print("{}", .{inst_tracking.short});
572 }572 }
...@@ -932,7 +932,7 @@ const FormatWipMirData = struct {...@@ -932,7 +932,7 @@ const FormatWipMirData = struct {
932 func: *Func,932 func: *Func,
933 inst: Mir.Inst.Index,933 inst: Mir.Inst.Index,
934};934};
935fn formatWipMir(data: FormatWipMirData, writer: *std.io.Writer) std.io.Writer.Error!void {935fn formatWipMir(data: FormatWipMirData, writer: *std.Io.Writer) std.Io.Writer.Error!void {
936 const pt = data.func.pt;936 const pt = data.func.pt;
937 const comp = pt.zcu.comp;937 const comp = pt.zcu.comp;
938 var lower: Lower = .{938 var lower: Lower = .{
...@@ -980,7 +980,7 @@ const FormatNavData = struct {...@@ -980,7 +980,7 @@ const FormatNavData = struct {
980 ip: *const InternPool,980 ip: *const InternPool,
981 nav_index: InternPool.Nav.Index,981 nav_index: InternPool.Nav.Index,
982};982};
983fn formatNav(data: FormatNavData, writer: *std.io.Writer) std.io.Writer.Error!void {983fn formatNav(data: FormatNavData, writer: *std.Io.Writer) std.Io.Writer.Error!void {
984 try writer.print("{f}", .{data.ip.getNav(data.nav_index).fqn.fmt(data.ip)});984 try writer.print("{f}", .{data.ip.getNav(data.nav_index).fqn.fmt(data.ip)});
985}985}
986fn fmtNav(nav_index: InternPool.Nav.Index, ip: *const InternPool) std.fmt.Formatter(FormatNavData, formatNav) {986fn fmtNav(nav_index: InternPool.Nav.Index, ip: *const InternPool) std.fmt.Formatter(FormatNavData, formatNav) {
...@@ -994,7 +994,7 @@ const FormatAirData = struct {...@@ -994,7 +994,7 @@ const FormatAirData = struct {
994 func: *Func,994 func: *Func,
995 inst: Air.Inst.Index,995 inst: Air.Inst.Index,
996};996};
997fn formatAir(data: FormatAirData, writer: *std.io.Writer) std.io.Writer.Error!void {997fn formatAir(data: FormatAirData, writer: *std.Io.Writer) std.Io.Writer.Error!void {
998 // Not acceptable implementation because it ignores `writer`:998 // Not acceptable implementation because it ignores `writer`:
999 //data.func.air.dumpInst(data.inst, data.func.pt, data.func.liveness);999 //data.func.air.dumpInst(data.inst, data.func.pt, data.func.liveness);
1000 _ = data;1000 _ = data;
...@@ -1008,7 +1008,7 @@ fn fmtAir(func: *Func, inst: Air.Inst.Index) std.fmt.Formatter(FormatAirData, fo...@@ -1008,7 +1008,7 @@ fn fmtAir(func: *Func, inst: Air.Inst.Index) std.fmt.Formatter(FormatAirData, fo
1008const FormatTrackingData = struct {1008const FormatTrackingData = struct {
1009 func: *Func,1009 func: *Func,
1010};1010};
1011fn formatTracking(data: FormatTrackingData, writer: *std.io.Writer) std.io.Writer.Error!void {1011fn formatTracking(data: FormatTrackingData, writer: *std.Io.Writer) std.Io.Writer.Error!void {
1012 var it = data.func.inst_tracking.iterator();1012 var it = data.func.inst_tracking.iterator();
1013 while (it.next()) |entry| try writer.print("\n%{d} = {f}", .{ entry.key_ptr.*, entry.value_ptr.* });1013 while (it.next()) |entry| try writer.print("\n%{d} = {f}", .{ entry.key_ptr.*, entry.value_ptr.* });
1014}1014}
src/arch/riscv64/Mir.zig+1-1
...@@ -92,7 +92,7 @@ pub const Inst = struct {...@@ -92,7 +92,7 @@ pub const Inst = struct {
92 },92 },
93 };93 };
9494
95 pub fn format(inst: Inst, writer: *std.io.Writer) std.io.Writer.Error!void {95 pub fn format(inst: Inst, writer: *std.Io.Writer) std.Io.Writer.Error!void {
96 try writer.print("Tag: {s}, Data: {s}", .{ @tagName(inst.tag), @tagName(inst.data) });96 try writer.print("Tag: {s}, Data: {s}", .{ @tagName(inst.tag), @tagName(inst.data) });
97 }97 }
98};98};
src/arch/x86_64/CodeGen.zig+2-2
...@@ -6,7 +6,7 @@ const log = std.log.scoped(.codegen);...@@ -6,7 +6,7 @@ const log = std.log.scoped(.codegen);
6const tracking_log = std.log.scoped(.tracking);6const tracking_log = std.log.scoped(.tracking);
7const verbose_tracking_log = std.log.scoped(.verbose_tracking);7const verbose_tracking_log = std.log.scoped(.verbose_tracking);
8const wip_mir_log = std.log.scoped(.wip_mir);8const wip_mir_log = std.log.scoped(.wip_mir);
9const Writer = std.io.Writer;9const Writer = std.Io.Writer;
1010
11const Air = @import("../../Air.zig");11const Air = @import("../../Air.zig");
12const Allocator = std.mem.Allocator;12const Allocator = std.mem.Allocator;
...@@ -1102,7 +1102,7 @@ const FormatAirData = struct {...@@ -1102,7 +1102,7 @@ const FormatAirData = struct {
1102 self: *CodeGen,1102 self: *CodeGen,
1103 inst: Air.Inst.Index,1103 inst: Air.Inst.Index,
1104};1104};
1105fn formatAir(data: FormatAirData, w: *std.io.Writer) Writer.Error!void {1105fn formatAir(data: FormatAirData, w: *Writer) Writer.Error!void {
1106 data.self.air.writeInst(w, data.inst, data.self.pt, data.self.liveness);1106 data.self.air.writeInst(w, data.inst, data.self.pt, data.self.liveness);
1107}1107}
1108fn fmtAir(self: *CodeGen, inst: Air.Inst.Index) std.fmt.Formatter(FormatAirData, formatAir) {1108fn fmtAir(self: *CodeGen, inst: Air.Inst.Index) std.fmt.Formatter(FormatAirData, formatAir) {
src/arch/x86_64/Disassembler.zig+9-11
...@@ -287,13 +287,12 @@ const Prefixes = struct {...@@ -287,13 +287,12 @@ const Prefixes = struct {
287287
288fn parsePrefixes(dis: *Disassembler) !Prefixes {288fn parsePrefixes(dis: *Disassembler) !Prefixes {
289 const rex_prefix_mask: u4 = 0b0100;289 const rex_prefix_mask: u4 = 0b0100;
290 var stream = std.io.fixedBufferStream(dis.code[dis.pos..]);290 var reader: std.Io.Reader = .fixed(dis.code[dis.pos..]);
291 const reader = stream.reader();
292291
293 var res: Prefixes = .{};292 var res: Prefixes = .{};
294293
295 while (true) {294 while (true) {
296 const next_byte = try reader.readByte();295 const next_byte = try reader.takeByte();
297 dis.pos += 1;296 dis.pos += 1;
298297
299 switch (next_byte) {298 switch (next_byte) {
...@@ -341,12 +340,11 @@ fn parseEncoding(dis: *Disassembler, prefixes: Prefixes) !?Encoding {...@@ -341,12 +340,11 @@ fn parseEncoding(dis: *Disassembler, prefixes: Prefixes) !?Encoding {
341 const o_mask: u8 = 0b1111_1000;340 const o_mask: u8 = 0b1111_1000;
342341
343 var opcode: [3]u8 = .{ 0, 0, 0 };342 var opcode: [3]u8 = .{ 0, 0, 0 };
344 var stream = std.io.fixedBufferStream(dis.code[dis.pos..]);343 var reader: std.Io.Reader = .fixed(dis.code[dis.pos..]);
345 const reader = stream.reader();
346344
347 comptime var opc_count = 0;345 comptime var opc_count = 0;
348 inline while (opc_count < 3) : (opc_count += 1) {346 inline while (opc_count < 3) : (opc_count += 1) {
349 const byte = try reader.readByte();347 const byte = try reader.takeByte();
350 opcode[opc_count] = byte;348 opcode[opc_count] = byte;
351 dis.pos += 1;349 dis.pos += 1;
352350
...@@ -410,11 +408,11 @@ fn parseImm(dis: *Disassembler, kind: Encoding.Op) !Immediate {...@@ -410,11 +408,11 @@ fn parseImm(dis: *Disassembler, kind: Encoding.Op) !Immediate {
410}408}
411409
412fn parseOffset(dis: *Disassembler) !u64 {410fn parseOffset(dis: *Disassembler) !u64 {
413 var stream = std.io.fixedBufferStream(dis.code[dis.pos..]);411 var reader: std.Io.Reader = .fixed(dis.code);
414 const reader = stream.reader();412 reader.seek = dis.pos;
415 const offset = try reader.readInt(u64, .little);413 defer dis.pos = reader.seek;
416 dis.pos += 8;414
417 return offset;415 return reader.takeInt(u64, .little);
418}416}
419417
420const ModRm = packed struct {418const ModRm = packed struct {
src/arch/x86_64/Emit.zig+1-1
...@@ -698,7 +698,7 @@ fn encodeInst(emit: *Emit, lowered_inst: Instruction, reloc_info: []const RelocI...@@ -698,7 +698,7 @@ fn encodeInst(emit: *Emit, lowered_inst: Instruction, reloc_info: []const RelocI
698 const gpa = comp.gpa;698 const gpa = comp.gpa;
699 const start_offset: u32 = @intCast(emit.code.items.len);699 const start_offset: u32 = @intCast(emit.code.items.len);
700 {700 {
701 var aw: std.io.Writer.Allocating = .fromArrayList(gpa, emit.code);701 var aw: std.Io.Writer.Allocating = .fromArrayList(gpa, emit.code);
702 defer emit.code.* = aw.toArrayList();702 defer emit.code.* = aw.toArrayList();
703 lowered_inst.encode(&aw.writer, .{}) catch |err| switch (err) {703 lowered_inst.encode(&aw.writer, .{}) catch |err| switch (err) {
704 error.WriteFailed => return error.OutOfMemory,704 error.WriteFailed => return error.OutOfMemory,
src/arch/x86_64/Encoding.zig+2-2
...@@ -158,7 +158,7 @@ pub fn modRmExt(encoding: Encoding) u3 {...@@ -158,7 +158,7 @@ pub fn modRmExt(encoding: Encoding) u3 {
158 };158 };
159}159}
160160
161pub fn format(encoding: Encoding, writer: *std.io.Writer) std.io.Writer.Error!void {161pub fn format(encoding: Encoding, writer: *std.Io.Writer) std.Io.Writer.Error!void {
162 var opc = encoding.opcode();162 var opc = encoding.opcode();
163 if (encoding.data.mode.isVex()) {163 if (encoding.data.mode.isVex()) {
164 try writer.writeAll("VEX.");164 try writer.writeAll("VEX.");
...@@ -1016,7 +1016,7 @@ fn estimateInstructionLength(prefix: Prefix, encoding: Encoding, ops: []const Op...@@ -1016,7 +1016,7 @@ fn estimateInstructionLength(prefix: Prefix, encoding: Encoding, ops: []const Op
1016 // By using a buffer with maximum length of encoded instruction, we can use1016 // By using a buffer with maximum length of encoded instruction, we can use
1017 // the `end` field of the Writer for the count.1017 // the `end` field of the Writer for the count.
1018 var buf: [16]u8 = undefined;1018 var buf: [16]u8 = undefined;
1019 var trash: std.io.Writer.Discarding = .init(&buf);1019 var trash: std.Io.Writer.Discarding = .init(&buf);
1020 inst.encode(&trash.writer, .{1020 inst.encode(&trash.writer, .{
1021 .allow_frame_locs = true,1021 .allow_frame_locs = true,
1022 .allow_symbols = true,1022 .allow_symbols = true,
src/arch/x86_64/bits.zig+2-2
...@@ -827,7 +827,7 @@ pub const Memory = struct {...@@ -827,7 +827,7 @@ pub const Memory = struct {
827 };827 };
828 }828 }
829829
830 pub fn format(s: Size, writer: *std.io.Writer) std.io.Writer.Error!void {830 pub fn format(s: Size, writer: *std.Io.Writer) std.Io.Writer.Error!void {
831 if (s == .none) return;831 if (s == .none) return;
832 try writer.writeAll(@tagName(s));832 try writer.writeAll(@tagName(s));
833 switch (s) {833 switch (s) {
...@@ -892,7 +892,7 @@ pub const Immediate = union(enum) {...@@ -892,7 +892,7 @@ pub const Immediate = union(enum) {
892 return .{ .signed = x };892 return .{ .signed = x };
893 }893 }
894894
895 pub fn format(imm: Immediate, writer: *std.io.Writer) std.io.Writer.Error!void {895 pub fn format(imm: Immediate, writer: *std.Io.Writer) std.Io.Writer.Error!void {
896 switch (imm) {896 switch (imm) {
897 inline else => |int| try writer.print("{d}", .{int}),897 inline else => |int| try writer.print("{d}", .{int}),
898 .nav => |nav_off| try writer.print("Nav({d}) + {d}", .{ @intFromEnum(nav_off.nav), nav_off.off }),898 .nav => |nav_off| try writer.print("Nav({d}) + {d}", .{ @intFromEnum(nav_off.nav), nav_off.off }),
src/arch/x86_64/encoder.zig+1-1
...@@ -3,7 +3,7 @@ const assert = std.debug.assert;...@@ -3,7 +3,7 @@ const assert = std.debug.assert;
3const log = std.log.scoped(.x86_64_encoder);3const log = std.log.scoped(.x86_64_encoder);
4const math = std.math;4const math = std.math;
5const testing = std.testing;5const testing = std.testing;
6const Writer = std.io.Writer;6const Writer = std.Io.Writer;
77
8const bits = @import("bits.zig");8const bits = @import("bits.zig");
9const Encoding = @import("Encoding.zig");9const Encoding = @import("Encoding.zig");
src/codegen/c.zig+10-10
...@@ -4,7 +4,7 @@ const assert = std.debug.assert;...@@ -4,7 +4,7 @@ const assert = std.debug.assert;
4const mem = std.mem;4const mem = std.mem;
5const log = std.log.scoped(.c);5const log = std.log.scoped(.c);
6const Allocator = mem.Allocator;6const Allocator = mem.Allocator;
7const Writer = std.io.Writer;7const Writer = std.Io.Writer;
88
9const dev = @import("../dev.zig");9const dev = @import("../dev.zig");
10const link = @import("../link.zig");10const link = @import("../link.zig");
...@@ -345,15 +345,15 @@ fn isReservedIdent(ident: []const u8) bool {...@@ -345,15 +345,15 @@ fn isReservedIdent(ident: []const u8) bool {
345 } else return reserved_idents.has(ident);345 } else return reserved_idents.has(ident);
346}346}
347347
348fn formatIdentSolo(ident: []const u8, w: *std.io.Writer) std.io.Writer.Error!void {348fn formatIdentSolo(ident: []const u8, w: *Writer) Writer.Error!void {
349 return formatIdentOptions(ident, w, true);349 return formatIdentOptions(ident, w, true);
350}350}
351351
352fn formatIdentUnsolo(ident: []const u8, w: *std.io.Writer) std.io.Writer.Error!void {352fn formatIdentUnsolo(ident: []const u8, w: *Writer) Writer.Error!void {
353 return formatIdentOptions(ident, w, false);353 return formatIdentOptions(ident, w, false);
354}354}
355355
356fn formatIdentOptions(ident: []const u8, w: *std.io.Writer, solo: bool) std.io.Writer.Error!void {356fn formatIdentOptions(ident: []const u8, w: *Writer, solo: bool) Writer.Error!void {
357 if (solo and isReservedIdent(ident)) {357 if (solo and isReservedIdent(ident)) {
358 try w.writeAll("zig_e_");358 try w.writeAll("zig_e_");
359 }359 }
...@@ -384,7 +384,7 @@ const CTypePoolStringFormatData = struct {...@@ -384,7 +384,7 @@ const CTypePoolStringFormatData = struct {
384 ctype_pool: *const CType.Pool,384 ctype_pool: *const CType.Pool,
385 solo: bool,385 solo: bool,
386};386};
387fn formatCTypePoolString(data: CTypePoolStringFormatData, w: *std.io.Writer) std.io.Writer.Error!void {387fn formatCTypePoolString(data: CTypePoolStringFormatData, w: *Writer) Writer.Error!void {
388 if (data.ctype_pool_string.toSlice(data.ctype_pool)) |slice|388 if (data.ctype_pool_string.toSlice(data.ctype_pool)) |slice|
389 try formatIdentOptions(slice, w, data.solo)389 try formatIdentOptions(slice, w, data.solo)
390 else390 else
...@@ -711,8 +711,8 @@ pub const Function = struct {...@@ -711,8 +711,8 @@ pub const Function = struct {
711/// It is not available when generating .h file.711/// It is not available when generating .h file.
712pub const Object = struct {712pub const Object = struct {
713 dg: DeclGen,713 dg: DeclGen,
714 code_header: std.io.Writer.Allocating,714 code_header: Writer.Allocating,
715 code: std.io.Writer.Allocating,715 code: Writer.Allocating,
716 indent_counter: usize,716 indent_counter: usize,
717717
718 const indent_width = 1;718 const indent_width = 1;
...@@ -748,7 +748,7 @@ pub const DeclGen = struct {...@@ -748,7 +748,7 @@ pub const DeclGen = struct {
748 pass: Pass,748 pass: Pass,
749 is_naked_fn: bool,749 is_naked_fn: bool,
750 expected_block: ?u32,750 expected_block: ?u32,
751 fwd_decl: std.io.Writer.Allocating,751 fwd_decl: Writer.Allocating,
752 error_msg: ?*Zcu.ErrorMsg,752 error_msg: ?*Zcu.ErrorMsg,
753 ctype_pool: CType.Pool,753 ctype_pool: CType.Pool,
754 scratch: std.ArrayListUnmanaged(u32),754 scratch: std.ArrayListUnmanaged(u32),
...@@ -8287,7 +8287,7 @@ const FormatStringContext = struct {...@@ -8287,7 +8287,7 @@ const FormatStringContext = struct {
8287 sentinel: ?u8,8287 sentinel: ?u8,
8288};8288};
82898289
8290fn formatStringLiteral(data: FormatStringContext, w: *std.io.Writer) std.io.Writer.Error!void {8290fn formatStringLiteral(data: FormatStringContext, w: *Writer) Writer.Error!void {
8291 var literal: StringLiteral = .init(w, data.str.len + @intFromBool(data.sentinel != null));8291 var literal: StringLiteral = .init(w, data.str.len + @intFromBool(data.sentinel != null));
8292 try literal.start();8292 try literal.start();
8293 for (data.str) |c| try literal.writeChar(c);8293 for (data.str) |c| try literal.writeChar(c);
...@@ -8314,7 +8314,7 @@ const FormatIntLiteralContext = struct {...@@ -8314,7 +8314,7 @@ const FormatIntLiteralContext = struct {
8314 base: u8,8314 base: u8,
8315 case: std.fmt.Case,8315 case: std.fmt.Case,
8316};8316};
8317fn formatIntLiteral(data: FormatIntLiteralContext, w: *std.io.Writer) std.io.Writer.Error!void {8317fn formatIntLiteral(data: FormatIntLiteralContext, w: *Writer) Writer.Error!void {
8318 const pt = data.dg.pt;8318 const pt = data.dg.pt;
8319 const zcu = pt.zcu;8319 const zcu = pt.zcu;
8320 const target = &data.dg.mod.resolved_target.result;8320 const target = &data.dg.mod.resolved_target.result;
src/codegen/c/Type.zig+1-1
...@@ -3396,7 +3396,7 @@ pub const AlignAs = packed struct {...@@ -3396,7 +3396,7 @@ pub const AlignAs = packed struct {
33963396
3397const std = @import("std");3397const std = @import("std");
3398const assert = std.debug.assert;3398const assert = std.debug.assert;
3399const Writer = std.io.Writer;3399const Writer = std.Io.Writer;
34003400
3401const CType = @This();3401const CType = @This();
3402const InternPool = @import("../../InternPool.zig");3402const InternPool = @import("../../InternPool.zig");
src/codegen/llvm.zig+1-1
...@@ -2684,7 +2684,7 @@ pub const Object = struct {...@@ -2684,7 +2684,7 @@ pub const Object = struct {
2684 }2684 }
26852685
2686 fn allocTypeName(o: *Object, pt: Zcu.PerThread, ty: Type) Allocator.Error![:0]const u8 {2686 fn allocTypeName(o: *Object, pt: Zcu.PerThread, ty: Type) Allocator.Error![:0]const u8 {
2687 var aw: std.io.Writer.Allocating = .init(o.gpa);2687 var aw: std.Io.Writer.Allocating = .init(o.gpa);
2688 defer aw.deinit();2688 defer aw.deinit();
2689 ty.print(&aw.writer, pt) catch |err| switch (err) {2689 ty.print(&aw.writer, pt) catch |err| switch (err) {
2690 error.WriteFailed => return error.OutOfMemory,2690 error.WriteFailed => return error.OutOfMemory,
src/codegen/spirv/CodeGen.zig+1-1
...@@ -1211,7 +1211,7 @@ fn constantNavRef(cg: *CodeGen, ty: Type, nav_index: InternPool.Nav.Index) !Id {...@@ -1211,7 +1211,7 @@ fn constantNavRef(cg: *CodeGen, ty: Type, nav_index: InternPool.Nav.Index) !Id {
1211// Turn a Zig type's name into a cache reference.1211// Turn a Zig type's name into a cache reference.
1212fn resolveTypeName(cg: *CodeGen, ty: Type) ![]const u8 {1212fn resolveTypeName(cg: *CodeGen, ty: Type) ![]const u8 {
1213 const gpa = cg.module.gpa;1213 const gpa = cg.module.gpa;
1214 var aw: std.io.Writer.Allocating = .init(gpa);1214 var aw: std.Io.Writer.Allocating = .init(gpa);
1215 defer aw.deinit();1215 defer aw.deinit();
1216 ty.print(&aw.writer, cg.pt) catch |err| switch (err) {1216 ty.print(&aw.writer, cg.pt) catch |err| switch (err) {
1217 error.WriteFailed => return error.OutOfMemory,1217 error.WriteFailed => return error.OutOfMemory,
src/codegen/spirv/spec.zig+1-1
...@@ -18,7 +18,7 @@ pub const Id = enum(Word) {...@@ -18,7 +18,7 @@ pub const Id = enum(Word) {
18 none,18 none,
19 _,19 _,
2020
21 pub fn format(self: Id, writer: *std.io.Writer) std.io.Writer.Error!void {21 pub fn format(self: Id, writer: *std.Io.Writer) std.Io.Writer.Error!void {
22 switch (self) {22 switch (self) {
23 .none => try writer.writeAll("(none)"),23 .none => try writer.writeAll("(none)"),
24 else => try writer.print("%{d}", .{@intFromEnum(self)}),24 else => try writer.print("%{d}", .{@intFromEnum(self)}),
src/crash_report.zig-1
...@@ -2,7 +2,6 @@ const std = @import("std");...@@ -2,7 +2,6 @@ const std = @import("std");
2const builtin = @import("builtin");2const builtin = @import("builtin");
3const build_options = @import("build_options");3const build_options = @import("build_options");
4const debug = std.debug;4const debug = std.debug;
5const io = std.io;
6const print_zir = @import("print_zir.zig");5const print_zir = @import("print_zir.zig");
7const windows = std.os.windows;6const windows = std.os.windows;
8const posix = std.posix;7const posix = std.posix;
src/libs/mingw.zig+1-1
...@@ -325,7 +325,7 @@ pub fn buildImportLib(comp: *Compilation, lib_name: []const u8) !void {...@@ -325,7 +325,7 @@ pub fn buildImportLib(comp: *Compilation, lib_name: []const u8) !void {
325325
326 for (aro_comp.diagnostics.list.items) |diagnostic| {326 for (aro_comp.diagnostics.list.items) |diagnostic| {
327 if (diagnostic.kind == .@"fatal error" or diagnostic.kind == .@"error") {327 if (diagnostic.kind == .@"fatal error" or diagnostic.kind == .@"error") {
328 aro.Diagnostics.render(&aro_comp, std.io.tty.detectConfig(std.fs.File.stderr()));328 aro.Diagnostics.render(&aro_comp, std.Io.tty.detectConfig(std.fs.File.stderr()));
329 return error.AroPreprocessorFailed;329 return error.AroPreprocessorFailed;
330 }330 }
331 }331 }
src/link/C.zig+4-4
...@@ -348,7 +348,7 @@ pub fn updateLineNumber(self: *C, pt: Zcu.PerThread, ti_id: InternPool.TrackedIn...@@ -348,7 +348,7 @@ pub fn updateLineNumber(self: *C, pt: Zcu.PerThread, ti_id: InternPool.TrackedIn
348 _ = ti_id;348 _ = ti_id;
349}349}
350350
351fn abiDefines(w: *std.io.Writer, target: *const std.Target) !void {351fn abiDefines(w: *std.Io.Writer, target: *const std.Target) !void {
352 switch (target.abi) {352 switch (target.abi) {
353 .msvc, .itanium => try w.writeAll("#define ZIG_TARGET_ABI_MSVC\n"),353 .msvc, .itanium => try w.writeAll("#define ZIG_TARGET_ABI_MSVC\n"),
354 else => {},354 else => {},
...@@ -400,7 +400,7 @@ pub fn flush(self: *C, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.P...@@ -400,7 +400,7 @@ pub fn flush(self: *C, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.P
400 };400 };
401 defer f.deinit(gpa);401 defer f.deinit(gpa);
402402
403 var abi_defines_aw: std.io.Writer.Allocating = .init(gpa);403 var abi_defines_aw: std.Io.Writer.Allocating = .init(gpa);
404 defer abi_defines_aw.deinit();404 defer abi_defines_aw.deinit();
405 abiDefines(&abi_defines_aw.writer, zcu.getTarget()) catch |err| switch (err) {405 abiDefines(&abi_defines_aw.writer, zcu.getTarget()) catch |err| switch (err) {
406 error.WriteFailed => return error.OutOfMemory,406 error.WriteFailed => return error.OutOfMemory,
...@@ -415,7 +415,7 @@ pub fn flush(self: *C, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.P...@@ -415,7 +415,7 @@ pub fn flush(self: *C, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.P
415 const ctypes_index = f.all_buffers.items.len;415 const ctypes_index = f.all_buffers.items.len;
416 f.all_buffers.items.len += 1;416 f.all_buffers.items.len += 1;
417417
418 var asm_aw: std.io.Writer.Allocating = .init(gpa);418 var asm_aw: std.Io.Writer.Allocating = .init(gpa);
419 defer asm_aw.deinit();419 defer asm_aw.deinit();
420 codegen.genGlobalAsm(zcu, &asm_aw.writer) catch |err| switch (err) {420 codegen.genGlobalAsm(zcu, &asm_aw.writer) catch |err| switch (err) {
421 error.WriteFailed => return error.OutOfMemory,421 error.WriteFailed => return error.OutOfMemory,
...@@ -582,7 +582,7 @@ fn flushCTypes(...@@ -582,7 +582,7 @@ fn flushCTypes(
582 try global_from_decl_map.ensureTotalCapacity(gpa, decl_ctype_pool.items.len);582 try global_from_decl_map.ensureTotalCapacity(gpa, decl_ctype_pool.items.len);
583 defer global_from_decl_map.clearRetainingCapacity();583 defer global_from_decl_map.clearRetainingCapacity();
584584
585 var ctypes_aw: std.io.Writer.Allocating = .fromArrayList(gpa, &f.ctypes);585 var ctypes_aw: std.Io.Writer.Allocating = .fromArrayList(gpa, &f.ctypes);
586 const ctypes_bw = &ctypes_aw.writer;586 const ctypes_bw = &ctypes_aw.writer;
587 defer f.ctypes = ctypes_aw.toArrayList();587 defer f.ctypes = ctypes_aw.toArrayList();
588588
src/link/Coff.zig+1-1
...@@ -3039,7 +3039,7 @@ const ImportTable = struct {...@@ -3039,7 +3039,7 @@ const ImportTable = struct {
3039 itab: ImportTable,3039 itab: ImportTable,
3040 ctx: Context,3040 ctx: Context,
30413041
3042 fn default(f: Format, writer: *std.io.Writer) std.io.Writer.Error!void {3042 fn default(f: Format, writer: *std.Io.Writer) std.Io.Writer.Error!void {
3043 const lib_name = f.ctx.coff.temp_strtab.getAssumeExists(f.ctx.name_off);3043 const lib_name = f.ctx.coff.temp_strtab.getAssumeExists(f.ctx.name_off);
3044 const base_vaddr = getBaseAddress(f.ctx);3044 const base_vaddr = getBaseAddress(f.ctx);
3045 try writer.print("IAT({s}.dll) @{x}:", .{ lib_name, base_vaddr });3045 try writer.print("IAT({s}.dll) @{x}:", .{ lib_name, base_vaddr });
src/link/Elf.zig+5-5
...@@ -3869,7 +3869,7 @@ fn fmtShdr(self: *Elf, shdr: elf.Elf64_Shdr) std.fmt.Formatter(FormatShdr, forma...@@ -3869,7 +3869,7 @@ fn fmtShdr(self: *Elf, shdr: elf.Elf64_Shdr) std.fmt.Formatter(FormatShdr, forma
3869 } };3869 } };
3870}3870}
38713871
3872fn formatShdr(ctx: FormatShdr, writer: *std.io.Writer) std.io.Writer.Error!void {3872fn formatShdr(ctx: FormatShdr, writer: *std.Io.Writer) std.Io.Writer.Error!void {
3873 const shdr = ctx.shdr;3873 const shdr = ctx.shdr;
3874 try writer.print("{s} : @{x} ({x}) : align({x}) : size({x}) : entsize({x}) : flags({f})", .{3874 try writer.print("{s} : @{x} ({x}) : align({x}) : size({x}) : entsize({x}) : flags({f})", .{
3875 ctx.elf_file.getShString(shdr.sh_name), shdr.sh_offset,3875 ctx.elf_file.getShString(shdr.sh_name), shdr.sh_offset,
...@@ -3883,7 +3883,7 @@ pub fn fmtShdrFlags(sh_flags: u64) std.fmt.Formatter(u64, formatShdrFlags) {...@@ -3883,7 +3883,7 @@ pub fn fmtShdrFlags(sh_flags: u64) std.fmt.Formatter(u64, formatShdrFlags) {
3883 return .{ .data = sh_flags };3883 return .{ .data = sh_flags };
3884}3884}
38853885
3886fn formatShdrFlags(sh_flags: u64, writer: *std.io.Writer) std.io.Writer.Error!void {3886fn formatShdrFlags(sh_flags: u64, writer: *std.Io.Writer) std.Io.Writer.Error!void {
3887 if (elf.SHF_WRITE & sh_flags != 0) {3887 if (elf.SHF_WRITE & sh_flags != 0) {
3888 try writer.writeAll("W");3888 try writer.writeAll("W");
3889 }3889 }
...@@ -3940,7 +3940,7 @@ fn fmtPhdr(self: *Elf, phdr: elf.Elf64_Phdr) std.fmt.Formatter(FormatPhdr, forma...@@ -3940,7 +3940,7 @@ fn fmtPhdr(self: *Elf, phdr: elf.Elf64_Phdr) std.fmt.Formatter(FormatPhdr, forma
3940 } };3940 } };
3941}3941}
39423942
3943fn formatPhdr(ctx: FormatPhdr, writer: *std.io.Writer) std.io.Writer.Error!void {3943fn formatPhdr(ctx: FormatPhdr, writer: *std.Io.Writer) std.Io.Writer.Error!void {
3944 const phdr = ctx.phdr;3944 const phdr = ctx.phdr;
3945 const write = phdr.p_flags & elf.PF_W != 0;3945 const write = phdr.p_flags & elf.PF_W != 0;
3946 const read = phdr.p_flags & elf.PF_R != 0;3946 const read = phdr.p_flags & elf.PF_R != 0;
...@@ -3971,7 +3971,7 @@ pub fn dumpState(self: *Elf) std.fmt.Formatter(*Elf, fmtDumpState) {...@@ -3971,7 +3971,7 @@ pub fn dumpState(self: *Elf) std.fmt.Formatter(*Elf, fmtDumpState) {
3971 return .{ .data = self };3971 return .{ .data = self };
3972}3972}
39733973
3974fn fmtDumpState(self: *Elf, writer: *std.io.Writer) std.io.Writer.Error!void {3974fn fmtDumpState(self: *Elf, writer: *std.Io.Writer) std.Io.Writer.Error!void {
3975 const shared_objects = self.shared_objects.values();3975 const shared_objects = self.shared_objects.values();
39763976
3977 if (self.zigObjectPtr()) |zig_object| {3977 if (self.zigObjectPtr()) |zig_object| {
...@@ -4189,7 +4189,7 @@ pub const Ref = struct {...@@ -4189,7 +4189,7 @@ pub const Ref = struct {
4189 return ref.index == other.index and ref.file == other.file;4189 return ref.index == other.index and ref.file == other.file;
4190 }4190 }
41914191
4192 pub fn format(ref: Ref, writer: *std.io.Writer) std.io.Writer.Error!void {4192 pub fn format(ref: Ref, writer: *std.Io.Writer) std.Io.Writer.Error!void {
4193 try writer.print("ref({d},{d})", .{ ref.index, ref.file });4193 try writer.print("ref({d},{d})", .{ ref.index, ref.file });
4194 }4194 }
4195};4195};
src/link/Elf/Archive.zig+2-2
...@@ -204,7 +204,7 @@ pub const ArSymtab = struct {...@@ -204,7 +204,7 @@ pub const ArSymtab = struct {
204 ar: ArSymtab,204 ar: ArSymtab,
205 elf_file: *Elf,205 elf_file: *Elf,
206206
207 fn default(f: Format, writer: *std.io.Writer) std.io.Writer.Error!void {207 fn default(f: Format, writer: *std.Io.Writer) std.Io.Writer.Error!void {
208 const ar = f.ar;208 const ar = f.ar;
209 const elf_file = f.elf_file;209 const elf_file = f.elf_file;
210 for (ar.symtab.items, 0..) |entry, i| {210 for (ar.symtab.items, 0..) |entry, i| {
...@@ -259,7 +259,7 @@ pub const ArStrtab = struct {...@@ -259,7 +259,7 @@ pub const ArStrtab = struct {
259 try writer.writeAll(ar.buffer.items);259 try writer.writeAll(ar.buffer.items);
260 }260 }
261261
262 pub fn format(ar: ArStrtab, writer: *std.io.Writer) std.io.Writer.Error!void {262 pub fn format(ar: ArStrtab, writer: *std.Io.Writer) std.Io.Writer.Error!void {
263 try writer.print("{f}", .{std.ascii.hexEscape(ar.buffer.items, .lower)});263 try writer.print("{f}", .{std.ascii.hexEscape(ar.buffer.items, .lower)});
264 }264 }
265};265};
src/link/Elf/AtomList.zig+1-1
...@@ -170,7 +170,7 @@ const Format = struct {...@@ -170,7 +170,7 @@ const Format = struct {
170 atom_list: AtomList,170 atom_list: AtomList,
171 elf_file: *Elf,171 elf_file: *Elf,
172172
173 fn default(f: Format, writer: *std.io.Writer) std.io.Writer.Error!void {173 fn default(f: Format, writer: *std.Io.Writer) std.Io.Writer.Error!void {
174 const list = f.atom_list;174 const list = f.atom_list;
175 try writer.print("list : @{x} : shdr({d}) : align({x}) : size({x})", .{175 try writer.print("list : @{x} : shdr({d}) : align({x}) : size({x})", .{
176 list.address(f.elf_file),176 list.address(f.elf_file),
src/link/Elf/LinkerDefined.zig+1-1
...@@ -448,7 +448,7 @@ const Format = struct {...@@ -448,7 +448,7 @@ const Format = struct {
448 self: *LinkerDefined,448 self: *LinkerDefined,
449 elf_file: *Elf,449 elf_file: *Elf,
450450
451 fn symtab(ctx: Format, writer: *std.io.Writer) std.io.Writer.Error!void {451 fn symtab(ctx: Format, writer: *std.Io.Writer) std.Io.Writer.Error!void {
452 const self = ctx.self;452 const self = ctx.self;
453 const elf_file = ctx.elf_file;453 const elf_file = ctx.elf_file;
454 try writer.writeAll(" globals\n");454 try writer.writeAll(" globals\n");
src/link/Elf/Merge.zig+2-2
...@@ -168,7 +168,7 @@ pub const Section = struct {...@@ -168,7 +168,7 @@ pub const Section = struct {
168 msec: Section,168 msec: Section,
169 elf_file: *Elf,169 elf_file: *Elf,
170170
171 pub fn default(f: Format, writer: *std.io.Writer) std.io.Writer.Error!void {171 pub fn default(f: Format, writer: *std.Io.Writer) std.Io.Writer.Error!void {
172 const msec = f.msec;172 const msec = f.msec;
173 const elf_file = f.elf_file;173 const elf_file = f.elf_file;
174 try writer.print("{s} : @{x} : size({x}) : align({x}) : entsize({x}) : type({x}) : flags({x})\n", .{174 try writer.print("{s} : @{x} : size({x}) : align({x}) : entsize({x}) : type({x}) : flags({x})\n", .{
...@@ -222,7 +222,7 @@ pub const Subsection = struct {...@@ -222,7 +222,7 @@ pub const Subsection = struct {
222 msub: Subsection,222 msub: Subsection,
223 elf_file: *Elf,223 elf_file: *Elf,
224224
225 pub fn default(ctx: Format, writer: *std.io.Writer) std.io.Writer.Error!void {225 pub fn default(ctx: Format, writer: *std.Io.Writer) std.Io.Writer.Error!void {
226 const msub = ctx.msub;226 const msub = ctx.msub;
227 const elf_file = ctx.elf_file;227 const elf_file = ctx.elf_file;
228 try writer.print("@{x} : align({x}) : size({x})", .{228 try writer.print("@{x} : align({x}) : size({x})", .{
src/link/Elf/Object.zig+6-6
...@@ -1442,7 +1442,7 @@ const Format = struct {...@@ -1442,7 +1442,7 @@ const Format = struct {
1442 object: *Object,1442 object: *Object,
1443 elf_file: *Elf,1443 elf_file: *Elf,
14441444
1445 fn symtab(f: Format, writer: *std.io.Writer) std.io.Writer.Error!void {1445 fn symtab(f: Format, writer: *std.Io.Writer) std.Io.Writer.Error!void {
1446 const object = f.object;1446 const object = f.object;
1447 const elf_file = f.elf_file;1447 const elf_file = f.elf_file;
1448 try writer.writeAll(" locals\n");1448 try writer.writeAll(" locals\n");
...@@ -1461,7 +1461,7 @@ const Format = struct {...@@ -1461,7 +1461,7 @@ const Format = struct {
1461 }1461 }
1462 }1462 }
14631463
1464 fn atoms(f: Format, writer: *std.io.Writer) std.io.Writer.Error!void {1464 fn atoms(f: Format, writer: *std.Io.Writer) std.Io.Writer.Error!void {
1465 const object = f.object;1465 const object = f.object;
1466 try writer.writeAll(" atoms\n");1466 try writer.writeAll(" atoms\n");
1467 for (object.atoms_indexes.items) |atom_index| {1467 for (object.atoms_indexes.items) |atom_index| {
...@@ -1470,7 +1470,7 @@ const Format = struct {...@@ -1470,7 +1470,7 @@ const Format = struct {
1470 }1470 }
1471 }1471 }
14721472
1473 fn cies(f: Format, writer: *std.io.Writer) std.io.Writer.Error!void {1473 fn cies(f: Format, writer: *std.Io.Writer) std.Io.Writer.Error!void {
1474 const object = f.object;1474 const object = f.object;
1475 try writer.writeAll(" cies\n");1475 try writer.writeAll(" cies\n");
1476 for (object.cies.items, 0..) |cie, i| {1476 for (object.cies.items, 0..) |cie, i| {
...@@ -1478,7 +1478,7 @@ const Format = struct {...@@ -1478,7 +1478,7 @@ const Format = struct {
1478 }1478 }
1479 }1479 }
14801480
1481 fn fdes(f: Format, writer: *std.io.Writer) std.io.Writer.Error!void {1481 fn fdes(f: Format, writer: *std.Io.Writer) std.Io.Writer.Error!void {
1482 const object = f.object;1482 const object = f.object;
1483 try writer.writeAll(" fdes\n");1483 try writer.writeAll(" fdes\n");
1484 for (object.fdes.items, 0..) |fde, i| {1484 for (object.fdes.items, 0..) |fde, i| {
...@@ -1486,7 +1486,7 @@ const Format = struct {...@@ -1486,7 +1486,7 @@ const Format = struct {
1486 }1486 }
1487 }1487 }
14881488
1489 fn groups(f: Format, writer: *std.io.Writer) std.io.Writer.Error!void {1489 fn groups(f: Format, writer: *std.Io.Writer) std.Io.Writer.Error!void {
1490 const object = f.object;1490 const object = f.object;
1491 const elf_file = f.elf_file;1491 const elf_file = f.elf_file;
1492 try writer.writeAll(" groups\n");1492 try writer.writeAll(" groups\n");
...@@ -1536,7 +1536,7 @@ pub fn fmtPath(self: Object) std.fmt.Formatter(Object, formatPath) {...@@ -1536,7 +1536,7 @@ pub fn fmtPath(self: Object) std.fmt.Formatter(Object, formatPath) {
1536 return .{ .data = self };1536 return .{ .data = self };
1537}1537}
15381538
1539fn formatPath(object: Object, writer: *std.io.Writer) std.io.Writer.Error!void {1539fn formatPath(object: Object, writer: *std.Io.Writer) std.Io.Writer.Error!void {
1540 if (object.archive) |ar| {1540 if (object.archive) |ar| {
1541 try writer.print("{f}({f})", .{ ar.path, object.path });1541 try writer.print("{f}({f})", .{ ar.path, object.path });
1542 } else {1542 } else {
src/link/Elf/SharedObject.zig+1-1
...@@ -520,7 +520,7 @@ const Format = struct {...@@ -520,7 +520,7 @@ const Format = struct {
520 shared: SharedObject,520 shared: SharedObject,
521 elf_file: *Elf,521 elf_file: *Elf,
522522
523 fn symtab(f: Format, writer: *std.io.Writer) std.io.Writer.Error!void {523 fn symtab(f: Format, writer: *std.Io.Writer) std.Io.Writer.Error!void {
524 const shared = f.shared;524 const shared = f.shared;
525 const elf_file = f.elf_file;525 const elf_file = f.elf_file;
526 try writer.writeAll(" globals\n");526 try writer.writeAll(" globals\n");
src/link/Elf/Symbol.zig+2-2
...@@ -320,7 +320,7 @@ const Format = struct {...@@ -320,7 +320,7 @@ const Format = struct {
320 symbol: Symbol,320 symbol: Symbol,
321 elf_file: *Elf,321 elf_file: *Elf,
322322
323 fn name(f: Format, writer: *std.io.Writer) std.io.Writer.Error!void {323 fn name(f: Format, writer: *std.Io.Writer) std.Io.Writer.Error!void {
324 const elf_file = f.elf_file;324 const elf_file = f.elf_file;
325 const symbol = f.symbol;325 const symbol = f.symbol;
326 try writer.writeAll(symbol.name(elf_file));326 try writer.writeAll(symbol.name(elf_file));
...@@ -335,7 +335,7 @@ const Format = struct {...@@ -335,7 +335,7 @@ const Format = struct {
335 }335 }
336 }336 }
337337
338 fn default(f: Format, writer: *std.io.Writer) std.io.Writer.Error!void {338 fn default(f: Format, writer: *std.Io.Writer) std.Io.Writer.Error!void {
339 const symbol = f.symbol;339 const symbol = f.symbol;
340 const elf_file = f.elf_file;340 const elf_file = f.elf_file;
341 try writer.print("%{d} : {f} : @{x}", .{341 try writer.print("%{d} : {f} : @{x}", .{
src/link/Elf/Thunk.zig+1-1
...@@ -76,7 +76,7 @@ const Format = struct {...@@ -76,7 +76,7 @@ const Format = struct {
76 thunk: Thunk,76 thunk: Thunk,
77 elf_file: *Elf,77 elf_file: *Elf,
7878
79 fn default(f: Format, writer: *std.io.Writer) std.io.Writer.Error!void {79 fn default(f: Format, writer: *std.Io.Writer) std.Io.Writer.Error!void {
80 const thunk = f.thunk;80 const thunk = f.thunk;
81 const elf_file = f.elf_file;81 const elf_file = f.elf_file;
82 try writer.print("@{x} : size({x})\n", .{ thunk.value, thunk.size(elf_file) });82 try writer.print("@{x} : size({x})\n", .{ thunk.value, thunk.size(elf_file) });
src/link/Elf/ZigObject.zig+2-2
...@@ -2201,7 +2201,7 @@ const Format = struct {...@@ -2201,7 +2201,7 @@ const Format = struct {
2201 self: *ZigObject,2201 self: *ZigObject,
2202 elf_file: *Elf,2202 elf_file: *Elf,
22032203
2204 fn symtab(f: Format, writer: *std.io.Writer) std.io.Writer.Error!void {2204 fn symtab(f: Format, writer: *std.Io.Writer) std.Io.Writer.Error!void {
2205 const self = f.self;2205 const self = f.self;
2206 const elf_file = f.elf_file;2206 const elf_file = f.elf_file;
2207 try writer.writeAll(" locals\n");2207 try writer.writeAll(" locals\n");
...@@ -2216,7 +2216,7 @@ const Format = struct {...@@ -2216,7 +2216,7 @@ const Format = struct {
2216 }2216 }
2217 }2217 }
22182218
2219 fn atoms(f: Format, writer: *std.io.Writer) std.io.Writer.Error!void {2219 fn atoms(f: Format, writer: *std.Io.Writer) std.Io.Writer.Error!void {
2220 try writer.writeAll(" atoms\n");2220 try writer.writeAll(" atoms\n");
2221 for (f.self.atoms_indexes.items) |atom_index| {2221 for (f.self.atoms_indexes.items) |atom_index| {
2222 const atom_ptr = f.self.atom(atom_index) orelse continue;2222 const atom_ptr = f.self.atom(atom_index) orelse continue;
src/link/Elf/eh_frame.zig+6-7
...@@ -58,7 +58,7 @@ pub const Fde = struct {...@@ -58,7 +58,7 @@ pub const Fde = struct {
58 fde: Fde,58 fde: Fde,
59 elf_file: *Elf,59 elf_file: *Elf,
6060
61 fn default(f: Format, writer: *std.io.Writer) std.io.Writer.Error!void {61 fn default(f: Format, writer: *std.Io.Writer) std.Io.Writer.Error!void {
62 const fde = f.fde;62 const fde = f.fde;
63 const elf_file = f.elf_file;63 const elf_file = f.elf_file;
64 const base_addr = fde.address(elf_file);64 const base_addr = fde.address(elf_file);
...@@ -141,7 +141,7 @@ pub const Cie = struct {...@@ -141,7 +141,7 @@ pub const Cie = struct {
141 cie: Cie,141 cie: Cie,
142 elf_file: *Elf,142 elf_file: *Elf,
143143
144 fn default(f: Format, writer: *std.io.Writer) std.io.Writer.Error!void {144 fn default(f: Format, writer: *std.Io.Writer) std.Io.Writer.Error!void {
145 const cie = f.cie;145 const cie = f.cie;
146 const elf_file = f.elf_file;146 const elf_file = f.elf_file;
147 const base_addr = cie.address(elf_file);147 const base_addr = cie.address(elf_file);
...@@ -167,15 +167,14 @@ pub const Iterator = struct {...@@ -167,15 +167,14 @@ pub const Iterator = struct {
167 pub fn next(it: *Iterator) !?Record {167 pub fn next(it: *Iterator) !?Record {
168 if (it.pos >= it.data.len) return null;168 if (it.pos >= it.data.len) return null;
169169
170 var stream = std.io.fixedBufferStream(it.data[it.pos..]);170 var reader: std.Io.Reader = .fixed(it.data[it.pos..]);
171 const reader = stream.reader();
172171
173 const size = try reader.readInt(u32, .little);172 const size = try reader.takeInt(u32, .little);
174 if (size == 0) return null;173 if (size == 0) return null;
175 if (size == 0xFFFFFFFF) @panic("TODO");174 if (size == 0xFFFFFFFF) @panic("TODO");
176175
177 const id = try reader.readInt(u32, .little);176 const id = try reader.takeInt(u32, .little);
178 const record = Record{177 const record: Record = .{
179 .tag = if (id == 0) .cie else .fde,178 .tag = if (id == 0) .cie else .fde,
180 .offset = it.pos,179 .offset = it.pos,
181 .size = size,180 .size = size,
src/link/Elf/file.zig+1-1
...@@ -14,7 +14,7 @@ pub const File = union(enum) {...@@ -14,7 +14,7 @@ pub const File = union(enum) {
14 return .{ .data = file };14 return .{ .data = file };
15 }15 }
1616
17 fn formatPath(file: File, writer: *std.io.Writer) std.io.Writer.Error!void {17 fn formatPath(file: File, writer: *std.Io.Writer) std.Io.Writer.Error!void {
18 switch (file) {18 switch (file) {
19 .zig_object => |zo| try writer.writeAll(zo.basename),19 .zig_object => |zo| try writer.writeAll(zo.basename),
20 .linker_defined => try writer.writeAll("(linker defined)"),20 .linker_defined => try writer.writeAll("(linker defined)"),
src/link/Elf/gc.zig+1-1
...@@ -169,7 +169,7 @@ const Level = struct {...@@ -169,7 +169,7 @@ const Level = struct {
169 self.value += 1;169 self.value += 1;
170 }170 }
171171
172 pub fn format(self: *const @This(), w: *std.io.Writer) std.io.Writer.Error!void {172 pub fn format(self: *const @This(), w: *std.Io.Writer) std.Io.Writer.Error!void {
173 try w.splatByteAll(' ', self.value);173 try w.splatByteAll(' ', self.value);
174 }174 }
175};175};
src/link/Elf/relocation.zig+1-1
...@@ -160,7 +160,7 @@ pub fn fmtRelocType(r_type: u32, cpu_arch: std.Target.Cpu.Arch) std.fmt.Formatte...@@ -160,7 +160,7 @@ pub fn fmtRelocType(r_type: u32, cpu_arch: std.Target.Cpu.Arch) std.fmt.Formatte
160 } };160 } };
161}161}
162162
163fn formatRelocType(ctx: FormatRelocTypeCtx, writer: *std.io.Writer) std.io.Writer.Error!void {163fn formatRelocType(ctx: FormatRelocTypeCtx, writer: *std.Io.Writer) std.Io.Writer.Error!void {
164 const r_type = ctx.r_type;164 const r_type = ctx.r_type;
165 switch (ctx.cpu_arch) {165 switch (ctx.cpu_arch) {
166 .x86_64 => try writer.print("R_X86_64_{s}", .{@tagName(@as(elf.R_X86_64, @enumFromInt(r_type)))}),166 .x86_64 => try writer.print("R_X86_64_{s}", .{@tagName(@as(elf.R_X86_64, @enumFromInt(r_type)))}),
src/link/Elf/synthetic_sections.zig+2-2
...@@ -605,7 +605,7 @@ pub const GotSection = struct {...@@ -605,7 +605,7 @@ pub const GotSection = struct {
605 got: GotSection,605 got: GotSection,
606 elf_file: *Elf,606 elf_file: *Elf,
607607
608 pub fn default(f: Format, writer: *std.io.Writer) std.io.Writer.Error!void {608 pub fn default(f: Format, writer: *std.Io.Writer) std.Io.Writer.Error!void {
609 const got = f.got;609 const got = f.got;
610 const elf_file = f.elf_file;610 const elf_file = f.elf_file;
611 try writer.writeAll("GOT\n");611 try writer.writeAll("GOT\n");
...@@ -741,7 +741,7 @@ pub const PltSection = struct {...@@ -741,7 +741,7 @@ pub const PltSection = struct {
741 plt: PltSection,741 plt: PltSection,
742 elf_file: *Elf,742 elf_file: *Elf,
743743
744 pub fn default(f: Format, writer: *std.io.Writer) std.io.Writer.Error!void {744 pub fn default(f: Format, writer: *std.Io.Writer) std.Io.Writer.Error!void {
745 const plt = f.plt;745 const plt = f.plt;
746 const elf_file = f.elf_file;746 const elf_file = f.elf_file;
747 try writer.writeAll("PLT\n");747 try writer.writeAll("PLT\n");
src/link/Lld.zig+4-2
...@@ -1650,7 +1650,8 @@ fn spawnLld(...@@ -1650,7 +1650,8 @@ fn spawnLld(
1650 child.stderr_behavior = .Pipe;1650 child.stderr_behavior = .Pipe;
16511651
1652 child.spawn() catch |err| break :term err;1652 child.spawn() catch |err| break :term err;
1653 stderr = try child.stderr.?.deprecatedReader().readAllAlloc(comp.gpa, std.math.maxInt(usize));1653 var stderr_reader = child.stderr.?.readerStreaming(&.{});
1654 stderr = try stderr_reader.interface.allocRemaining(comp.gpa, .unlimited);
1654 break :term child.wait();1655 break :term child.wait();
1655 }) catch |first_err| term: {1656 }) catch |first_err| term: {
1656 const err = switch (first_err) {1657 const err = switch (first_err) {
...@@ -1699,7 +1700,8 @@ fn spawnLld(...@@ -1699,7 +1700,8 @@ fn spawnLld(
1699 rsp_child.stderr_behavior = .Pipe;1700 rsp_child.stderr_behavior = .Pipe;
17001701
1701 rsp_child.spawn() catch |err| break :err err;1702 rsp_child.spawn() catch |err| break :err err;
1702 stderr = try rsp_child.stderr.?.deprecatedReader().readAllAlloc(comp.gpa, std.math.maxInt(usize));1703 var stderr_reader = rsp_child.stderr.?.readerStreaming(&.{});
1704 stderr = try stderr_reader.interface.allocRemaining(comp.gpa, .unlimited);
1703 break :term rsp_child.wait() catch |err| break :err err;1705 break :term rsp_child.wait() catch |err| break :err err;
1704 }1706 }
1705 },1707 },
src/link/MachO.zig+1-1
...@@ -4361,7 +4361,7 @@ fn inferSdkVersion(comp: *Compilation, sdk_layout: SdkLayout) ?std.SemanticVersi...@@ -4361,7 +4361,7 @@ fn inferSdkVersion(comp: *Compilation, sdk_layout: SdkLayout) ?std.SemanticVersi
4361// The file/property is also available with vendored libc.4361// The file/property is also available with vendored libc.
4362fn readSdkVersionFromSettings(arena: Allocator, dir: []const u8) ![]const u8 {4362fn readSdkVersionFromSettings(arena: Allocator, dir: []const u8) ![]const u8 {
4363 const sdk_path = try fs.path.join(arena, &.{ dir, "SDKSettings.json" });4363 const sdk_path = try fs.path.join(arena, &.{ dir, "SDKSettings.json" });
4364 const contents = try fs.cwd().readFileAlloc(arena, sdk_path, std.math.maxInt(u16));4364 const contents = try fs.cwd().readFileAlloc(sdk_path, arena, .limited(std.math.maxInt(u16)));
4365 const parsed = try std.json.parseFromSlice(std.json.Value, arena, contents, .{});4365 const parsed = try std.json.parseFromSlice(std.json.Value, arena, contents, .{});
4366 if (parsed.value.object.get("MinimalDisplayName")) |ver| return ver.string;4366 if (parsed.value.object.get("MinimalDisplayName")) |ver| return ver.string;
4367 return error.SdkVersionFailure;4367 return error.SdkVersionFailure;
src/link/MachO/CodeSignature.zig+1-3
...@@ -245,9 +245,7 @@ pub fn deinit(self: *CodeSignature, allocator: Allocator) void {...@@ -245,9 +245,7 @@ pub fn deinit(self: *CodeSignature, allocator: Allocator) void {
245}245}
246246
247pub fn addEntitlements(self: *CodeSignature, allocator: Allocator, path: []const u8) !void {247pub fn addEntitlements(self: *CodeSignature, allocator: Allocator, path: []const u8) !void {
248 const file = try fs.cwd().openFile(path, .{});248 const inner = try fs.cwd().readFileAlloc(path, allocator, .limited(std.math.maxInt(u32)));
249 defer file.close();
250 const inner = try file.readToEndAlloc(allocator, std.math.maxInt(u32));
251 self.entitlements = .{ .inner = inner };249 self.entitlements = .{ .inner = inner };
252}250}
253251
src/link/MachO/Dylib.zig+1-1
...@@ -914,7 +914,7 @@ const math = std.math;...@@ -914,7 +914,7 @@ const math = std.math;
914const mem = std.mem;914const mem = std.mem;
915const Allocator = mem.Allocator;915const Allocator = mem.Allocator;
916const Path = std.Build.Cache.Path;916const Path = std.Build.Cache.Path;
917const Writer = std.io.Writer;917const Writer = std.Io.Writer;
918918
919const Dylib = @This();919const Dylib = @This();
920const File = @import("file.zig").File;920const File = @import("file.zig").File;
src/link/MachO/InternalObject.zig+1-1
...@@ -894,7 +894,7 @@ const macho = std.macho;...@@ -894,7 +894,7 @@ const macho = std.macho;
894const mem = std.mem;894const mem = std.mem;
895const std = @import("std");895const std = @import("std");
896const trace = @import("../../tracy.zig").trace;896const trace = @import("../../tracy.zig").trace;
897const Writer = std.io.Writer;897const Writer = std.Io.Writer;
898898
899const Allocator = std.mem.Allocator;899const Allocator = std.mem.Allocator;
900const Atom = @import("Atom.zig");900const Atom = @import("Atom.zig");
src/link/MachO/Object.zig+1-1
...@@ -3094,7 +3094,7 @@ const math = std.math;...@@ -3094,7 +3094,7 @@ const math = std.math;
3094const mem = std.mem;3094const mem = std.mem;
3095const Path = std.Build.Cache.Path;3095const Path = std.Build.Cache.Path;
3096const Allocator = std.mem.Allocator;3096const Allocator = std.mem.Allocator;
3097const Writer = std.io.Writer;3097const Writer = std.Io.Writer;
30983098
3099const eh_frame = @import("eh_frame.zig");3099const eh_frame = @import("eh_frame.zig");
3100const trace = @import("../../tracy.zig").trace;3100const trace = @import("../../tracy.zig").trace;
src/link/MachO/Relocation.zig+1-1
...@@ -162,7 +162,7 @@ const std = @import("std");...@@ -162,7 +162,7 @@ const std = @import("std");
162const assert = std.debug.assert;162const assert = std.debug.assert;
163const macho = std.macho;163const macho = std.macho;
164const math = std.math;164const math = std.math;
165const Writer = std.io.Writer;165const Writer = std.Io.Writer;
166166
167const Atom = @import("Atom.zig");167const Atom = @import("Atom.zig");
168const MachO = @import("../MachO.zig");168const MachO = @import("../MachO.zig");
src/link/MachO/Symbol.zig+1-1
...@@ -417,7 +417,7 @@ pub const Index = u32;...@@ -417,7 +417,7 @@ pub const Index = u32;
417const assert = std.debug.assert;417const assert = std.debug.assert;
418const macho = std.macho;418const macho = std.macho;
419const std = @import("std");419const std = @import("std");
420const Writer = std.io.Writer;420const Writer = std.Io.Writer;
421421
422const Atom = @import("Atom.zig");422const Atom = @import("Atom.zig");
423const File = @import("file.zig").File;423const File = @import("file.zig").File;
src/link/MachO/Thunk.zig+1-1
...@@ -97,7 +97,7 @@ const math = std.math;...@@ -97,7 +97,7 @@ const math = std.math;
97const mem = std.mem;97const mem = std.mem;
98const std = @import("std");98const std = @import("std");
99const trace = @import("../../tracy.zig").trace;99const trace = @import("../../tracy.zig").trace;
100const Writer = std.io.Writer;100const Writer = std.Io.Writer;
101101
102const Allocator = mem.Allocator;102const Allocator = mem.Allocator;
103const Atom = @import("Atom.zig");103const Atom = @import("Atom.zig");
src/link/MachO/ZigObject.zig+1-1
...@@ -1785,7 +1785,7 @@ const mem = std.mem;...@@ -1785,7 +1785,7 @@ const mem = std.mem;
1785const target_util = @import("../../target.zig");1785const target_util = @import("../../target.zig");
1786const trace = @import("../../tracy.zig").trace;1786const trace = @import("../../tracy.zig").trace;
1787const std = @import("std");1787const std = @import("std");
1788const Writer = std.io.Writer;1788const Writer = std.Io.Writer;
17891789
1790const Allocator = std.mem.Allocator;1790const Allocator = std.mem.Allocator;
1791const Archive = @import("Archive.zig");1791const Archive = @import("Archive.zig");
src/link/MachO/dead_strip.zig+1-1
...@@ -212,7 +212,7 @@ const mem = std.mem;...@@ -212,7 +212,7 @@ const mem = std.mem;
212const trace = @import("../../tracy.zig").trace;212const trace = @import("../../tracy.zig").trace;
213const track_live_log = std.log.scoped(.dead_strip_track_live);213const track_live_log = std.log.scoped(.dead_strip_track_live);
214const std = @import("std");214const std = @import("std");
215const Writer = std.io.Writer;215const Writer = std.Io.Writer;
216216
217const Allocator = mem.Allocator;217const Allocator = mem.Allocator;
218const Atom = @import("Atom.zig");218const Atom = @import("Atom.zig");
src/link/MachO/dyld_info/Rebase.zig+1-1
...@@ -656,7 +656,7 @@ const macho = std.macho;...@@ -656,7 +656,7 @@ const macho = std.macho;
656const mem = std.mem;656const mem = std.mem;
657const testing = std.testing;657const testing = std.testing;
658const Allocator = mem.Allocator;658const Allocator = mem.Allocator;
659const Writer = std.io.Writer;659const Writer = std.Io.Writer;
660660
661const trace = @import("../../../tracy.zig").trace;661const trace = @import("../../../tracy.zig").trace;
662const File = @import("../file.zig").File;662const File = @import("../file.zig").File;
src/link/MachO/dyld_info/bind.zig+1-1
...@@ -647,7 +647,7 @@ fn setDylibOrdinal(ordinal: i16, writer: *std.Io.Writer) !void {...@@ -647,7 +647,7 @@ fn setDylibOrdinal(ordinal: i16, writer: *std.Io.Writer) !void {
647fn setAddend(addend: i64, writer: *std.Io.Writer) !void {647fn setAddend(addend: i64, writer: *std.Io.Writer) !void {
648 log.debug(">>> set addend: {x}", .{addend});648 log.debug(">>> set addend: {x}", .{addend});
649 try writer.writeByte(macho.BIND_OPCODE_SET_ADDEND_SLEB);649 try writer.writeByte(macho.BIND_OPCODE_SET_ADDEND_SLEB);
650 try std.leb.writeIleb128(writer, addend);650 try writer.writeSleb128(addend);
651}651}
652652
653fn doBind(writer: *std.Io.Writer) !void {653fn doBind(writer: *std.Io.Writer) !void {
src/link/MachO/eh_frame.zig+4-5
...@@ -248,13 +248,12 @@ pub const Iterator = struct {...@@ -248,13 +248,12 @@ pub const Iterator = struct {
248 pub fn next(it: *Iterator) !?Record {248 pub fn next(it: *Iterator) !?Record {
249 if (it.pos >= it.data.len) return null;249 if (it.pos >= it.data.len) return null;
250250
251 var stream = std.io.fixedBufferStream(it.data[it.pos..]);251 var reader: std.Io.Reader = .fixed(it.data[it.pos..]);
252 const reader = stream.reader();
253252
254 const size = try reader.readInt(u32, .little);253 const size = try reader.takeInt(u32, .little);
255 if (size == 0xFFFFFFFF) @panic("DWARF CFI is 32bit on macOS");254 if (size == 0xFFFFFFFF) @panic("DWARF CFI is 32bit on macOS");
256255
257 const id = try reader.readInt(u32, .little);256 const id = try reader.takeInt(u32, .little);
258 const record = Record{257 const record = Record{
259 .tag = if (id == 0) .cie else .fde,258 .tag = if (id == 0) .cie else .fde,
260 .offset = it.pos,259 .offset = it.pos,
...@@ -502,7 +501,7 @@ const math = std.math;...@@ -502,7 +501,7 @@ const math = std.math;
502const mem = std.mem;501const mem = std.mem;
503const std = @import("std");502const std = @import("std");
504const trace = @import("../../tracy.zig").trace;503const trace = @import("../../tracy.zig").trace;
505const Writer = std.io.Writer;504const Writer = std.Io.Writer;
506505
507const Allocator = std.mem.Allocator;506const Allocator = std.mem.Allocator;
508const Atom = @import("Atom.zig");507const Atom = @import("Atom.zig");
src/link/MachO/file.zig+1-1
...@@ -364,7 +364,7 @@ const log = std.log.scoped(.link);...@@ -364,7 +364,7 @@ const log = std.log.scoped(.link);
364const macho = std.macho;364const macho = std.macho;
365const Allocator = std.mem.Allocator;365const Allocator = std.mem.Allocator;
366const Path = std.Build.Cache.Path;366const Path = std.Build.Cache.Path;
367const Writer = std.io.Writer;367const Writer = std.Io.Writer;
368368
369const trace = @import("../../tracy.zig").trace;369const trace = @import("../../tracy.zig").trace;
370const Archive = @import("Archive.zig");370const Archive = @import("Archive.zig");
src/link/MachO/relocatable.zig+1-1
...@@ -780,7 +780,7 @@ const macho = std.macho;...@@ -780,7 +780,7 @@ const macho = std.macho;
780const math = std.math;780const math = std.math;
781const mem = std.mem;781const mem = std.mem;
782const state_log = std.log.scoped(.link_state);782const state_log = std.log.scoped(.link_state);
783const Writer = std.io.Writer;783const Writer = std.Io.Writer;
784784
785const Archive = @import("Archive.zig");785const Archive = @import("Archive.zig");
786const Atom = @import("Atom.zig");786const Atom = @import("Atom.zig");
src/link/SpirV.zig+1-1
...@@ -249,7 +249,7 @@ pub fn flush(...@@ -249,7 +249,7 @@ pub fn flush(
249 // We need to export the list of error names somewhere so that we can pretty-print them in the249 // We need to export the list of error names somewhere so that we can pretty-print them in the
250 // executor. This is not really an important thing though, so we can just dump it in any old250 // executor. This is not really an important thing though, so we can just dump it in any old
251 // nonsemantic instruction. For now, just put it in OpSourceExtension with a special name.251 // nonsemantic instruction. For now, just put it in OpSourceExtension with a special name.
252 var error_info: std.io.Writer.Allocating = .init(linker.module.gpa);252 var error_info: std.Io.Writer.Allocating = .init(linker.module.gpa);
253 defer error_info.deinit();253 defer error_info.deinit();
254254
255 error_info.writer.writeAll("zig_errors:") catch return error.OutOfMemory;255 error_info.writer.writeAll("zig_errors:") catch return error.OutOfMemory;
src/link/Wasm.zig+2-2
...@@ -2126,7 +2126,7 @@ pub const FunctionType = extern struct {...@@ -2126,7 +2126,7 @@ pub const FunctionType = extern struct {
2126 wasm: *const Wasm,2126 wasm: *const Wasm,
2127 ft: FunctionType,2127 ft: FunctionType,
21282128
2129 pub fn format(self: Formatter, writer: *std.io.Writer) std.io.Writer.Error!void {2129 pub fn format(self: Formatter, writer: *std.Io.Writer) std.Io.Writer.Error!void {
2130 const params = self.ft.params.slice(self.wasm);2130 const params = self.ft.params.slice(self.wasm);
2131 const returns = self.ft.returns.slice(self.wasm);2131 const returns = self.ft.returns.slice(self.wasm);
21322132
...@@ -2905,7 +2905,7 @@ pub const Feature = packed struct(u8) {...@@ -2905,7 +2905,7 @@ pub const Feature = packed struct(u8) {
2905 @"=",2905 @"=",
2906 };2906 };
29072907
2908 pub fn format(feature: Feature, writer: *std.io.Writer) std.io.Writer.Error!void {2908 pub fn format(feature: Feature, writer: *std.Io.Writer) std.Io.Writer.Error!void {
2909 try writer.print("{s} {s}", .{ @tagName(feature.prefix), @tagName(feature.tag) });2909 try writer.print("{s} {s}", .{ @tagName(feature.prefix), @tagName(feature.tag) });
2910 }2910 }
29112911
src/link/Wasm/Object.zig+3-6
...@@ -1460,13 +1460,10 @@ fn parseFeatures(...@@ -1460,13 +1460,10 @@ fn parseFeatures(
1460}1460}
14611461
1462fn readLeb(comptime T: type, bytes: []const u8, pos: usize) struct { T, usize } {1462fn readLeb(comptime T: type, bytes: []const u8, pos: usize) struct { T, usize } {
1463 var fbr = std.io.fixedBufferStream(bytes[pos..]);1463 var reader: std.Io.Reader = .fixed(bytes[pos..]);
1464 return .{1464 return .{
1465 switch (@typeInfo(T).int.signedness) {1465 reader.takeLeb128(T) catch unreachable,
1466 .signed => std.leb.readIleb128(T, fbr.reader()) catch unreachable,1466 pos + reader.seek,
1467 .unsigned => std.leb.readUleb128(T, fbr.reader()) catch unreachable,
1468 },
1469 pos + fbr.pos,
1470 };1467 };
1471}1468}
14721469
src/link/table_section.zig+1-1
...@@ -39,7 +39,7 @@ pub fn TableSection(comptime Entry: type) type {...@@ -39,7 +39,7 @@ pub fn TableSection(comptime Entry: type) type {
39 return self.entries.items.len;39 return self.entries.items.len;
40 }40 }
4141
42 pub fn format(self: Self, writer: *std.io.Writer) std.io.Writer.Error!void {42 pub fn format(self: Self, writer: *std.Io.Writer) std.Io.Writer.Error!void {
43 try writer.writeAll("TableSection:\n");43 try writer.writeAll("TableSection:\n");
44 for (self.entries.items, 0..) |entry, i| {44 for (self.entries.items, 0..) |entry, i| {
45 try writer.print(" {d} => {}\n", .{ i, entry });45 try writer.print(" {d} => {}\n", .{ i, entry });
src/link/tapi/parse.zig+5-5
...@@ -57,7 +57,7 @@ pub const Node = struct {...@@ -57,7 +57,7 @@ pub const Node = struct {
57 }57 }
58 }58 }
5959
60 pub fn format(self: *const Node, writer: *std.io.Writer) std.io.Writer.Error!void {60 pub fn format(self: *const Node, writer: *std.Io.Writer) std.Io.Writer.Error!void {
61 switch (self.tag) {61 switch (self.tag) {
62 inline else => |tag| return @as(*tag.Type(), @fieldParentPtr("base", self)).format(writer),62 inline else => |tag| return @as(*tag.Type(), @fieldParentPtr("base", self)).format(writer),
63 }63 }
...@@ -81,7 +81,7 @@ pub const Node = struct {...@@ -81,7 +81,7 @@ pub const Node = struct {
81 }81 }
82 }82 }
8383
84 pub fn format(self: *const Doc, writer: *std.io.Writer) std.io.Writer.Error!void {84 pub fn format(self: *const Doc, writer: *std.Io.Writer) std.Io.Writer.Error!void {
85 if (self.directive) |id| {85 if (self.directive) |id| {
86 try writer.print("{{ ", .{});86 try writer.print("{{ ", .{});
87 const directive = self.base.tree.getRaw(id, id);87 const directive = self.base.tree.getRaw(id, id);
...@@ -121,7 +121,7 @@ pub const Node = struct {...@@ -121,7 +121,7 @@ pub const Node = struct {
121 self.values.deinit(allocator);121 self.values.deinit(allocator);
122 }122 }
123123
124 pub fn format(self: *const Map, writer: *std.io.Writer) std.io.Writer.Error!void {124 pub fn format(self: *const Map, writer: *std.Io.Writer) std.Io.Writer.Error!void {
125 try std.fmt.format(writer, "{{ ", .{});125 try std.fmt.format(writer, "{{ ", .{});
126 for (self.values.items) |entry| {126 for (self.values.items) |entry| {
127 const key = self.base.tree.getRaw(entry.key, entry.key);127 const key = self.base.tree.getRaw(entry.key, entry.key);
...@@ -153,7 +153,7 @@ pub const Node = struct {...@@ -153,7 +153,7 @@ pub const Node = struct {
153 self.values.deinit(allocator);153 self.values.deinit(allocator);
154 }154 }
155155
156 pub fn format(self: *const List, writer: *std.io.Writer) std.io.Writer.Error!void {156 pub fn format(self: *const List, writer: *std.Io.Writer) std.Io.Writer.Error!void {
157 try std.fmt.format(writer, "[ ", .{});157 try std.fmt.format(writer, "[ ", .{});
158 for (self.values.items) |node| {158 for (self.values.items) |node| {
159 try std.fmt.format(writer, "{}, ", .{node});159 try std.fmt.format(writer, "{}, ", .{node});
...@@ -177,7 +177,7 @@ pub const Node = struct {...@@ -177,7 +177,7 @@ pub const Node = struct {
177 self.string_value.deinit(allocator);177 self.string_value.deinit(allocator);
178 }178 }
179179
180 pub fn format(self: *const Value, writer: *std.io.Writer) std.io.Writer.Error!void {180 pub fn format(self: *const Value, writer: *std.Io.Writer) std.Io.Writer.Error!void {
181 const raw = self.base.tree.getRaw(self.base.start, self.base.end);181 const raw = self.base.tree.getRaw(self.base.start, self.base.end);
182 return std.fmt.format(writer, "{s}", .{raw});182 return std.fmt.format(writer, "{s}", .{raw});
183 }183 }
src/main.zig+7-8
...@@ -1,7 +1,6 @@...@@ -1,7 +1,6 @@
1const std = @import("std");1const std = @import("std");
2const builtin = @import("builtin");2const builtin = @import("builtin");
3const assert = std.debug.assert;3const assert = std.debug.assert;
4const io = std.io;
5const fs = std.fs;4const fs = std.fs;
6const mem = std.mem;5const mem = std.mem;
7const process = std.process;6const process = std.process;
...@@ -5444,7 +5443,7 @@ fn cmdBuild(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {...@@ -5444,7 +5443,7 @@ fn cmdBuild(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
5444 // that are missing.5443 // that are missing.
5445 const s = fs.path.sep_str;5444 const s = fs.path.sep_str;
5446 const tmp_sub_path = "tmp" ++ s ++ results_tmp_file_nonce;5445 const tmp_sub_path = "tmp" ++ s ++ results_tmp_file_nonce;
5447 const stdout = dirs.local_cache.handle.readFileAlloc(arena, tmp_sub_path, 50 * 1024 * 1024) catch |err| {5446 const stdout = dirs.local_cache.handle.readFileAlloc(tmp_sub_path, arena, .limited(50 * 1024 * 1024)) catch |err| {
5448 fatal("unable to read results of configure phase from '{f}{s}': {s}", .{5447 fatal("unable to read results of configure phase from '{f}{s}': {s}", .{
5449 dirs.local_cache, tmp_sub_path, @errorName(err),5448 dirs.local_cache, tmp_sub_path, @errorName(err),
5450 });5449 });
...@@ -5694,7 +5693,8 @@ fn jitCmd(...@@ -5694,7 +5693,8 @@ fn jitCmd(
5694 try child.spawn();5693 try child.spawn();
56955694
5696 if (options.capture) |ptr| {5695 if (options.capture) |ptr| {
5697 ptr.* = try child.stdout.?.readToEndAlloc(arena, std.math.maxInt(u32));5696 var stdout_reader = child.stdout.?.readerStreaming(&.{});
5697 ptr.* = try stdout_reader.interface.allocRemaining(arena, .limited(std.math.maxInt(u32)));
5698 }5698 }
56995699
5700 const term = try child.wait();5700 const term = try child.wait();
...@@ -5827,7 +5827,7 @@ const ArgIteratorResponseFile = process.ArgIteratorGeneral(.{ .comments = true,...@@ -5827,7 +5827,7 @@ const ArgIteratorResponseFile = process.ArgIteratorGeneral(.{ .comments = true,
5827/// Initialize the arguments from a Response File. "*.rsp"5827/// Initialize the arguments from a Response File. "*.rsp"
5828fn initArgIteratorResponseFile(allocator: Allocator, resp_file_path: []const u8) !ArgIteratorResponseFile {5828fn initArgIteratorResponseFile(allocator: Allocator, resp_file_path: []const u8) !ArgIteratorResponseFile {
5829 const max_bytes = 10 * 1024 * 1024; // 10 MiB of command line arguments is a reasonable limit5829 const max_bytes = 10 * 1024 * 1024; // 10 MiB of command line arguments is a reasonable limit
5830 const cmd_line = try fs.cwd().readFileAlloc(allocator, resp_file_path, max_bytes);5830 const cmd_line = try fs.cwd().readFileAlloc(resp_file_path, allocator, .limited(max_bytes));
5831 errdefer allocator.free(cmd_line);5831 errdefer allocator.free(cmd_line);
58325832
5833 return ArgIteratorResponseFile.initTakeOwnership(allocator, cmd_line);5833 return ArgIteratorResponseFile.initTakeOwnership(allocator, cmd_line);
...@@ -7351,10 +7351,9 @@ fn loadManifest(...@@ -7351,10 +7351,9 @@ fn loadManifest(
7351) !struct { Package.Manifest, Ast } {7351) !struct { Package.Manifest, Ast } {
7352 const manifest_bytes = while (true) {7352 const manifest_bytes = while (true) {
7353 break options.dir.readFileAllocOptions(7353 break options.dir.readFileAllocOptions(
7354 arena,
7355 Package.Manifest.basename,7354 Package.Manifest.basename,
7356 Package.Manifest.max_bytes,7355 arena,
7357 null,7356 .limited(Package.Manifest.max_bytes),
7358 .@"1",7357 .@"1",
7359 0,7358 0,
7360 ) catch |err| switch (err) {7359 ) catch |err| switch (err) {
...@@ -7436,7 +7435,7 @@ const Templates = struct {...@@ -7436,7 +7435,7 @@ const Templates = struct {
7436 }7435 }
74377436
7438 const max_bytes = 10 * 1024 * 1024;7437 const max_bytes = 10 * 1024 * 1024;
7439 const contents = templates.dir.readFileAlloc(arena, template_path, max_bytes) catch |err| {7438 const contents = templates.dir.readFileAlloc(template_path, arena, .limited(max_bytes)) catch |err| {
7440 fatal("unable to read template file '{s}': {s}", .{ template_path, @errorName(err) });7439 fatal("unable to read template file '{s}': {s}", .{ template_path, @errorName(err) });
7441 };7440 };
7442 templates.buffer.clearRetainingCapacity();7441 templates.buffer.clearRetainingCapacity();
src/print_targets.zig+2-3
...@@ -1,6 +1,5 @@...@@ -1,6 +1,5 @@
1const std = @import("std");1const std = @import("std");
2const fs = std.fs;2const fs = std.fs;
3const io = std.io;
4const mem = std.mem;3const mem = std.mem;
5const meta = std.meta;4const meta = std.meta;
6const fatal = std.process.fatal;5const fatal = std.process.fatal;
...@@ -25,9 +24,9 @@ pub fn cmdTargets(...@@ -25,9 +24,9 @@ pub fn cmdTargets(
25 defer allocator.free(zig_lib_directory.path.?);24 defer allocator.free(zig_lib_directory.path.?);
2625
27 const abilists_contents = zig_lib_directory.handle.readFileAlloc(26 const abilists_contents = zig_lib_directory.handle.readFileAlloc(
28 allocator,
29 glibc.abilists_path,27 glibc.abilists_path,
30 glibc.abilists_max_size,28 allocator,
29 .limited(glibc.abilists_max_size),
31 ) catch |err| switch (err) {30 ) catch |err| switch (err) {
32 error.OutOfMemory => return error.OutOfMemory,31 error.OutOfMemory => return error.OutOfMemory,
33 else => fatal("unable to read " ++ glibc.abilists_path ++ ": {s}", .{@errorName(err)}),32 else => fatal("unable to read " ++ glibc.abilists_path ++ ": {s}", .{@errorName(err)}),
src/print_value.zig+10-9
...@@ -9,6 +9,7 @@ const Sema = @import("Sema.zig");...@@ -9,6 +9,7 @@ const Sema = @import("Sema.zig");
9const InternPool = @import("InternPool.zig");9const InternPool = @import("InternPool.zig");
10const Allocator = std.mem.Allocator;10const Allocator = std.mem.Allocator;
11const Target = std.Target;11const Target = std.Target;
12const Writer = std.Io.Writer;
1213
13const max_aggregate_items = 100;14const max_aggregate_items = 100;
14const max_string_len = 256;15const max_string_len = 256;
...@@ -20,7 +21,7 @@ pub const FormatContext = struct {...@@ -20,7 +21,7 @@ pub const FormatContext = struct {
20 depth: u8,21 depth: u8,
21};22};
2223
23pub fn formatSema(ctx: FormatContext, writer: *std.io.Writer) std.io.Writer.Error!void {24pub fn formatSema(ctx: FormatContext, writer: *Writer) Writer.Error!void {
24 const sema = ctx.opt_sema.?;25 const sema = ctx.opt_sema.?;
25 return print(ctx.val, writer, ctx.depth, ctx.pt, sema) catch |err| switch (err) {26 return print(ctx.val, writer, ctx.depth, ctx.pt, sema) catch |err| switch (err) {
26 error.OutOfMemory => @panic("OOM"), // We're not allowed to return this from a format function27 error.OutOfMemory => @panic("OOM"), // We're not allowed to return this from a format function
...@@ -30,7 +31,7 @@ pub fn formatSema(ctx: FormatContext, writer: *std.io.Writer) std.io.Writer.Erro...@@ -30,7 +31,7 @@ pub fn formatSema(ctx: FormatContext, writer: *std.io.Writer) std.io.Writer.Erro
30 };31 };
31}32}
3233
33pub fn format(ctx: FormatContext, writer: *std.io.Writer) std.io.Writer.Error!void {34pub fn format(ctx: FormatContext, writer: *Writer) Writer.Error!void {
34 std.debug.assert(ctx.opt_sema == null);35 std.debug.assert(ctx.opt_sema == null);
35 return print(ctx.val, writer, ctx.depth, ctx.pt, null) catch |err| switch (err) {36 return print(ctx.val, writer, ctx.depth, ctx.pt, null) catch |err| switch (err) {
36 error.OutOfMemory => @panic("OOM"), // We're not allowed to return this from a format function37 error.OutOfMemory => @panic("OOM"), // We're not allowed to return this from a format function
...@@ -41,11 +42,11 @@ pub fn format(ctx: FormatContext, writer: *std.io.Writer) std.io.Writer.Error!vo...@@ -41,11 +42,11 @@ pub fn format(ctx: FormatContext, writer: *std.io.Writer) std.io.Writer.Error!vo
4142
42pub fn print(43pub fn print(
43 val: Value,44 val: Value,
44 writer: *std.io.Writer,45 writer: *Writer,
45 level: u8,46 level: u8,
46 pt: Zcu.PerThread,47 pt: Zcu.PerThread,
47 opt_sema: ?*Sema,48 opt_sema: ?*Sema,
48) (std.io.Writer.Error || Zcu.CompileError)!void {49) (Writer.Error || Zcu.CompileError)!void {
49 const zcu = pt.zcu;50 const zcu = pt.zcu;
50 const ip = &zcu.intern_pool;51 const ip = &zcu.intern_pool;
51 switch (ip.indexToKey(val.toIntern())) {52 switch (ip.indexToKey(val.toIntern())) {
...@@ -184,11 +185,11 @@ fn printAggregate(...@@ -184,11 +185,11 @@ fn printAggregate(
184 val: Value,185 val: Value,
185 aggregate: InternPool.Key.Aggregate,186 aggregate: InternPool.Key.Aggregate,
186 is_ref: bool,187 is_ref: bool,
187 writer: *std.io.Writer,188 writer: *Writer,
188 level: u8,189 level: u8,
189 pt: Zcu.PerThread,190 pt: Zcu.PerThread,
190 opt_sema: ?*Sema,191 opt_sema: ?*Sema,
191) (std.io.Writer.Error || Zcu.CompileError)!void {192) (Writer.Error || Zcu.CompileError)!void {
192 if (level == 0) {193 if (level == 0) {
193 if (is_ref) try writer.writeByte('&');194 if (is_ref) try writer.writeByte('&');
194 return writer.writeAll(".{ ... }");195 return writer.writeAll(".{ ... }");
...@@ -270,11 +271,11 @@ fn printPtr(...@@ -270,11 +271,11 @@ fn printPtr(
270 ptr_val: Value,271 ptr_val: Value,
271 /// Whether to print `derivation` as an lvalue or rvalue. If `null`, the more concise option is chosen.272 /// Whether to print `derivation` as an lvalue or rvalue. If `null`, the more concise option is chosen.
272 want_kind: ?PrintPtrKind,273 want_kind: ?PrintPtrKind,
273 writer: *std.io.Writer,274 writer: *Writer,
274 level: u8,275 level: u8,
275 pt: Zcu.PerThread,276 pt: Zcu.PerThread,
276 opt_sema: ?*Sema,277 opt_sema: ?*Sema,
277) (std.io.Writer.Error || Zcu.CompileError)!void {278) (Writer.Error || Zcu.CompileError)!void {
278 const ptr = switch (pt.zcu.intern_pool.indexToKey(ptr_val.toIntern())) {279 const ptr = switch (pt.zcu.intern_pool.indexToKey(ptr_val.toIntern())) {
279 .undef => return writer.writeAll("undefined"),280 .undef => return writer.writeAll("undefined"),
280 .ptr => |ptr| ptr,281 .ptr => |ptr| ptr,
...@@ -316,7 +317,7 @@ const PrintPtrKind = enum { lvalue, rvalue };...@@ -316,7 +317,7 @@ const PrintPtrKind = enum { lvalue, rvalue };
316/// Returns the root derivation, which may be ignored.317/// Returns the root derivation, which may be ignored.
317pub fn printPtrDerivation(318pub fn printPtrDerivation(
318 derivation: Value.PointerDeriveStep,319 derivation: Value.PointerDeriveStep,
319 writer: *std.io.Writer,320 writer: *Writer,
320 pt: Zcu.PerThread,321 pt: Zcu.PerThread,
321 /// Whether to print `derivation` as an lvalue or rvalue. If `null`, the more concise option is chosen.322 /// Whether to print `derivation` as an lvalue or rvalue. If `null`, the more concise option is chosen.
322 /// If this is `.rvalue`, the result may look like `&foo`, so it's not necessarily valid to treat it as323 /// If this is `.rvalue`, the result may look like `&foo`, so it's not necessarily valid to treat it as
src/print_zir.zig+106-106
...@@ -10,7 +10,7 @@ const Zcu = @import("Zcu.zig");...@@ -10,7 +10,7 @@ const Zcu = @import("Zcu.zig");
10const LazySrcLoc = Zcu.LazySrcLoc;10const LazySrcLoc = Zcu.LazySrcLoc;
1111
12/// Write human-readable, debug formatted ZIR code.12/// Write human-readable, debug formatted ZIR code.
13pub fn renderAsText(gpa: Allocator, tree: ?Ast, zir: Zir, bw: *std.io.Writer) !void {13pub fn renderAsText(gpa: Allocator, tree: ?Ast, zir: Zir, bw: *std.Io.Writer) !void {
14 var arena = std.heap.ArenaAllocator.init(gpa);14 var arena = std.heap.ArenaAllocator.init(gpa);
15 defer arena.deinit();15 defer arena.deinit();
1616
...@@ -57,7 +57,7 @@ pub fn renderInstructionContext(...@@ -57,7 +57,7 @@ pub fn renderInstructionContext(
57 scope_file: *Zcu.File,57 scope_file: *Zcu.File,
58 parent_decl_node: Ast.Node.Index,58 parent_decl_node: Ast.Node.Index,
59 indent: u32,59 indent: u32,
60 bw: *std.io.Writer,60 bw: *std.Io.Writer,
61) !void {61) !void {
62 var arena = std.heap.ArenaAllocator.init(gpa);62 var arena = std.heap.ArenaAllocator.init(gpa);
63 defer arena.deinit();63 defer arena.deinit();
...@@ -89,7 +89,7 @@ pub fn renderSingleInstruction(...@@ -89,7 +89,7 @@ pub fn renderSingleInstruction(
89 scope_file: *Zcu.File,89 scope_file: *Zcu.File,
90 parent_decl_node: Ast.Node.Index,90 parent_decl_node: Ast.Node.Index,
91 indent: u32,91 indent: u32,
92 bw: *std.io.Writer,92 bw: *std.Io.Writer,
93) !void {93) !void {
94 var arena = std.heap.ArenaAllocator.init(gpa);94 var arena = std.heap.ArenaAllocator.init(gpa);
95 defer arena.deinit();95 defer arena.deinit();
...@@ -176,11 +176,11 @@ const Writer = struct {...@@ -176,11 +176,11 @@ const Writer = struct {
176 }176 }
177 } = .{},177 } = .{},
178178
179 const Error = std.io.Writer.Error || Allocator.Error;179 const Error = std.Io.Writer.Error || Allocator.Error;
180180
181 fn writeInstToStream(181 fn writeInstToStream(
182 self: *Writer,182 self: *Writer,
183 stream: *std.io.Writer,183 stream: *std.Io.Writer,
184 inst: Zir.Inst.Index,184 inst: Zir.Inst.Index,
185 ) Error!void {185 ) Error!void {
186 const tags = self.code.instructions.items(.tag);186 const tags = self.code.instructions.items(.tag);
...@@ -508,7 +508,7 @@ const Writer = struct {...@@ -508,7 +508,7 @@ const Writer = struct {
508 }508 }
509 }509 }
510510
511 fn writeExtended(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {511 fn writeExtended(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
512 const extended = self.code.instructions.items(.data)[@intFromEnum(inst)].extended;512 const extended = self.code.instructions.items(.data)[@intFromEnum(inst)].extended;
513 try stream.print("{s}(", .{@tagName(extended.opcode)});513 try stream.print("{s}(", .{@tagName(extended.opcode)});
514 switch (extended.opcode) {514 switch (extended.opcode) {
...@@ -616,13 +616,13 @@ const Writer = struct {...@@ -616,13 +616,13 @@ const Writer = struct {
616 }616 }
617 }617 }
618618
619 fn writeExtNode(self: *Writer, stream: *std.io.Writer, extended: Zir.Inst.Extended.InstData) !void {619 fn writeExtNode(self: *Writer, stream: *std.Io.Writer, extended: Zir.Inst.Extended.InstData) !void {
620 try stream.writeAll(")) ");620 try stream.writeAll(")) ");
621 const src_node: Ast.Node.Offset = @enumFromInt(@as(i32, @bitCast(extended.operand)));621 const src_node: Ast.Node.Offset = @enumFromInt(@as(i32, @bitCast(extended.operand)));
622 try self.writeSrcNode(stream, src_node);622 try self.writeSrcNode(stream, src_node);
623 }623 }
624624
625 fn writeArrayInitElemType(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {625 fn writeArrayInitElemType(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
626 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].bin;626 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].bin;
627 try self.writeInstRef(stream, inst_data.lhs);627 try self.writeInstRef(stream, inst_data.lhs);
628 try stream.print(", {d})", .{@intFromEnum(inst_data.rhs)});628 try stream.print(", {d})", .{@intFromEnum(inst_data.rhs)});
...@@ -630,7 +630,7 @@ const Writer = struct {...@@ -630,7 +630,7 @@ const Writer = struct {
630630
631 fn writeUnNode(631 fn writeUnNode(
632 self: *Writer,632 self: *Writer,
633 stream: *std.io.Writer,633 stream: *std.Io.Writer,
634 inst: Zir.Inst.Index,634 inst: Zir.Inst.Index,
635 ) Error!void {635 ) Error!void {
636 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].un_node;636 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
...@@ -641,7 +641,7 @@ const Writer = struct {...@@ -641,7 +641,7 @@ const Writer = struct {
641641
642 fn writeUnTok(642 fn writeUnTok(
643 self: *Writer,643 self: *Writer,
644 stream: *std.io.Writer,644 stream: *std.Io.Writer,
645 inst: Zir.Inst.Index,645 inst: Zir.Inst.Index,
646 ) Error!void {646 ) Error!void {
647 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].un_tok;647 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].un_tok;
...@@ -652,7 +652,7 @@ const Writer = struct {...@@ -652,7 +652,7 @@ const Writer = struct {
652652
653 fn writeValidateDestructure(653 fn writeValidateDestructure(
654 self: *Writer,654 self: *Writer,
655 stream: *std.io.Writer,655 stream: *std.Io.Writer,
656 inst: Zir.Inst.Index,656 inst: Zir.Inst.Index,
657 ) Error!void {657 ) Error!void {
658 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;658 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
...@@ -666,7 +666,7 @@ const Writer = struct {...@@ -666,7 +666,7 @@ const Writer = struct {
666666
667 fn writeValidateArrayInitTy(667 fn writeValidateArrayInitTy(
668 self: *Writer,668 self: *Writer,
669 stream: *std.io.Writer,669 stream: *std.Io.Writer,
670 inst: Zir.Inst.Index,670 inst: Zir.Inst.Index,
671 ) Error!void {671 ) Error!void {
672 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;672 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
...@@ -678,7 +678,7 @@ const Writer = struct {...@@ -678,7 +678,7 @@ const Writer = struct {
678678
679 fn writeArrayTypeSentinel(679 fn writeArrayTypeSentinel(
680 self: *Writer,680 self: *Writer,
681 stream: *std.io.Writer,681 stream: *std.Io.Writer,
682 inst: Zir.Inst.Index,682 inst: Zir.Inst.Index,
683 ) Error!void {683 ) Error!void {
684 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;684 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
...@@ -694,7 +694,7 @@ const Writer = struct {...@@ -694,7 +694,7 @@ const Writer = struct {
694694
695 fn writePtrType(695 fn writePtrType(
696 self: *Writer,696 self: *Writer,
697 stream: *std.io.Writer,697 stream: *std.Io.Writer,
698 inst: Zir.Inst.Index,698 inst: Zir.Inst.Index,
699 ) Error!void {699 ) Error!void {
700 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].ptr_type;700 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].ptr_type;
...@@ -737,12 +737,12 @@ const Writer = struct {...@@ -737,12 +737,12 @@ const Writer = struct {
737 try self.writeSrcNode(stream, extra.data.src_node);737 try self.writeSrcNode(stream, extra.data.src_node);
738 }738 }
739739
740 fn writeInt(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {740 fn writeInt(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
741 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].int;741 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].int;
742 try stream.print("{d})", .{inst_data});742 try stream.print("{d})", .{inst_data});
743 }743 }
744744
745 fn writeIntBig(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {745 fn writeIntBig(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
746 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].str;746 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].str;
747 const byte_count = inst_data.len * @sizeOf(std.math.big.Limb);747 const byte_count = inst_data.len * @sizeOf(std.math.big.Limb);
748 const limb_bytes = self.code.string_bytes[@intFromEnum(inst_data.start)..][0..byte_count];748 const limb_bytes = self.code.string_bytes[@intFromEnum(inst_data.start)..][0..byte_count];
...@@ -761,12 +761,12 @@ const Writer = struct {...@@ -761,12 +761,12 @@ const Writer = struct {
761 try stream.print("{s})", .{as_string});761 try stream.print("{s})", .{as_string});
762 }762 }
763763
764 fn writeFloat(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {764 fn writeFloat(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
765 const number = self.code.instructions.items(.data)[@intFromEnum(inst)].float;765 const number = self.code.instructions.items(.data)[@intFromEnum(inst)].float;
766 try stream.print("{d})", .{number});766 try stream.print("{d})", .{number});
767 }767 }
768768
769 fn writeFloat128(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {769 fn writeFloat128(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
770 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;770 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
771 const extra = self.code.extraData(Zir.Inst.Float128, inst_data.payload_index).data;771 const extra = self.code.extraData(Zir.Inst.Float128, inst_data.payload_index).data;
772 const number = extra.get();772 const number = extra.get();
...@@ -777,7 +777,7 @@ const Writer = struct {...@@ -777,7 +777,7 @@ const Writer = struct {
777777
778 fn writeStr(778 fn writeStr(
779 self: *Writer,779 self: *Writer,
780 stream: *std.io.Writer,780 stream: *std.Io.Writer,
781 inst: Zir.Inst.Index,781 inst: Zir.Inst.Index,
782 ) Error!void {782 ) Error!void {
783 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].str;783 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].str;
...@@ -785,7 +785,7 @@ const Writer = struct {...@@ -785,7 +785,7 @@ const Writer = struct {
785 try stream.print("\"{f}\")", .{std.zig.fmtString(str)});785 try stream.print("\"{f}\")", .{std.zig.fmtString(str)});
786 }786 }
787787
788 fn writeSliceStart(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {788 fn writeSliceStart(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
789 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;789 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
790 const extra = self.code.extraData(Zir.Inst.SliceStart, inst_data.payload_index).data;790 const extra = self.code.extraData(Zir.Inst.SliceStart, inst_data.payload_index).data;
791 try self.writeInstRef(stream, extra.lhs);791 try self.writeInstRef(stream, extra.lhs);
...@@ -795,7 +795,7 @@ const Writer = struct {...@@ -795,7 +795,7 @@ const Writer = struct {
795 try self.writeSrcNode(stream, inst_data.src_node);795 try self.writeSrcNode(stream, inst_data.src_node);
796 }796 }
797797
798 fn writeSliceEnd(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {798 fn writeSliceEnd(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
799 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;799 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
800 const extra = self.code.extraData(Zir.Inst.SliceEnd, inst_data.payload_index).data;800 const extra = self.code.extraData(Zir.Inst.SliceEnd, inst_data.payload_index).data;
801 try self.writeInstRef(stream, extra.lhs);801 try self.writeInstRef(stream, extra.lhs);
...@@ -807,7 +807,7 @@ const Writer = struct {...@@ -807,7 +807,7 @@ const Writer = struct {
807 try self.writeSrcNode(stream, inst_data.src_node);807 try self.writeSrcNode(stream, inst_data.src_node);
808 }808 }
809809
810 fn writeSliceSentinel(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {810 fn writeSliceSentinel(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
811 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;811 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
812 const extra = self.code.extraData(Zir.Inst.SliceSentinel, inst_data.payload_index).data;812 const extra = self.code.extraData(Zir.Inst.SliceSentinel, inst_data.payload_index).data;
813 try self.writeInstRef(stream, extra.lhs);813 try self.writeInstRef(stream, extra.lhs);
...@@ -821,7 +821,7 @@ const Writer = struct {...@@ -821,7 +821,7 @@ const Writer = struct {
821 try self.writeSrcNode(stream, inst_data.src_node);821 try self.writeSrcNode(stream, inst_data.src_node);
822 }822 }
823823
824 fn writeSliceLength(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {824 fn writeSliceLength(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
825 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;825 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
826 const extra = self.code.extraData(Zir.Inst.SliceLength, inst_data.payload_index).data;826 const extra = self.code.extraData(Zir.Inst.SliceLength, inst_data.payload_index).data;
827 try self.writeInstRef(stream, extra.lhs);827 try self.writeInstRef(stream, extra.lhs);
...@@ -837,7 +837,7 @@ const Writer = struct {...@@ -837,7 +837,7 @@ const Writer = struct {
837 try self.writeSrcNode(stream, inst_data.src_node);837 try self.writeSrcNode(stream, inst_data.src_node);
838 }838 }
839839
840 fn writeUnionInit(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {840 fn writeUnionInit(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
841 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;841 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
842 const extra = self.code.extraData(Zir.Inst.UnionInit, inst_data.payload_index).data;842 const extra = self.code.extraData(Zir.Inst.UnionInit, inst_data.payload_index).data;
843 try self.writeInstRef(stream, extra.union_type);843 try self.writeInstRef(stream, extra.union_type);
...@@ -849,7 +849,7 @@ const Writer = struct {...@@ -849,7 +849,7 @@ const Writer = struct {
849 try self.writeSrcNode(stream, inst_data.src_node);849 try self.writeSrcNode(stream, inst_data.src_node);
850 }850 }
851851
852 fn writeShuffle(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {852 fn writeShuffle(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
853 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;853 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
854 const extra = self.code.extraData(Zir.Inst.Shuffle, inst_data.payload_index).data;854 const extra = self.code.extraData(Zir.Inst.Shuffle, inst_data.payload_index).data;
855 try self.writeInstRef(stream, extra.elem_type);855 try self.writeInstRef(stream, extra.elem_type);
...@@ -863,7 +863,7 @@ const Writer = struct {...@@ -863,7 +863,7 @@ const Writer = struct {
863 try self.writeSrcNode(stream, inst_data.src_node);863 try self.writeSrcNode(stream, inst_data.src_node);
864 }864 }
865865
866 fn writeSelect(self: *Writer, stream: *std.io.Writer, extended: Zir.Inst.Extended.InstData) !void {866 fn writeSelect(self: *Writer, stream: *std.Io.Writer, extended: Zir.Inst.Extended.InstData) !void {
867 const extra = self.code.extraData(Zir.Inst.Select, extended.operand).data;867 const extra = self.code.extraData(Zir.Inst.Select, extended.operand).data;
868 try self.writeInstRef(stream, extra.elem_type);868 try self.writeInstRef(stream, extra.elem_type);
869 try stream.writeAll(", ");869 try stream.writeAll(", ");
...@@ -876,7 +876,7 @@ const Writer = struct {...@@ -876,7 +876,7 @@ const Writer = struct {
876 try self.writeSrcNode(stream, extra.node);876 try self.writeSrcNode(stream, extra.node);
877 }877 }
878878
879 fn writeMulAdd(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {879 fn writeMulAdd(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
880 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;880 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
881 const extra = self.code.extraData(Zir.Inst.MulAdd, inst_data.payload_index).data;881 const extra = self.code.extraData(Zir.Inst.MulAdd, inst_data.payload_index).data;
882 try self.writeInstRef(stream, extra.mulend1);882 try self.writeInstRef(stream, extra.mulend1);
...@@ -888,7 +888,7 @@ const Writer = struct {...@@ -888,7 +888,7 @@ const Writer = struct {
888 try self.writeSrcNode(stream, inst_data.src_node);888 try self.writeSrcNode(stream, inst_data.src_node);
889 }889 }
890890
891 fn writeBuiltinCall(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {891 fn writeBuiltinCall(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
892 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;892 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
893 const extra = self.code.extraData(Zir.Inst.BuiltinCall, inst_data.payload_index).data;893 const extra = self.code.extraData(Zir.Inst.BuiltinCall, inst_data.payload_index).data;
894894
...@@ -904,7 +904,7 @@ const Writer = struct {...@@ -904,7 +904,7 @@ const Writer = struct {
904 try self.writeSrcNode(stream, inst_data.src_node);904 try self.writeSrcNode(stream, inst_data.src_node);
905 }905 }
906906
907 fn writeFieldParentPtr(self: *Writer, stream: *std.io.Writer, extended: Zir.Inst.Extended.InstData) !void {907 fn writeFieldParentPtr(self: *Writer, stream: *std.Io.Writer, extended: Zir.Inst.Extended.InstData) !void {
908 const extra = self.code.extraData(Zir.Inst.FieldParentPtr, extended.operand).data;908 const extra = self.code.extraData(Zir.Inst.FieldParentPtr, extended.operand).data;
909 const FlagsInt = @typeInfo(Zir.Inst.FullPtrCastFlags).@"struct".backing_integer.?;909 const FlagsInt = @typeInfo(Zir.Inst.FullPtrCastFlags).@"struct".backing_integer.?;
910 const flags: Zir.Inst.FullPtrCastFlags = @bitCast(@as(FlagsInt, @truncate(extended.small)));910 const flags: Zir.Inst.FullPtrCastFlags = @bitCast(@as(FlagsInt, @truncate(extended.small)));
...@@ -921,7 +921,7 @@ const Writer = struct {...@@ -921,7 +921,7 @@ const Writer = struct {
921 try self.writeSrcNode(stream, extra.src_node);921 try self.writeSrcNode(stream, extra.src_node);
922 }922 }
923923
924 fn writeParam(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {924 fn writeParam(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
925 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_tok;925 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_tok;
926 const extra = self.code.extraData(Zir.Inst.Param, inst_data.payload_index);926 const extra = self.code.extraData(Zir.Inst.Param, inst_data.payload_index);
927 const body = self.code.bodySlice(extra.end, extra.data.type.body_len);927 const body = self.code.bodySlice(extra.end, extra.data.type.body_len);
...@@ -936,7 +936,7 @@ const Writer = struct {...@@ -936,7 +936,7 @@ const Writer = struct {
936 try self.writeSrcTok(stream, inst_data.src_tok);936 try self.writeSrcTok(stream, inst_data.src_tok);
937 }937 }
938938
939 fn writePlNodeBin(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {939 fn writePlNodeBin(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
940 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;940 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
941 const extra = self.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;941 const extra = self.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
942 try self.writeInstRef(stream, extra.lhs);942 try self.writeInstRef(stream, extra.lhs);
...@@ -946,7 +946,7 @@ const Writer = struct {...@@ -946,7 +946,7 @@ const Writer = struct {
946 try self.writeSrcNode(stream, inst_data.src_node);946 try self.writeSrcNode(stream, inst_data.src_node);
947 }947 }
948948
949 fn writePlNodeMultiOp(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {949 fn writePlNodeMultiOp(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
950 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;950 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
951 const extra = self.code.extraData(Zir.Inst.MultiOp, inst_data.payload_index);951 const extra = self.code.extraData(Zir.Inst.MultiOp, inst_data.payload_index);
952 const args = self.code.refSlice(extra.end, extra.data.operands_len);952 const args = self.code.refSlice(extra.end, extra.data.operands_len);
...@@ -959,7 +959,7 @@ const Writer = struct {...@@ -959,7 +959,7 @@ const Writer = struct {
959 try self.writeSrcNode(stream, inst_data.src_node);959 try self.writeSrcNode(stream, inst_data.src_node);
960 }960 }
961961
962 fn writeArrayMul(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {962 fn writeArrayMul(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
963 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;963 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
964 const extra = self.code.extraData(Zir.Inst.ArrayMul, inst_data.payload_index).data;964 const extra = self.code.extraData(Zir.Inst.ArrayMul, inst_data.payload_index).data;
965 try self.writeInstRef(stream, extra.res_ty);965 try self.writeInstRef(stream, extra.res_ty);
...@@ -971,13 +971,13 @@ const Writer = struct {...@@ -971,13 +971,13 @@ const Writer = struct {
971 try self.writeSrcNode(stream, inst_data.src_node);971 try self.writeSrcNode(stream, inst_data.src_node);
972 }972 }
973973
974 fn writeElemValImm(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {974 fn writeElemValImm(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
975 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].elem_val_imm;975 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].elem_val_imm;
976 try self.writeInstRef(stream, inst_data.operand);976 try self.writeInstRef(stream, inst_data.operand);
977 try stream.print(", {d})", .{inst_data.idx});977 try stream.print(", {d})", .{inst_data.idx});
978 }978 }
979979
980 fn writeArrayInitElemPtr(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {980 fn writeArrayInitElemPtr(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
981 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;981 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
982 const extra = self.code.extraData(Zir.Inst.ElemPtrImm, inst_data.payload_index).data;982 const extra = self.code.extraData(Zir.Inst.ElemPtrImm, inst_data.payload_index).data;
983983
...@@ -986,7 +986,7 @@ const Writer = struct {...@@ -986,7 +986,7 @@ const Writer = struct {
986 try self.writeSrcNode(stream, inst_data.src_node);986 try self.writeSrcNode(stream, inst_data.src_node);
987 }987 }
988988
989 fn writePlNodeExport(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {989 fn writePlNodeExport(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
990 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;990 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
991 const extra = self.code.extraData(Zir.Inst.Export, inst_data.payload_index).data;991 const extra = self.code.extraData(Zir.Inst.Export, inst_data.payload_index).data;
992992
...@@ -997,7 +997,7 @@ const Writer = struct {...@@ -997,7 +997,7 @@ const Writer = struct {
997 try self.writeSrcNode(stream, inst_data.src_node);997 try self.writeSrcNode(stream, inst_data.src_node);
998 }998 }
999999
1000 fn writeValidateArrayInitRefTy(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {1000 fn writeValidateArrayInitRefTy(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
1001 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;1001 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1002 const extra = self.code.extraData(Zir.Inst.ArrayInitRefTy, inst_data.payload_index).data;1002 const extra = self.code.extraData(Zir.Inst.ArrayInitRefTy, inst_data.payload_index).data;
10031003
...@@ -1007,7 +1007,7 @@ const Writer = struct {...@@ -1007,7 +1007,7 @@ const Writer = struct {
1007 try self.writeSrcNode(stream, inst_data.src_node);1007 try self.writeSrcNode(stream, inst_data.src_node);
1008 }1008 }
10091009
1010 fn writeStructInit(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {1010 fn writeStructInit(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
1011 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;1011 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1012 const extra = self.code.extraData(Zir.Inst.StructInit, inst_data.payload_index);1012 const extra = self.code.extraData(Zir.Inst.StructInit, inst_data.payload_index);
1013 var field_i: u32 = 0;1013 var field_i: u32 = 0;
...@@ -1031,7 +1031,7 @@ const Writer = struct {...@@ -1031,7 +1031,7 @@ const Writer = struct {
1031 try self.writeSrcNode(stream, inst_data.src_node);1031 try self.writeSrcNode(stream, inst_data.src_node);
1032 }1032 }
10331033
1034 fn writeCmpxchg(self: *Writer, stream: *std.io.Writer, extended: Zir.Inst.Extended.InstData) !void {1034 fn writeCmpxchg(self: *Writer, stream: *std.Io.Writer, extended: Zir.Inst.Extended.InstData) !void {
1035 const extra = self.code.extraData(Zir.Inst.Cmpxchg, extended.operand).data;1035 const extra = self.code.extraData(Zir.Inst.Cmpxchg, extended.operand).data;
10361036
1037 try self.writeInstRef(stream, extra.ptr);1037 try self.writeInstRef(stream, extra.ptr);
...@@ -1047,7 +1047,7 @@ const Writer = struct {...@@ -1047,7 +1047,7 @@ const Writer = struct {
1047 try self.writeSrcNode(stream, extra.node);1047 try self.writeSrcNode(stream, extra.node);
1048 }1048 }
10491049
1050 fn writePtrCastFull(self: *Writer, stream: *std.io.Writer, extended: Zir.Inst.Extended.InstData) !void {1050 fn writePtrCastFull(self: *Writer, stream: *std.Io.Writer, extended: Zir.Inst.Extended.InstData) !void {
1051 const FlagsInt = @typeInfo(Zir.Inst.FullPtrCastFlags).@"struct".backing_integer.?;1051 const FlagsInt = @typeInfo(Zir.Inst.FullPtrCastFlags).@"struct".backing_integer.?;
1052 const flags: Zir.Inst.FullPtrCastFlags = @bitCast(@as(FlagsInt, @truncate(extended.small)));1052 const flags: Zir.Inst.FullPtrCastFlags = @bitCast(@as(FlagsInt, @truncate(extended.small)));
1053 const extra = self.code.extraData(Zir.Inst.BinNode, extended.operand).data;1053 const extra = self.code.extraData(Zir.Inst.BinNode, extended.operand).data;
...@@ -1063,7 +1063,7 @@ const Writer = struct {...@@ -1063,7 +1063,7 @@ const Writer = struct {
1063 try self.writeSrcNode(stream, extra.node);1063 try self.writeSrcNode(stream, extra.node);
1064 }1064 }
10651065
1066 fn writePtrCastNoDest(self: *Writer, stream: *std.io.Writer, extended: Zir.Inst.Extended.InstData) !void {1066 fn writePtrCastNoDest(self: *Writer, stream: *std.Io.Writer, extended: Zir.Inst.Extended.InstData) !void {
1067 const FlagsInt = @typeInfo(Zir.Inst.FullPtrCastFlags).@"struct".backing_integer.?;1067 const FlagsInt = @typeInfo(Zir.Inst.FullPtrCastFlags).@"struct".backing_integer.?;
1068 const flags: Zir.Inst.FullPtrCastFlags = @bitCast(@as(FlagsInt, @truncate(extended.small)));1068 const flags: Zir.Inst.FullPtrCastFlags = @bitCast(@as(FlagsInt, @truncate(extended.small)));
1069 const extra = self.code.extraData(Zir.Inst.UnNode, extended.operand).data;1069 const extra = self.code.extraData(Zir.Inst.UnNode, extended.operand).data;
...@@ -1074,7 +1074,7 @@ const Writer = struct {...@@ -1074,7 +1074,7 @@ const Writer = struct {
1074 try self.writeSrcNode(stream, extra.node);1074 try self.writeSrcNode(stream, extra.node);
1075 }1075 }
10761076
1077 fn writeAtomicLoad(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {1077 fn writeAtomicLoad(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
1078 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;1078 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1079 const extra = self.code.extraData(Zir.Inst.AtomicLoad, inst_data.payload_index).data;1079 const extra = self.code.extraData(Zir.Inst.AtomicLoad, inst_data.payload_index).data;
10801080
...@@ -1087,7 +1087,7 @@ const Writer = struct {...@@ -1087,7 +1087,7 @@ const Writer = struct {
1087 try self.writeSrcNode(stream, inst_data.src_node);1087 try self.writeSrcNode(stream, inst_data.src_node);
1088 }1088 }
10891089
1090 fn writeAtomicStore(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {1090 fn writeAtomicStore(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
1091 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;1091 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1092 const extra = self.code.extraData(Zir.Inst.AtomicStore, inst_data.payload_index).data;1092 const extra = self.code.extraData(Zir.Inst.AtomicStore, inst_data.payload_index).data;
10931093
...@@ -1100,7 +1100,7 @@ const Writer = struct {...@@ -1100,7 +1100,7 @@ const Writer = struct {
1100 try self.writeSrcNode(stream, inst_data.src_node);1100 try self.writeSrcNode(stream, inst_data.src_node);
1101 }1101 }
11021102
1103 fn writeAtomicRmw(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {1103 fn writeAtomicRmw(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
1104 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;1104 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1105 const extra = self.code.extraData(Zir.Inst.AtomicRmw, inst_data.payload_index).data;1105 const extra = self.code.extraData(Zir.Inst.AtomicRmw, inst_data.payload_index).data;
11061106
...@@ -1115,7 +1115,7 @@ const Writer = struct {...@@ -1115,7 +1115,7 @@ const Writer = struct {
1115 try self.writeSrcNode(stream, inst_data.src_node);1115 try self.writeSrcNode(stream, inst_data.src_node);
1116 }1116 }
11171117
1118 fn writeStructInitAnon(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {1118 fn writeStructInitAnon(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
1119 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;1119 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1120 const extra = self.code.extraData(Zir.Inst.StructInitAnon, inst_data.payload_index);1120 const extra = self.code.extraData(Zir.Inst.StructInitAnon, inst_data.payload_index);
1121 var field_i: u32 = 0;1121 var field_i: u32 = 0;
...@@ -1136,7 +1136,7 @@ const Writer = struct {...@@ -1136,7 +1136,7 @@ const Writer = struct {
1136 try self.writeSrcNode(stream, inst_data.src_node);1136 try self.writeSrcNode(stream, inst_data.src_node);
1137 }1137 }
11381138
1139 fn writeStructInitFieldType(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {1139 fn writeStructInitFieldType(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
1140 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;1140 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1141 const extra = self.code.extraData(Zir.Inst.FieldType, inst_data.payload_index).data;1141 const extra = self.code.extraData(Zir.Inst.FieldType, inst_data.payload_index).data;
1142 try self.writeInstRef(stream, extra.container_type);1142 try self.writeInstRef(stream, extra.container_type);
...@@ -1145,7 +1145,7 @@ const Writer = struct {...@@ -1145,7 +1145,7 @@ const Writer = struct {
1145 try self.writeSrcNode(stream, inst_data.src_node);1145 try self.writeSrcNode(stream, inst_data.src_node);
1146 }1146 }
11471147
1148 fn writeFieldTypeRef(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {1148 fn writeFieldTypeRef(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
1149 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;1149 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1150 const extra = self.code.extraData(Zir.Inst.FieldTypeRef, inst_data.payload_index).data;1150 const extra = self.code.extraData(Zir.Inst.FieldTypeRef, inst_data.payload_index).data;
1151 try self.writeInstRef(stream, extra.container_type);1151 try self.writeInstRef(stream, extra.container_type);
...@@ -1155,7 +1155,7 @@ const Writer = struct {...@@ -1155,7 +1155,7 @@ const Writer = struct {
1155 try self.writeSrcNode(stream, inst_data.src_node);1155 try self.writeSrcNode(stream, inst_data.src_node);
1156 }1156 }
11571157
1158 fn writeNodeMultiOp(self: *Writer, stream: *std.io.Writer, extended: Zir.Inst.Extended.InstData) !void {1158 fn writeNodeMultiOp(self: *Writer, stream: *std.Io.Writer, extended: Zir.Inst.Extended.InstData) !void {
1159 const extra = self.code.extraData(Zir.Inst.NodeMultiOp, extended.operand);1159 const extra = self.code.extraData(Zir.Inst.NodeMultiOp, extended.operand);
1160 const operands = self.code.refSlice(extra.end, extended.small);1160 const operands = self.code.refSlice(extra.end, extended.small);
11611161
...@@ -1169,7 +1169,7 @@ const Writer = struct {...@@ -1169,7 +1169,7 @@ const Writer = struct {
11691169
1170 fn writeInstNode(1170 fn writeInstNode(
1171 self: *Writer,1171 self: *Writer,
1172 stream: *std.io.Writer,1172 stream: *std.Io.Writer,
1173 inst: Zir.Inst.Index,1173 inst: Zir.Inst.Index,
1174 ) Error!void {1174 ) Error!void {
1175 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].inst_node;1175 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].inst_node;
...@@ -1180,7 +1180,7 @@ const Writer = struct {...@@ -1180,7 +1180,7 @@ const Writer = struct {
11801180
1181 fn writeAsm(1181 fn writeAsm(
1182 self: *Writer,1182 self: *Writer,
1183 stream: *std.io.Writer,1183 stream: *std.Io.Writer,
1184 extended: Zir.Inst.Extended.InstData,1184 extended: Zir.Inst.Extended.InstData,
1185 tmpl_is_expr: bool,1185 tmpl_is_expr: bool,
1186 ) !void {1186 ) !void {
...@@ -1258,7 +1258,7 @@ const Writer = struct {...@@ -1258,7 +1258,7 @@ const Writer = struct {
1258 try self.writeSrcNode(stream, extra.data.src_node);1258 try self.writeSrcNode(stream, extra.data.src_node);
1259 }1259 }
12601260
1261 fn writeOverflowArithmetic(self: *Writer, stream: *std.io.Writer, extended: Zir.Inst.Extended.InstData) !void {1261 fn writeOverflowArithmetic(self: *Writer, stream: *std.Io.Writer, extended: Zir.Inst.Extended.InstData) !void {
1262 const extra = self.code.extraData(Zir.Inst.BinNode, extended.operand).data;1262 const extra = self.code.extraData(Zir.Inst.BinNode, extended.operand).data;
12631263
1264 try self.writeInstRef(stream, extra.lhs);1264 try self.writeInstRef(stream, extra.lhs);
...@@ -1270,7 +1270,7 @@ const Writer = struct {...@@ -1270,7 +1270,7 @@ const Writer = struct {
12701270
1271 fn writeCall(1271 fn writeCall(
1272 self: *Writer,1272 self: *Writer,
1273 stream: *std.io.Writer,1273 stream: *std.Io.Writer,
1274 inst: Zir.Inst.Index,1274 inst: Zir.Inst.Index,
1275 comptime kind: enum { direct, field },1275 comptime kind: enum { direct, field },
1276 ) !void {1276 ) !void {
...@@ -1321,7 +1321,7 @@ const Writer = struct {...@@ -1321,7 +1321,7 @@ const Writer = struct {
1321 try self.writeSrcNode(stream, inst_data.src_node);1321 try self.writeSrcNode(stream, inst_data.src_node);
1322 }1322 }
13231323
1324 fn writeBlock(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {1324 fn writeBlock(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
1325 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;1325 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1326 const extra = self.code.extraData(Zir.Inst.Block, inst_data.payload_index);1326 const extra = self.code.extraData(Zir.Inst.Block, inst_data.payload_index);
1327 const body = self.code.bodySlice(extra.end, extra.data.body_len);1327 const body = self.code.bodySlice(extra.end, extra.data.body_len);
...@@ -1330,7 +1330,7 @@ const Writer = struct {...@@ -1330,7 +1330,7 @@ const Writer = struct {
1330 try self.writeSrcNode(stream, inst_data.src_node);1330 try self.writeSrcNode(stream, inst_data.src_node);
1331 }1331 }
13321332
1333 fn writeBlockComptime(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {1333 fn writeBlockComptime(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
1334 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;1334 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1335 const extra = self.code.extraData(Zir.Inst.BlockComptime, inst_data.payload_index);1335 const extra = self.code.extraData(Zir.Inst.BlockComptime, inst_data.payload_index);
1336 const body = self.code.bodySlice(extra.end, extra.data.body_len);1336 const body = self.code.bodySlice(extra.end, extra.data.body_len);
...@@ -1340,7 +1340,7 @@ const Writer = struct {...@@ -1340,7 +1340,7 @@ const Writer = struct {
1340 try self.writeSrcNode(stream, inst_data.src_node);1340 try self.writeSrcNode(stream, inst_data.src_node);
1341 }1341 }
13421342
1343 fn writeCondBr(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {1343 fn writeCondBr(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
1344 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;1344 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1345 const extra = self.code.extraData(Zir.Inst.CondBr, inst_data.payload_index);1345 const extra = self.code.extraData(Zir.Inst.CondBr, inst_data.payload_index);
1346 const then_body = self.code.bodySlice(extra.end, extra.data.then_body_len);1346 const then_body = self.code.bodySlice(extra.end, extra.data.then_body_len);
...@@ -1354,7 +1354,7 @@ const Writer = struct {...@@ -1354,7 +1354,7 @@ const Writer = struct {
1354 try self.writeSrcNode(stream, inst_data.src_node);1354 try self.writeSrcNode(stream, inst_data.src_node);
1355 }1355 }
13561356
1357 fn writeTry(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {1357 fn writeTry(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
1358 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;1358 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1359 const extra = self.code.extraData(Zir.Inst.Try, inst_data.payload_index);1359 const extra = self.code.extraData(Zir.Inst.Try, inst_data.payload_index);
1360 const body = self.code.bodySlice(extra.end, extra.data.body_len);1360 const body = self.code.bodySlice(extra.end, extra.data.body_len);
...@@ -1365,7 +1365,7 @@ const Writer = struct {...@@ -1365,7 +1365,7 @@ const Writer = struct {
1365 try self.writeSrcNode(stream, inst_data.src_node);1365 try self.writeSrcNode(stream, inst_data.src_node);
1366 }1366 }
13671367
1368 fn writeStructDecl(self: *Writer, stream: *std.io.Writer, extended: Zir.Inst.Extended.InstData) !void {1368 fn writeStructDecl(self: *Writer, stream: *std.Io.Writer, extended: Zir.Inst.Extended.InstData) !void {
1369 const small: Zir.Inst.StructDecl.Small = @bitCast(extended.small);1369 const small: Zir.Inst.StructDecl.Small = @bitCast(extended.small);
13701370
1371 const extra = self.code.extraData(Zir.Inst.StructDecl, extended.operand);1371 const extra = self.code.extraData(Zir.Inst.StructDecl, extended.operand);
...@@ -1557,7 +1557,7 @@ const Writer = struct {...@@ -1557,7 +1557,7 @@ const Writer = struct {
1557 try self.writeSrcNode(stream, .zero);1557 try self.writeSrcNode(stream, .zero);
1558 }1558 }
15591559
1560 fn writeUnionDecl(self: *Writer, stream: *std.io.Writer, extended: Zir.Inst.Extended.InstData) !void {1560 fn writeUnionDecl(self: *Writer, stream: *std.Io.Writer, extended: Zir.Inst.Extended.InstData) !void {
1561 const small = @as(Zir.Inst.UnionDecl.Small, @bitCast(extended.small));1561 const small = @as(Zir.Inst.UnionDecl.Small, @bitCast(extended.small));
15621562
1563 const extra = self.code.extraData(Zir.Inst.UnionDecl, extended.operand);1563 const extra = self.code.extraData(Zir.Inst.UnionDecl, extended.operand);
...@@ -1708,7 +1708,7 @@ const Writer = struct {...@@ -1708,7 +1708,7 @@ const Writer = struct {
1708 try self.writeSrcNode(stream, .zero);1708 try self.writeSrcNode(stream, .zero);
1709 }1709 }
17101710
1711 fn writeEnumDecl(self: *Writer, stream: *std.io.Writer, extended: Zir.Inst.Extended.InstData) !void {1711 fn writeEnumDecl(self: *Writer, stream: *std.Io.Writer, extended: Zir.Inst.Extended.InstData) !void {
1712 const small = @as(Zir.Inst.EnumDecl.Small, @bitCast(extended.small));1712 const small = @as(Zir.Inst.EnumDecl.Small, @bitCast(extended.small));
17131713
1714 const extra = self.code.extraData(Zir.Inst.EnumDecl, extended.operand);1714 const extra = self.code.extraData(Zir.Inst.EnumDecl, extended.operand);
...@@ -1829,7 +1829,7 @@ const Writer = struct {...@@ -1829,7 +1829,7 @@ const Writer = struct {
18291829
1830 fn writeOpaqueDecl(1830 fn writeOpaqueDecl(
1831 self: *Writer,1831 self: *Writer,
1832 stream: *std.io.Writer,1832 stream: *std.Io.Writer,
1833 extended: Zir.Inst.Extended.InstData,1833 extended: Zir.Inst.Extended.InstData,
1834 ) !void {1834 ) !void {
1835 const small = @as(Zir.Inst.OpaqueDecl.Small, @bitCast(extended.small));1835 const small = @as(Zir.Inst.OpaqueDecl.Small, @bitCast(extended.small));
...@@ -1871,7 +1871,7 @@ const Writer = struct {...@@ -1871,7 +1871,7 @@ const Writer = struct {
1871 try self.writeSrcNode(stream, .zero);1871 try self.writeSrcNode(stream, .zero);
1872 }1872 }
18731873
1874 fn writeTupleDecl(self: *Writer, stream: *std.io.Writer, extended: Zir.Inst.Extended.InstData) !void {1874 fn writeTupleDecl(self: *Writer, stream: *std.Io.Writer, extended: Zir.Inst.Extended.InstData) !void {
1875 const fields_len = extended.small;1875 const fields_len = extended.small;
1876 assert(fields_len != 0);1876 assert(fields_len != 0);
1877 const extra = self.code.extraData(Zir.Inst.TupleDecl, extended.operand);1877 const extra = self.code.extraData(Zir.Inst.TupleDecl, extended.operand);
...@@ -1899,7 +1899,7 @@ const Writer = struct {...@@ -1899,7 +1899,7 @@ const Writer = struct {
18991899
1900 fn writeErrorSetDecl(1900 fn writeErrorSetDecl(
1901 self: *Writer,1901 self: *Writer,
1902 stream: *std.io.Writer,1902 stream: *std.Io.Writer,
1903 inst: Zir.Inst.Index,1903 inst: Zir.Inst.Index,
1904 ) !void {1904 ) !void {
1905 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;1905 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
...@@ -1924,7 +1924,7 @@ const Writer = struct {...@@ -1924,7 +1924,7 @@ const Writer = struct {
1924 try self.writeSrcNode(stream, inst_data.src_node);1924 try self.writeSrcNode(stream, inst_data.src_node);
1925 }1925 }
19261926
1927 fn writeSwitchBlockErrUnion(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {1927 fn writeSwitchBlockErrUnion(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
1928 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;1928 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1929 const extra = self.code.extraData(Zir.Inst.SwitchBlockErrUnion, inst_data.payload_index);1929 const extra = self.code.extraData(Zir.Inst.SwitchBlockErrUnion, inst_data.payload_index);
19301930
...@@ -2061,7 +2061,7 @@ const Writer = struct {...@@ -2061,7 +2061,7 @@ const Writer = struct {
2061 try self.writeSrcNode(stream, inst_data.src_node);2061 try self.writeSrcNode(stream, inst_data.src_node);
2062 }2062 }
20632063
2064 fn writeSwitchBlock(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {2064 fn writeSwitchBlock(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
2065 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;2065 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2066 const extra = self.code.extraData(Zir.Inst.SwitchBlock, inst_data.payload_index);2066 const extra = self.code.extraData(Zir.Inst.SwitchBlock, inst_data.payload_index);
20672067
...@@ -2242,7 +2242,7 @@ const Writer = struct {...@@ -2242,7 +2242,7 @@ const Writer = struct {
2242 try self.writeSrcNode(stream, inst_data.src_node);2242 try self.writeSrcNode(stream, inst_data.src_node);
2243 }2243 }
22442244
2245 fn writePlNodeField(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {2245 fn writePlNodeField(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
2246 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;2246 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2247 const extra = self.code.extraData(Zir.Inst.Field, inst_data.payload_index).data;2247 const extra = self.code.extraData(Zir.Inst.Field, inst_data.payload_index).data;
2248 const name = self.code.nullTerminatedString(extra.field_name_start);2248 const name = self.code.nullTerminatedString(extra.field_name_start);
...@@ -2251,7 +2251,7 @@ const Writer = struct {...@@ -2251,7 +2251,7 @@ const Writer = struct {
2251 try self.writeSrcNode(stream, inst_data.src_node);2251 try self.writeSrcNode(stream, inst_data.src_node);
2252 }2252 }
22532253
2254 fn writePlNodeFieldNamed(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {2254 fn writePlNodeFieldNamed(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
2255 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;2255 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2256 const extra = self.code.extraData(Zir.Inst.FieldNamed, inst_data.payload_index).data;2256 const extra = self.code.extraData(Zir.Inst.FieldNamed, inst_data.payload_index).data;
2257 try self.writeInstRef(stream, extra.lhs);2257 try self.writeInstRef(stream, extra.lhs);
...@@ -2261,7 +2261,7 @@ const Writer = struct {...@@ -2261,7 +2261,7 @@ const Writer = struct {
2261 try self.writeSrcNode(stream, inst_data.src_node);2261 try self.writeSrcNode(stream, inst_data.src_node);
2262 }2262 }
22632263
2264 fn writeAs(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {2264 fn writeAs(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
2265 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;2265 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2266 const extra = self.code.extraData(Zir.Inst.As, inst_data.payload_index).data;2266 const extra = self.code.extraData(Zir.Inst.As, inst_data.payload_index).data;
2267 try self.writeInstRef(stream, extra.dest_type);2267 try self.writeInstRef(stream, extra.dest_type);
...@@ -2273,7 +2273,7 @@ const Writer = struct {...@@ -2273,7 +2273,7 @@ const Writer = struct {
22732273
2274 fn writeNode(2274 fn writeNode(
2275 self: *Writer,2275 self: *Writer,
2276 stream: *std.io.Writer,2276 stream: *std.Io.Writer,
2277 inst: Zir.Inst.Index,2277 inst: Zir.Inst.Index,
2278 ) Error!void {2278 ) Error!void {
2279 const src_node = self.code.instructions.items(.data)[@intFromEnum(inst)].node;2279 const src_node = self.code.instructions.items(.data)[@intFromEnum(inst)].node;
...@@ -2283,7 +2283,7 @@ const Writer = struct {...@@ -2283,7 +2283,7 @@ const Writer = struct {
22832283
2284 fn writeStrTok(2284 fn writeStrTok(
2285 self: *Writer,2285 self: *Writer,
2286 stream: *std.io.Writer,2286 stream: *std.Io.Writer,
2287 inst: Zir.Inst.Index,2287 inst: Zir.Inst.Index,
2288 ) Error!void {2288 ) Error!void {
2289 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].str_tok;2289 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].str_tok;
...@@ -2292,7 +2292,7 @@ const Writer = struct {...@@ -2292,7 +2292,7 @@ const Writer = struct {
2292 try self.writeSrcTok(stream, inst_data.src_tok);2292 try self.writeSrcTok(stream, inst_data.src_tok);
2293 }2293 }
22942294
2295 fn writeStrOp(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {2295 fn writeStrOp(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
2296 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].str_op;2296 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].str_op;
2297 const str = inst_data.getStr(self.code);2297 const str = inst_data.getStr(self.code);
2298 try self.writeInstRef(stream, inst_data.operand);2298 try self.writeInstRef(stream, inst_data.operand);
...@@ -2301,7 +2301,7 @@ const Writer = struct {...@@ -2301,7 +2301,7 @@ const Writer = struct {
23012301
2302 fn writeFunc(2302 fn writeFunc(
2303 self: *Writer,2303 self: *Writer,
2304 stream: *std.io.Writer,2304 stream: *std.Io.Writer,
2305 inst: Zir.Inst.Index,2305 inst: Zir.Inst.Index,
2306 inferred_error_set: bool,2306 inferred_error_set: bool,
2307 ) !void {2307 ) !void {
...@@ -2352,7 +2352,7 @@ const Writer = struct {...@@ -2352,7 +2352,7 @@ const Writer = struct {
2352 );2352 );
2353 }2353 }
23542354
2355 fn writeFuncFancy(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {2355 fn writeFuncFancy(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
2356 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;2356 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2357 const extra = self.code.extraData(Zir.Inst.FuncFancy, inst_data.payload_index);2357 const extra = self.code.extraData(Zir.Inst.FuncFancy, inst_data.payload_index);
23582358
...@@ -2411,7 +2411,7 @@ const Writer = struct {...@@ -2411,7 +2411,7 @@ const Writer = struct {
2411 );2411 );
2412 }2412 }
24132413
2414 fn writeAllocExtended(self: *Writer, stream: *std.io.Writer, extended: Zir.Inst.Extended.InstData) !void {2414 fn writeAllocExtended(self: *Writer, stream: *std.Io.Writer, extended: Zir.Inst.Extended.InstData) !void {
2415 const extra = self.code.extraData(Zir.Inst.AllocExtended, extended.operand);2415 const extra = self.code.extraData(Zir.Inst.AllocExtended, extended.operand);
2416 const small = @as(Zir.Inst.AllocExtended.Small, @bitCast(extended.small));2416 const small = @as(Zir.Inst.AllocExtended.Small, @bitCast(extended.small));
24172417
...@@ -2434,7 +2434,7 @@ const Writer = struct {...@@ -2434,7 +2434,7 @@ const Writer = struct {
2434 try self.writeSrcNode(stream, extra.data.src_node);2434 try self.writeSrcNode(stream, extra.data.src_node);
2435 }2435 }
24362436
2437 fn writeTypeofPeer(self: *Writer, stream: *std.io.Writer, extended: Zir.Inst.Extended.InstData) !void {2437 fn writeTypeofPeer(self: *Writer, stream: *std.Io.Writer, extended: Zir.Inst.Extended.InstData) !void {
2438 const extra = self.code.extraData(Zir.Inst.TypeOfPeer, extended.operand);2438 const extra = self.code.extraData(Zir.Inst.TypeOfPeer, extended.operand);
2439 const body = self.code.bodySlice(extra.data.body_index, extra.data.body_len);2439 const body = self.code.bodySlice(extra.data.body_index, extra.data.body_len);
2440 try self.writeBracedBody(stream, body);2440 try self.writeBracedBody(stream, body);
...@@ -2447,7 +2447,7 @@ const Writer = struct {...@@ -2447,7 +2447,7 @@ const Writer = struct {
2447 try stream.writeAll("])");2447 try stream.writeAll("])");
2448 }2448 }
24492449
2450 fn writeBoolBr(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {2450 fn writeBoolBr(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
2451 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;2451 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2452 const extra = self.code.extraData(Zir.Inst.BoolBr, inst_data.payload_index);2452 const extra = self.code.extraData(Zir.Inst.BoolBr, inst_data.payload_index);
2453 const body = self.code.bodySlice(extra.end, extra.data.body_len);2453 const body = self.code.bodySlice(extra.end, extra.data.body_len);
...@@ -2458,7 +2458,7 @@ const Writer = struct {...@@ -2458,7 +2458,7 @@ const Writer = struct {
2458 try self.writeSrcNode(stream, inst_data.src_node);2458 try self.writeSrcNode(stream, inst_data.src_node);
2459 }2459 }
24602460
2461 fn writeIntType(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {2461 fn writeIntType(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
2462 const int_type = self.code.instructions.items(.data)[@intFromEnum(inst)].int_type;2462 const int_type = self.code.instructions.items(.data)[@intFromEnum(inst)].int_type;
2463 const prefix: u8 = switch (int_type.signedness) {2463 const prefix: u8 = switch (int_type.signedness) {
2464 .signed => 'i',2464 .signed => 'i',
...@@ -2468,7 +2468,7 @@ const Writer = struct {...@@ -2468,7 +2468,7 @@ const Writer = struct {
2468 try self.writeSrcNode(stream, int_type.src_node);2468 try self.writeSrcNode(stream, int_type.src_node);
2469 }2469 }
24702470
2471 fn writeSaveErrRetIndex(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {2471 fn writeSaveErrRetIndex(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
2472 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].save_err_ret_index;2472 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].save_err_ret_index;
24732473
2474 try self.writeInstRef(stream, inst_data.operand);2474 try self.writeInstRef(stream, inst_data.operand);
...@@ -2476,7 +2476,7 @@ const Writer = struct {...@@ -2476,7 +2476,7 @@ const Writer = struct {
2476 try stream.writeAll(")");2476 try stream.writeAll(")");
2477 }2477 }
24782478
2479 fn writeRestoreErrRetIndex(self: *Writer, stream: *std.io.Writer, extended: Zir.Inst.Extended.InstData) !void {2479 fn writeRestoreErrRetIndex(self: *Writer, stream: *std.Io.Writer, extended: Zir.Inst.Extended.InstData) !void {
2480 const extra = self.code.extraData(Zir.Inst.RestoreErrRetIndex, extended.operand).data;2480 const extra = self.code.extraData(Zir.Inst.RestoreErrRetIndex, extended.operand).data;
24812481
2482 try self.writeInstRef(stream, extra.block);2482 try self.writeInstRef(stream, extra.block);
...@@ -2486,7 +2486,7 @@ const Writer = struct {...@@ -2486,7 +2486,7 @@ const Writer = struct {
2486 try self.writeSrcNode(stream, extra.src_node);2486 try self.writeSrcNode(stream, extra.src_node);
2487 }2487 }
24882488
2489 fn writeBreak(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {2489 fn writeBreak(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
2490 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].@"break";2490 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].@"break";
2491 const extra = self.code.extraData(Zir.Inst.Break, inst_data.payload_index).data;2491 const extra = self.code.extraData(Zir.Inst.Break, inst_data.payload_index).data;
24922492
...@@ -2496,7 +2496,7 @@ const Writer = struct {...@@ -2496,7 +2496,7 @@ const Writer = struct {
2496 try stream.writeAll(")");2496 try stream.writeAll(")");
2497 }2497 }
24982498
2499 fn writeArrayInit(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {2499 fn writeArrayInit(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
2500 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;2500 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
25012501
2502 const extra = self.code.extraData(Zir.Inst.MultiOp, inst_data.payload_index);2502 const extra = self.code.extraData(Zir.Inst.MultiOp, inst_data.payload_index);
...@@ -2512,7 +2512,7 @@ const Writer = struct {...@@ -2512,7 +2512,7 @@ const Writer = struct {
2512 try self.writeSrcNode(stream, inst_data.src_node);2512 try self.writeSrcNode(stream, inst_data.src_node);
2513 }2513 }
25142514
2515 fn writeArrayInitAnon(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {2515 fn writeArrayInitAnon(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
2516 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;2516 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
25172517
2518 const extra = self.code.extraData(Zir.Inst.MultiOp, inst_data.payload_index);2518 const extra = self.code.extraData(Zir.Inst.MultiOp, inst_data.payload_index);
...@@ -2527,7 +2527,7 @@ const Writer = struct {...@@ -2527,7 +2527,7 @@ const Writer = struct {
2527 try self.writeSrcNode(stream, inst_data.src_node);2527 try self.writeSrcNode(stream, inst_data.src_node);
2528 }2528 }
25292529
2530 fn writeArrayInitSent(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {2530 fn writeArrayInitSent(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
2531 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;2531 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
25322532
2533 const extra = self.code.extraData(Zir.Inst.MultiOp, inst_data.payload_index);2533 const extra = self.code.extraData(Zir.Inst.MultiOp, inst_data.payload_index);
...@@ -2547,7 +2547,7 @@ const Writer = struct {...@@ -2547,7 +2547,7 @@ const Writer = struct {
2547 try self.writeSrcNode(stream, inst_data.src_node);2547 try self.writeSrcNode(stream, inst_data.src_node);
2548 }2548 }
25492549
2550 fn writeUnreachable(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {2550 fn writeUnreachable(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
2551 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].@"unreachable";2551 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].@"unreachable";
2552 try stream.writeAll(") ");2552 try stream.writeAll(") ");
2553 try self.writeSrcNode(stream, inst_data.src_node);2553 try self.writeSrcNode(stream, inst_data.src_node);
...@@ -2555,7 +2555,7 @@ const Writer = struct {...@@ -2555,7 +2555,7 @@ const Writer = struct {
25552555
2556 fn writeFuncCommon(2556 fn writeFuncCommon(
2557 self: *Writer,2557 self: *Writer,
2558 stream: *std.io.Writer,2558 stream: *std.Io.Writer,
2559 inferred_error_set: bool,2559 inferred_error_set: bool,
2560 var_args: bool,2560 var_args: bool,
2561 is_noinline: bool,2561 is_noinline: bool,
...@@ -2592,19 +2592,19 @@ const Writer = struct {...@@ -2592,19 +2592,19 @@ const Writer = struct {
2592 try self.writeSrcNode(stream, src_node);2592 try self.writeSrcNode(stream, src_node);
2593 }2593 }
25942594
2595 fn writeDbgStmt(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {2595 fn writeDbgStmt(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
2596 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].dbg_stmt;2596 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].dbg_stmt;
2597 try stream.print("{d}, {d})", .{ inst_data.line + 1, inst_data.column + 1 });2597 try stream.print("{d}, {d})", .{ inst_data.line + 1, inst_data.column + 1 });
2598 }2598 }
25992599
2600 fn writeDefer(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {2600 fn writeDefer(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
2601 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].@"defer";2601 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].@"defer";
2602 const body = self.code.bodySlice(inst_data.index, inst_data.len);2602 const body = self.code.bodySlice(inst_data.index, inst_data.len);
2603 try self.writeBracedBody(stream, body);2603 try self.writeBracedBody(stream, body);
2604 try stream.writeByte(')');2604 try stream.writeByte(')');
2605 }2605 }
26062606
2607 fn writeDeferErrCode(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {2607 fn writeDeferErrCode(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
2608 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].defer_err_code;2608 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].defer_err_code;
2609 const extra = self.code.extraData(Zir.Inst.DeferErrCode, inst_data.payload_index).data;2609 const extra = self.code.extraData(Zir.Inst.DeferErrCode, inst_data.payload_index).data;
26102610
...@@ -2617,7 +2617,7 @@ const Writer = struct {...@@ -2617,7 +2617,7 @@ const Writer = struct {
2617 try stream.writeByte(')');2617 try stream.writeByte(')');
2618 }2618 }
26192619
2620 fn writeDeclaration(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {2620 fn writeDeclaration(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
2621 const decl = self.code.getDeclaration(inst);2621 const decl = self.code.getDeclaration(inst);
26222622
2623 const prev_parent_decl_node = self.parent_decl_node;2623 const prev_parent_decl_node = self.parent_decl_node;
...@@ -2673,26 +2673,26 @@ const Writer = struct {...@@ -2673,26 +2673,26 @@ const Writer = struct {
2673 try self.writeSrcNode(stream, .zero);2673 try self.writeSrcNode(stream, .zero);
2674 }2674 }
26752675
2676 fn writeClosureGet(self: *Writer, stream: *std.io.Writer, extended: Zir.Inst.Extended.InstData) !void {2676 fn writeClosureGet(self: *Writer, stream: *std.Io.Writer, extended: Zir.Inst.Extended.InstData) !void {
2677 try stream.print("{d})) ", .{extended.small});2677 try stream.print("{d})) ", .{extended.small});
2678 const src_node: Ast.Node.Offset = @enumFromInt(@as(i32, @bitCast(extended.operand)));2678 const src_node: Ast.Node.Offset = @enumFromInt(@as(i32, @bitCast(extended.operand)));
2679 try self.writeSrcNode(stream, src_node);2679 try self.writeSrcNode(stream, src_node);
2680 }2680 }
26812681
2682 fn writeBuiltinValue(self: *Writer, stream: *std.io.Writer, extended: Zir.Inst.Extended.InstData) !void {2682 fn writeBuiltinValue(self: *Writer, stream: *std.Io.Writer, extended: Zir.Inst.Extended.InstData) !void {
2683 const val: Zir.Inst.BuiltinValue = @enumFromInt(extended.small);2683 const val: Zir.Inst.BuiltinValue = @enumFromInt(extended.small);
2684 try stream.print("{s})) ", .{@tagName(val)});2684 try stream.print("{s})) ", .{@tagName(val)});
2685 const src_node: Ast.Node.Offset = @enumFromInt(@as(i32, @bitCast(extended.operand)));2685 const src_node: Ast.Node.Offset = @enumFromInt(@as(i32, @bitCast(extended.operand)));
2686 try self.writeSrcNode(stream, src_node);2686 try self.writeSrcNode(stream, src_node);
2687 }2687 }
26882688
2689 fn writeInplaceArithResultTy(self: *Writer, stream: *std.io.Writer, extended: Zir.Inst.Extended.InstData) !void {2689 fn writeInplaceArithResultTy(self: *Writer, stream: *std.Io.Writer, extended: Zir.Inst.Extended.InstData) !void {
2690 const op: Zir.Inst.InplaceOp = @enumFromInt(extended.small);2690 const op: Zir.Inst.InplaceOp = @enumFromInt(extended.small);
2691 try self.writeInstRef(stream, @enumFromInt(extended.operand));2691 try self.writeInstRef(stream, @enumFromInt(extended.operand));
2692 try stream.print(", {s}))", .{@tagName(op)});2692 try stream.print(", {s}))", .{@tagName(op)});
2693 }2693 }
26942694
2695 fn writeInstRef(self: *Writer, stream: *std.io.Writer, ref: Zir.Inst.Ref) !void {2695 fn writeInstRef(self: *Writer, stream: *std.Io.Writer, ref: Zir.Inst.Ref) !void {
2696 if (ref == .none) {2696 if (ref == .none) {
2697 return stream.writeAll(".none");2697 return stream.writeAll(".none");
2698 } else if (ref.toIndex()) |i| {2698 } else if (ref.toIndex()) |i| {
...@@ -2703,12 +2703,12 @@ const Writer = struct {...@@ -2703,12 +2703,12 @@ const Writer = struct {
2703 }2703 }
2704 }2704 }
27052705
2706 fn writeInstIndex(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {2706 fn writeInstIndex(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
2707 _ = self;2707 _ = self;
2708 return stream.print("%{d}", .{@intFromEnum(inst)});2708 return stream.print("%{d}", .{@intFromEnum(inst)});
2709 }2709 }
27102710
2711 fn writeCaptures(self: *Writer, stream: *std.io.Writer, extra_index: usize, captures_len: u32) !usize {2711 fn writeCaptures(self: *Writer, stream: *std.Io.Writer, extra_index: usize, captures_len: u32) !usize {
2712 if (captures_len == 0) {2712 if (captures_len == 0) {
2713 try stream.writeAll("{}");2713 try stream.writeAll("{}");
2714 return extra_index;2714 return extra_index;
...@@ -2728,7 +2728,7 @@ const Writer = struct {...@@ -2728,7 +2728,7 @@ const Writer = struct {
2728 return extra_index + 2 * captures_len;2728 return extra_index + 2 * captures_len;
2729 }2729 }
27302730
2731 fn writeCapture(self: *Writer, stream: *std.io.Writer, capture: Zir.Inst.Capture) !void {2731 fn writeCapture(self: *Writer, stream: *std.Io.Writer, capture: Zir.Inst.Capture) !void {
2732 switch (capture.unwrap()) {2732 switch (capture.unwrap()) {
2733 .nested => |i| return stream.print("[{d}]", .{i}),2733 .nested => |i| return stream.print("[{d}]", .{i}),
2734 .instruction => |inst| return self.writeInstIndex(stream, inst),2734 .instruction => |inst| return self.writeInstIndex(stream, inst),
...@@ -2747,7 +2747,7 @@ const Writer = struct {...@@ -2747,7 +2747,7 @@ const Writer = struct {
27472747
2748 fn writeOptionalInstRef(2748 fn writeOptionalInstRef(
2749 self: *Writer,2749 self: *Writer,
2750 stream: *std.io.Writer,2750 stream: *std.Io.Writer,
2751 prefix: []const u8,2751 prefix: []const u8,
2752 inst: Zir.Inst.Ref,2752 inst: Zir.Inst.Ref,
2753 ) !void {2753 ) !void {
...@@ -2758,7 +2758,7 @@ const Writer = struct {...@@ -2758,7 +2758,7 @@ const Writer = struct {
27582758
2759 fn writeOptionalInstRefOrBody(2759 fn writeOptionalInstRefOrBody(
2760 self: *Writer,2760 self: *Writer,
2761 stream: *std.io.Writer,2761 stream: *std.Io.Writer,
2762 prefix: []const u8,2762 prefix: []const u8,
2763 ref: Zir.Inst.Ref,2763 ref: Zir.Inst.Ref,
2764 body: []const Zir.Inst.Index,2764 body: []const Zir.Inst.Index,
...@@ -2776,7 +2776,7 @@ const Writer = struct {...@@ -2776,7 +2776,7 @@ const Writer = struct {
27762776
2777 fn writeFlag(2777 fn writeFlag(
2778 self: *Writer,2778 self: *Writer,
2779 stream: *std.io.Writer,2779 stream: *std.Io.Writer,
2780 name: []const u8,2780 name: []const u8,
2781 flag: bool,2781 flag: bool,
2782 ) !void {2782 ) !void {
...@@ -2785,7 +2785,7 @@ const Writer = struct {...@@ -2785,7 +2785,7 @@ const Writer = struct {
2785 try stream.writeAll(name);2785 try stream.writeAll(name);
2786 }2786 }
27872787
2788 fn writeSrcNode(self: *Writer, stream: *std.io.Writer, src_node: Ast.Node.Offset) !void {2788 fn writeSrcNode(self: *Writer, stream: *std.Io.Writer, src_node: Ast.Node.Offset) !void {
2789 const tree = self.tree orelse return;2789 const tree = self.tree orelse return;
2790 const abs_node = src_node.toAbsolute(self.parent_decl_node);2790 const abs_node = src_node.toAbsolute(self.parent_decl_node);
2791 const src_span = tree.nodeToSpan(abs_node);2791 const src_span = tree.nodeToSpan(abs_node);
...@@ -2797,7 +2797,7 @@ const Writer = struct {...@@ -2797,7 +2797,7 @@ const Writer = struct {
2797 });2797 });
2798 }2798 }
27992799
2800 fn writeSrcTok(self: *Writer, stream: *std.io.Writer, src_tok: Ast.TokenOffset) !void {2800 fn writeSrcTok(self: *Writer, stream: *std.Io.Writer, src_tok: Ast.TokenOffset) !void {
2801 const tree = self.tree orelse return;2801 const tree = self.tree orelse return;
2802 const abs_tok = src_tok.toAbsolute(tree.firstToken(self.parent_decl_node));2802 const abs_tok = src_tok.toAbsolute(tree.firstToken(self.parent_decl_node));
2803 const span_start = tree.tokenStart(abs_tok);2803 const span_start = tree.tokenStart(abs_tok);
...@@ -2810,7 +2810,7 @@ const Writer = struct {...@@ -2810,7 +2810,7 @@ const Writer = struct {
2810 });2810 });
2811 }2811 }
28122812
2813 fn writeSrcTokAbs(self: *Writer, stream: *std.io.Writer, src_tok: Ast.TokenIndex) !void {2813 fn writeSrcTokAbs(self: *Writer, stream: *std.Io.Writer, src_tok: Ast.TokenIndex) !void {
2814 const tree = self.tree orelse return;2814 const tree = self.tree orelse return;
2815 const span_start = tree.tokenStart(src_tok);2815 const span_start = tree.tokenStart(src_tok);
2816 const span_end = span_start + @as(u32, @intCast(tree.tokenSlice(src_tok).len));2816 const span_end = span_start + @as(u32, @intCast(tree.tokenSlice(src_tok).len));
...@@ -2822,15 +2822,15 @@ const Writer = struct {...@@ -2822,15 +2822,15 @@ const Writer = struct {
2822 });2822 });
2823 }2823 }
28242824
2825 fn writeBracedDecl(self: *Writer, stream: *std.io.Writer, body: []const Zir.Inst.Index) !void {2825 fn writeBracedDecl(self: *Writer, stream: *std.Io.Writer, body: []const Zir.Inst.Index) !void {
2826 try self.writeBracedBodyConditional(stream, body, self.recurse_decls);2826 try self.writeBracedBodyConditional(stream, body, self.recurse_decls);
2827 }2827 }
28282828
2829 fn writeBracedBody(self: *Writer, stream: *std.io.Writer, body: []const Zir.Inst.Index) !void {2829 fn writeBracedBody(self: *Writer, stream: *std.Io.Writer, body: []const Zir.Inst.Index) !void {
2830 try self.writeBracedBodyConditional(stream, body, self.recurse_blocks);2830 try self.writeBracedBodyConditional(stream, body, self.recurse_blocks);
2831 }2831 }
28322832
2833 fn writeBracedBodyConditional(self: *Writer, stream: *std.io.Writer, body: []const Zir.Inst.Index, enabled: bool) !void {2833 fn writeBracedBodyConditional(self: *Writer, stream: *std.Io.Writer, body: []const Zir.Inst.Index, enabled: bool) !void {
2834 if (body.len == 0) {2834 if (body.len == 0) {
2835 try stream.writeAll("{}");2835 try stream.writeAll("{}");
2836 } else if (enabled) {2836 } else if (enabled) {
...@@ -2859,7 +2859,7 @@ const Writer = struct {...@@ -2859,7 +2859,7 @@ const Writer = struct {
2859 }2859 }
2860 }2860 }
28612861
2862 fn writeBody(self: *Writer, stream: *std.io.Writer, body: []const Zir.Inst.Index) !void {2862 fn writeBody(self: *Writer, stream: *std.Io.Writer, body: []const Zir.Inst.Index) !void {
2863 for (body) |inst| {2863 for (body) |inst| {
2864 try stream.splatByteAll(' ', self.indent);2864 try stream.splatByteAll(' ', self.indent);
2865 try stream.print("%{d} ", .{@intFromEnum(inst)});2865 try stream.print("%{d} ", .{@intFromEnum(inst)});
...@@ -2868,7 +2868,7 @@ const Writer = struct {...@@ -2868,7 +2868,7 @@ const Writer = struct {
2868 }2868 }
2869 }2869 }
28702870
2871 fn writeImport(self: *Writer, stream: *std.io.Writer, inst: Zir.Inst.Index) !void {2871 fn writeImport(self: *Writer, stream: *std.Io.Writer, inst: Zir.Inst.Index) !void {
2872 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_tok;2872 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_tok;
2873 const extra = self.code.extraData(Zir.Inst.Import, inst_data.payload_index).data;2873 const extra = self.code.extraData(Zir.Inst.Import, inst_data.payload_index).data;
2874 try self.writeInstRef(stream, extra.res_ty);2874 try self.writeInstRef(stream, extra.res_ty);
src/print_zoir.zig+1-1
...@@ -113,4 +113,4 @@ const std = @import("std");...@@ -113,4 +113,4 @@ const std = @import("std");
113const assert = std.debug.assert;113const assert = std.debug.assert;
114const Allocator = std.mem.Allocator;114const Allocator = std.mem.Allocator;
115const Zoir = std.zig.Zoir;115const Zoir = std.zig.Zoir;
116const Writer = std.io.Writer;116const Writer = std.Io.Writer;
test/src/Cases.zig+1-1
...@@ -386,7 +386,7 @@ fn addFromDirInner(...@@ -386,7 +386,7 @@ fn addFromDirInner(
386 current_file.* = filename;386 current_file.* = filename;
387387
388 const max_file_size = 10 * 1024 * 1024;388 const max_file_size = 10 * 1024 * 1024;
389 const src = try iterable_dir.readFileAllocOptions(ctx.arena, filename, max_file_size, null, .@"1", 0);389 const src = try iterable_dir.readFileAllocOptions(filename, ctx.arena, .limited(max_file_size), .@"1", 0);
390390
391 // Parse the manifest391 // Parse the manifest
392 var manifest = try TestManifest.parse(ctx.arena, src);392 var manifest = try TestManifest.parse(ctx.arena, src);
test/src/check-stack-trace.zig+1-1
...@@ -13,7 +13,7 @@ pub fn main() !void {...@@ -13,7 +13,7 @@ pub fn main() !void {
13 const input_path = args[1];13 const input_path = args[1];
14 const optimize_mode_text = args[2];14 const optimize_mode_text = args[2];
1515
16 const input_bytes = try std.fs.cwd().readFileAlloc(arena, input_path, 5 * 1024 * 1024);16 const input_bytes = try std.fs.cwd().readFileAlloc(input_path, arena, .limited(5 * 1024 * 1024));
17 const optimize_mode = std.meta.stringToEnum(std.builtin.OptimizeMode, optimize_mode_text).?;17 const optimize_mode = std.meta.stringToEnum(std.builtin.OptimizeMode, optimize_mode_text).?;
1818
19 var stderr = input_bytes;19 var stderr = input_bytes;
test/standalone/child_process/main.zig+2-1
...@@ -32,7 +32,8 @@ pub fn main() !void {...@@ -32,7 +32,8 @@ pub fn main() !void {
3232
33 const hello_stdout = "hello from stdout";33 const hello_stdout = "hello from stdout";
34 var buf: [hello_stdout.len]u8 = undefined;34 var buf: [hello_stdout.len]u8 = undefined;
35 const n = try child.stdout.?.deprecatedReader().readAll(&buf);35 var stdout_reader = child.stdout.?.readerStreaming(&.{});
36 const n = try stdout_reader.interface.readSliceShort(&buf);
36 if (!std.mem.eql(u8, buf[0..n], hello_stdout)) {37 if (!std.mem.eql(u8, buf[0..n], hello_stdout)) {
37 testError("child stdout: '{s}'; want '{s}'", .{ buf[0..n], hello_stdout });38 testError("child stdout: '{s}'; want '{s}'", .{ buf[0..n], hello_stdout });
38 }39 }
test/standalone/cmakedefine/check.zig+2-2
...@@ -9,8 +9,8 @@ pub fn main() !void {...@@ -9,8 +9,8 @@ pub fn main() !void {
9 const actual_path = args[1];9 const actual_path = args[1];
10 const expected_path = args[2];10 const expected_path = args[2];
1111
12 const actual = try std.fs.cwd().readFileAlloc(arena, actual_path, 1024 * 1024);12 const actual = try std.fs.cwd().readFileAlloc(actual_path, arena, .limited(1024 * 1024));
13 const expected = try std.fs.cwd().readFileAlloc(arena, expected_path, 1024 * 1024);13 const expected = try std.fs.cwd().readFileAlloc(expected_path, arena, .limited(1024 * 1024));
1414
15 // The actual output starts with a comment which we should strip out before comparing.15 // The actual output starts with a comment which we should strip out before comparing.
16 const comment_str = "/* This file was generated by ConfigHeader using the Zig Build System. */\n";16 const comment_str = "/* This file was generated by ConfigHeader using the Zig Build System. */\n";
test/standalone/entry_point/check_differ.zig+2-2
...@@ -6,8 +6,8 @@ pub fn main() !void {...@@ -6,8 +6,8 @@ pub fn main() !void {
6 const args = try std.process.argsAlloc(arena);6 const args = try std.process.argsAlloc(arena);
7 if (args.len != 3) return error.BadUsage; // usage: 'check_differ <path a> <path b>'7 if (args.len != 3) return error.BadUsage; // usage: 'check_differ <path a> <path b>'
88
9 const contents_1 = try std.fs.cwd().readFileAlloc(arena, args[1], 1024 * 1024 * 64); // 64 MiB ought to be plenty9 const contents_1 = try std.fs.cwd().readFileAlloc(args[1], arena, .limited(1024 * 1024 * 64)); // 64 MiB ought to be plenty
10 const contents_2 = try std.fs.cwd().readFileAlloc(arena, args[2], 1024 * 1024 * 64); // 64 MiB ought to be plenty10 const contents_2 = try std.fs.cwd().readFileAlloc(args[2], arena, .limited(1024 * 1024 * 64)); // 64 MiB ought to be plenty
1111
12 if (std.mem.eql(u8, contents_1, contents_2)) {12 if (std.mem.eql(u8, contents_1, contents_2)) {
13 return error.FilesMatch;13 return error.FilesMatch;
test/standalone/simple/cat/main.zig+1-2
...@@ -1,5 +1,4 @@...@@ -1,5 +1,4 @@
1const std = @import("std");1const std = @import("std");
2const io = std.io;
3const fs = std.fs;2const fs = std.fs;
4const mem = std.mem;3const mem = std.mem;
5const warn = std.log.warn;4const warn = std.log.warn;
...@@ -16,7 +15,7 @@ pub fn main() !void {...@@ -16,7 +15,7 @@ pub fn main() !void {
16 var catted_anything = false;15 var catted_anything = false;
17 var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});16 var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
18 const stdout = &stdout_writer.interface;17 const stdout = &stdout_writer.interface;
19 var stdin_reader = std.fs.File.stdin().reader(&.{});18 var stdin_reader = std.fs.File.stdin().readerStreaming(&.{});
2019
21 const cwd = fs.cwd();20 const cwd = fs.cwd();
2221
tools/docgen.zig+4-5
...@@ -77,7 +77,8 @@ pub fn main() !void {...@@ -77,7 +77,8 @@ pub fn main() !void {
77 var code_dir = try fs.cwd().openDir(code_dir_path, .{});77 var code_dir = try fs.cwd().openDir(code_dir_path, .{});
78 defer code_dir.close();78 defer code_dir.close();
7979
80 const input_file_bytes = try in_file.deprecatedReader().readAllAlloc(arena, max_doc_file_size);80 var in_file_reader = in_file.reader(&.{});
81 const input_file_bytes = try in_file_reader.interface.allocRemaining(arena, .limited(max_doc_file_size));
8182
82 var tokenizer = Tokenizer.init(input_path, input_file_bytes);83 var tokenizer = Tokenizer.init(input_path, input_file_bytes);
83 var toc = try genToc(arena, &tokenizer);84 var toc = try genToc(arena, &tokenizer);
...@@ -1039,10 +1040,8 @@ fn genHtml(...@@ -1039,10 +1040,8 @@ fn genHtml(
1039 });1040 });
1040 defer allocator.free(out_basename);1041 defer allocator.free(out_basename);
10411042
1042 const contents = code_dir.readFileAlloc(allocator, out_basename, std.math.maxInt(u32)) catch |err| {1043 const contents = code_dir.readFileAlloc(out_basename, allocator, .limited(std.math.maxInt(u32))) catch |err| {
1043 return parseError(tokenizer, code.token, "unable to open '{s}': {s}", .{1044 return parseError(tokenizer, code.token, "unable to open '{s}': {t}", .{ out_basename, err });
1044 out_basename, @errorName(err),
1045 });
1046 };1045 };
1047 defer allocator.free(contents);1046 defer allocator.free(contents);
10481047
tools/doctest.zig+1-1
...@@ -70,7 +70,7 @@ pub fn main() !void {...@@ -70,7 +70,7 @@ pub fn main() !void {
70 const zig_path = opt_zig orelse fatal("missing zig compiler path (--zig)", .{});70 const zig_path = opt_zig orelse fatal("missing zig compiler path (--zig)", .{});
71 const cache_root = opt_cache_root orelse fatal("missing cache root path (--cache-root)", .{});71 const cache_root = opt_cache_root orelse fatal("missing cache root path (--cache-root)", .{});
7272
73 const source_bytes = try fs.cwd().readFileAlloc(arena, input_path, std.math.maxInt(u32));73 const source_bytes = try fs.cwd().readFileAlloc(input_path, arena, .limited(std.math.maxInt(u32)));
74 const code = try parseManifest(arena, source_bytes);74 const code = try parseManifest(arena, source_bytes);
75 const source = stripManifest(source_bytes);75 const source = stripManifest(source_bytes);
7676
tools/dump-cov.zig+2-3
...@@ -38,10 +38,9 @@ pub fn main() !void {...@@ -38,10 +38,9 @@ pub fn main() !void {
38 defer debug_info.deinit(gpa);38 defer debug_info.deinit(gpa);
3939
40 const cov_bytes = cov_path.root_dir.handle.readFileAllocOptions(40 const cov_bytes = cov_path.root_dir.handle.readFileAllocOptions(
41 arena,
42 cov_path.sub_path,41 cov_path.sub_path,
43 1 << 30,42 arena,
44 null,43 .limited(1 << 30),
45 .of(SeenPcsHeader),44 .of(SeenPcsHeader),
46 null,45 null,
47 ) catch |err| {46 ) catch |err| {
tools/fetch_them_macos_headers.zig+3-3
...@@ -1,6 +1,5 @@...@@ -1,6 +1,5 @@
1const std = @import("std");1const std = @import("std");
2const fs = std.fs;2const fs = std.fs;
3const io = std.io;
4const mem = std.mem;3const mem = std.mem;
5const process = std.process;4const process = std.process;
6const assert = std.debug.assert;5const assert = std.debug.assert;
...@@ -93,7 +92,7 @@ pub fn main() anyerror!void {...@@ -93,7 +92,7 @@ pub fn main() anyerror!void {
9392
94 var sdk_dir = try std.fs.cwd().openDir(sysroot_path, .{});93 var sdk_dir = try std.fs.cwd().openDir(sysroot_path, .{});
95 defer sdk_dir.close();94 defer sdk_dir.close();
96 const sdk_info = try sdk_dir.readFileAlloc(allocator, "SDKSettings.json", std.math.maxInt(u32));95 const sdk_info = try sdk_dir.readFileAlloc("SDKSettings.json", allocator, .limited(std.math.maxInt(u32)));
9796
98 const parsed_json = try std.json.parseFromSlice(struct {97 const parsed_json = try std.json.parseFromSlice(struct {
99 DefaultProperties: struct { MACOSX_DEPLOYMENT_TARGET: []const u8 },98 DefaultProperties: struct { MACOSX_DEPLOYMENT_TARGET: []const u8 },
...@@ -198,7 +197,8 @@ fn fetchTarget(...@@ -198,7 +197,8 @@ fn fetchTarget(
198 var dirs = std.StringHashMap(fs.Dir).init(arena);197 var dirs = std.StringHashMap(fs.Dir).init(arena);
199 try dirs.putNoClobber(".", dest_dir);198 try dirs.putNoClobber(".", dest_dir);
200199
201 const headers_list_str = try headers_list_file.deprecatedReader().readAllAlloc(arena, std.math.maxInt(usize));200 var headers_list_file_reader = headers_list_file.reader(&.{});
201 const headers_list_str = try headers_list_file_reader.interface.allocRemaining(arena, .unlimited);
202 const prefix = "/usr/include";202 const prefix = "/usr/include";
203203
204 var it = mem.splitScalar(u8, headers_list_str, '\n');204 var it = mem.splitScalar(u8, headers_list_str, '\n');
tools/gen_spirv_spec.zig+15-15
...@@ -136,7 +136,7 @@ fn readExtRegistry(exts: *std.array_list.Managed(Extension), dir: std.fs.Dir, su...@@ -136,7 +136,7 @@ fn readExtRegistry(exts: *std.array_list.Managed(Extension), dir: std.fs.Dir, su
136}136}
137137
138fn readRegistry(comptime RegistryType: type, dir: std.fs.Dir, path: []const u8) !RegistryType {138fn readRegistry(comptime RegistryType: type, dir: std.fs.Dir, path: []const u8) !RegistryType {
139 const spec = try dir.readFileAlloc(allocator, path, std.math.maxInt(usize));139 const spec = try dir.readFileAlloc(path, allocator, .unlimited);
140 // Required for json parsing.140 // Required for json parsing.
141 // TODO: ALI141 // TODO: ALI
142 @setEvalBranchQuota(10000);142 @setEvalBranchQuota(10000);
...@@ -189,7 +189,7 @@ fn tagPriorityScore(tag: []const u8) usize {...@@ -189,7 +189,7 @@ fn tagPriorityScore(tag: []const u8) usize {
189}189}
190190
191fn render(191fn render(
192 writer: *std.io.Writer,192 writer: *std.Io.Writer,
193 registry: CoreRegistry,193 registry: CoreRegistry,
194 extensions: []const Extension,194 extensions: []const Extension,
195) !void {195) !void {
...@@ -214,7 +214,7 @@ fn render(...@@ -214,7 +214,7 @@ fn render(
214 \\ none,214 \\ none,
215 \\ _,215 \\ _,
216 \\216 \\
217 \\ pub fn format(self: Id, writer: *std.io.Writer) std.io.Writer.Error!void {217 \\ pub fn format(self: Id, writer: *std.Io.Writer) std.Io.Writer.Error!void {
218 \\ switch (self) {218 \\ switch (self) {
219 \\ .none => try writer.writeAll("(none)"),219 \\ .none => try writer.writeAll("(none)"),
220 \\ else => try writer.print("%{d}", .{@intFromEnum(self)}),220 \\ else => try writer.print("%{d}", .{@intFromEnum(self)}),
...@@ -327,7 +327,7 @@ fn render(...@@ -327,7 +327,7 @@ fn render(
327}327}
328328
329fn renderInstructionSet(329fn renderInstructionSet(
330 writer: *std.io.Writer,330 writer: *std.Io.Writer,
331 core: CoreRegistry,331 core: CoreRegistry,
332 extensions: []const Extension,332 extensions: []const Extension,
333 all_operand_kinds: OperandKindMap,333 all_operand_kinds: OperandKindMap,
...@@ -362,7 +362,7 @@ fn renderInstructionSet(...@@ -362,7 +362,7 @@ fn renderInstructionSet(
362}362}
363363
364fn renderInstructionsCase(364fn renderInstructionsCase(
365 writer: *std.io.Writer,365 writer: *std.Io.Writer,
366 set_name: []const u8,366 set_name: []const u8,
367 instructions: []const Instruction,367 instructions: []const Instruction,
368 all_operand_kinds: OperandKindMap,368 all_operand_kinds: OperandKindMap,
...@@ -409,7 +409,7 @@ fn renderInstructionsCase(...@@ -409,7 +409,7 @@ fn renderInstructionsCase(
409 );409 );
410}410}
411411
412fn renderClass(writer: *std.io.Writer, instructions: []const Instruction) !void {412fn renderClass(writer: *std.Io.Writer, instructions: []const Instruction) !void {
413 var class_map = std.StringArrayHashMap(void).init(allocator);413 var class_map = std.StringArrayHashMap(void).init(allocator);
414414
415 for (instructions) |inst| {415 for (instructions) |inst| {
...@@ -427,7 +427,7 @@ fn renderClass(writer: *std.io.Writer, instructions: []const Instruction) !void...@@ -427,7 +427,7 @@ fn renderClass(writer: *std.io.Writer, instructions: []const Instruction) !void
427const Formatter = struct {427const Formatter = struct {
428 data: []const u8,428 data: []const u8,
429429
430 fn format(f: Formatter, writer: *std.Io.Writer) std.io.Writer.Error!void {430 fn format(f: Formatter, writer: *std.Io.Writer) std.Io.Writer.Error!void {
431 var id_buf: [128]u8 = undefined;431 var id_buf: [128]u8 = undefined;
432 var fw: std.Io.Writer = .fixed(&id_buf);432 var fw: std.Io.Writer = .fixed(&id_buf);
433 for (f.data, 0..) |c, i| {433 for (f.data, 0..) |c, i| {
...@@ -457,7 +457,7 @@ fn formatId(identifier: []const u8) std.fmt.Alt(Formatter, Formatter.format) {...@@ -457,7 +457,7 @@ fn formatId(identifier: []const u8) std.fmt.Alt(Formatter, Formatter.format) {
457 return .{ .data = .{ .data = identifier } };457 return .{ .data = .{ .data = identifier } };
458}458}
459459
460fn renderOperandKind(writer: *std.io.Writer, operands: []const OperandKind) !void {460fn renderOperandKind(writer: *std.Io.Writer, operands: []const OperandKind) !void {
461 try writer.writeAll(461 try writer.writeAll(
462 \\pub const OperandKind = enum {462 \\pub const OperandKind = enum {
463 \\ opcode,463 \\ opcode,
...@@ -513,7 +513,7 @@ fn renderOperandKind(writer: *std.io.Writer, operands: []const OperandKind) !voi...@@ -513,7 +513,7 @@ fn renderOperandKind(writer: *std.io.Writer, operands: []const OperandKind) !voi
513 try writer.writeAll("};\n}\n};\n");513 try writer.writeAll("};\n}\n};\n");
514}514}
515515
516fn renderEnumerant(writer: *std.io.Writer, enumerant: Enumerant) !void {516fn renderEnumerant(writer: *std.Io.Writer, enumerant: Enumerant) !void {
517 try writer.print(".{{.name = \"{s}\", .value = ", .{enumerant.enumerant});517 try writer.print(".{{.name = \"{s}\", .value = ", .{enumerant.enumerant});
518 switch (enumerant.value) {518 switch (enumerant.value) {
519 .bitflag => |flag| try writer.writeAll(flag),519 .bitflag => |flag| try writer.writeAll(flag),
...@@ -530,7 +530,7 @@ fn renderEnumerant(writer: *std.io.Writer, enumerant: Enumerant) !void {...@@ -530,7 +530,7 @@ fn renderEnumerant(writer: *std.io.Writer, enumerant: Enumerant) !void {
530}530}
531531
532fn renderOpcodes(532fn renderOpcodes(
533 writer: *std.io.Writer,533 writer: *std.Io.Writer,
534 opcode_type_name: []const u8,534 opcode_type_name: []const u8,
535 want_operands: bool,535 want_operands: bool,
536 instructions: []const Instruction,536 instructions: []const Instruction,
...@@ -629,7 +629,7 @@ fn renderOpcodes(...@@ -629,7 +629,7 @@ fn renderOpcodes(
629}629}
630630
631fn renderOperandKinds(631fn renderOperandKinds(
632 writer: *std.io.Writer,632 writer: *std.Io.Writer,
633 kinds: []const OperandKind,633 kinds: []const OperandKind,
634 extended_structs: ExtendedStructSet,634 extended_structs: ExtendedStructSet,
635) !void {635) !void {
...@@ -643,7 +643,7 @@ fn renderOperandKinds(...@@ -643,7 +643,7 @@ fn renderOperandKinds(
643}643}
644644
645fn renderValueEnum(645fn renderValueEnum(
646 writer: *std.io.Writer,646 writer: *std.Io.Writer,
647 enumeration: OperandKind,647 enumeration: OperandKind,
648 extended_structs: ExtendedStructSet,648 extended_structs: ExtendedStructSet,
649) !void {649) !void {
...@@ -721,7 +721,7 @@ fn renderValueEnum(...@@ -721,7 +721,7 @@ fn renderValueEnum(
721}721}
722722
723fn renderBitEnum(723fn renderBitEnum(
724 writer: *std.io.Writer,724 writer: *std.Io.Writer,
725 enumeration: OperandKind,725 enumeration: OperandKind,
726 extended_structs: ExtendedStructSet,726 extended_structs: ExtendedStructSet,
727) !void {727) !void {
...@@ -804,7 +804,7 @@ fn renderBitEnum(...@@ -804,7 +804,7 @@ fn renderBitEnum(
804}804}
805805
806fn renderOperand(806fn renderOperand(
807 writer: *std.io.Writer,807 writer: *std.Io.Writer,
808 kind: enum {808 kind: enum {
809 @"union",809 @"union",
810 instruction,810 instruction,
...@@ -888,7 +888,7 @@ fn renderOperand(...@@ -888,7 +888,7 @@ fn renderOperand(
888 try writer.writeAll(",\n");888 try writer.writeAll(",\n");
889}889}
890890
891fn renderFieldName(writer: *std.io.Writer, operands: []const Operand, field_index: usize) !void {891fn renderFieldName(writer: *std.Io.Writer, operands: []const Operand, field_index: usize) !void {
892 const operand = operands[field_index];892 const operand = operands[field_index];
893893
894 derive_from_kind: {894 derive_from_kind: {
tools/gen_stubs.zig+2-3
...@@ -299,10 +299,9 @@ pub fn main() !void {...@@ -299,10 +299,9 @@ pub fn main() !void {
299299
300 // Read the ELF header.300 // Read the ELF header.
301 const elf_bytes = build_all_dir.readFileAllocOptions(301 const elf_bytes = build_all_dir.readFileAllocOptions(
302 arena,
303 libc_so_path,302 libc_so_path,
304 100 * 1024 * 1024,303 arena,
305 1 * 1024 * 1024,304 .limited(100 * 1024 * 1024),
306 .of(elf.Elf64_Ehdr),305 .of(elf.Elf64_Ehdr),
307 null,306 null,
308 ) catch |err| {307 ) catch |err| {
tools/generate_JSONTestSuite.zig+1-1
...@@ -32,7 +32,7 @@ pub fn main() !void {...@@ -32,7 +32,7 @@ pub fn main() !void {
32 }).lessThan);32 }).lessThan);
3333
34 for (names.items) |name| {34 for (names.items) |name| {
35 const contents = try std.fs.cwd().readFileAlloc(allocator, name, 250001);35 const contents = try std.fs.cwd().readFileAlloc(name, allocator, .limited(250001));
36 try output.writeAll("test ");36 try output.writeAll("test ");
37 try writeString(output, name);37 try writeString(output, name);
38 try output.writeAll(" {\n try ");38 try output.writeAll(" {\n try ");
tools/generate_linux_syscalls.zig+1-1
...@@ -248,7 +248,7 @@ pub fn main() !void {...@@ -248,7 +248,7 @@ pub fn main() !void {
248 try Io.Writer.flush(stdout);248 try Io.Writer.flush(stdout);
249}249}
250250
251fn usage(w: *std.io.Writer, arg0: []const u8) std.io.Writer.Error!void {251fn usage(w: *std.Io.Writer, arg0: []const u8) std.Io.Writer.Error!void {
252 try w.print(252 try w.print(
253 \\Usage: {s} /path/to/zig /path/to/linux253 \\Usage: {s} /path/to/zig /path/to/linux
254 \\Alternative Usage: zig run /path/to/git/zig/tools/generate_linux_syscalls.zig -- /path/to/zig /path/to/linux254 \\Alternative Usage: zig run /path/to/git/zig/tools/generate_linux_syscalls.zig -- /path/to/zig /path/to/linux
tools/incr-check.zig+2-2
...@@ -52,7 +52,7 @@ pub fn main() !void {...@@ -52,7 +52,7 @@ pub fn main() !void {
52 const zig_exe = opt_zig_exe orelse fatal("missing path to zig\n{s}", .{usage});52 const zig_exe = opt_zig_exe orelse fatal("missing path to zig\n{s}", .{usage});
53 const input_file_name = opt_input_file_name orelse fatal("missing input file\n{s}", .{usage});53 const input_file_name = opt_input_file_name orelse fatal("missing input file\n{s}", .{usage});
5454
55 const input_file_bytes = try std.fs.cwd().readFileAlloc(arena, input_file_name, std.math.maxInt(u32));55 const input_file_bytes = try std.fs.cwd().readFileAlloc(input_file_name, arena, .limited(std.math.maxInt(u32)));
56 const case = try Case.parse(arena, input_file_bytes);56 const case = try Case.parse(arena, input_file_bytes);
5757
58 // Check now: if there are any targets using the `cbe` backend, we need the lib dir.58 // Check now: if there are any targets using the `cbe` backend, we need the lib dir.
...@@ -226,7 +226,7 @@ const Eval = struct {...@@ -226,7 +226,7 @@ const Eval = struct {
226 cc_child_args: *std.ArrayListUnmanaged([]const u8),226 cc_child_args: *std.ArrayListUnmanaged([]const u8),
227227
228 const StreamEnum = enum { stdout, stderr };228 const StreamEnum = enum { stdout, stderr };
229 const Poller = std.io.Poller(StreamEnum);229 const Poller = std.Io.Poller(StreamEnum);
230230
231 /// Currently this function assumes the previous updates have already been written.231 /// Currently this function assumes the previous updates have already been written.
232 fn write(eval: *Eval, update: Case.Update) void {232 fn write(eval: *Eval, update: Case.Update) void {
tools/migrate_langref.zig+2-2
...@@ -1,6 +1,5 @@...@@ -1,6 +1,5 @@
1const std = @import("std");1const std = @import("std");
2const builtin = @import("builtin");2const builtin = @import("builtin");
3const io = std.io;
4const fs = std.fs;3const fs = std.fs;
5const print = std.debug.print;4const print = std.debug.print;
6const mem = std.mem;5const mem = std.mem;
...@@ -29,7 +28,8 @@ pub fn main() !void {...@@ -29,7 +28,8 @@ pub fn main() !void {
29 var out_dir = try fs.cwd().openDir(fs.path.dirname(output_file).?, .{});28 var out_dir = try fs.cwd().openDir(fs.path.dirname(output_file).?, .{});
30 defer out_dir.close();29 defer out_dir.close();
3130
32 const input_file_bytes = try in_file.deprecatedReader().readAllAlloc(arena, std.math.maxInt(u32));31 var in_file_reader = in_file.reader(&.{});
32 const input_file_bytes = try in_file_reader.interface.allocRemaining(arena, .unlimited);
3333
34 var tokenizer = Tokenizer.init(input_file, input_file_bytes);34 var tokenizer = Tokenizer.init(input_file, input_file_bytes);
3535
tools/process_headers.zig+1-1
...@@ -254,7 +254,7 @@ pub fn main() !void {...@@ -254,7 +254,7 @@ pub fn main() !void {
254 .file, .sym_link => {254 .file, .sym_link => {
255 const rel_path = try std.fs.path.relative(allocator, target_include_dir, full_path);255 const rel_path = try std.fs.path.relative(allocator, target_include_dir, full_path);
256 const max_size = 2 * 1024 * 1024 * 1024;256 const max_size = 2 * 1024 * 1024 * 1024;
257 const raw_bytes = try std.fs.cwd().readFileAlloc(allocator, full_path, max_size);257 const raw_bytes = try std.fs.cwd().readFileAlloc(full_path, allocator, .limited(max_size));
258 const trimmed = std.mem.trim(u8, raw_bytes, " \r\n\t");258 const trimmed = std.mem.trim(u8, raw_bytes, " \r\n\t");
259 total_bytes += raw_bytes.len;259 total_bytes += raw_bytes.len;
260 const hash = try allocator.alloc(u8, 32);260 const hash = try allocator.alloc(u8, 32);
tools/update-linux-headers.zig+1-1
...@@ -206,7 +206,7 @@ pub fn main() !void {...@@ -206,7 +206,7 @@ pub fn main() !void {
206 .file => {206 .file => {
207 const rel_path = try std.fs.path.relative(arena, target_include_dir, full_path);207 const rel_path = try std.fs.path.relative(arena, target_include_dir, full_path);
208 const max_size = 2 * 1024 * 1024 * 1024;208 const max_size = 2 * 1024 * 1024 * 1024;
209 const raw_bytes = try std.fs.cwd().readFileAlloc(arena, full_path, max_size);209 const raw_bytes = try std.fs.cwd().readFileAlloc(full_path, arena, .limited(max_size));
210 const trimmed = std.mem.trim(u8, raw_bytes, " \r\n\t");210 const trimmed = std.mem.trim(u8, raw_bytes, " \r\n\t");
211 total_bytes += raw_bytes.len;211 total_bytes += raw_bytes.len;
212 const hash = try arena.alloc(u8, 32);212 const hash = try arena.alloc(u8, 32);
tools/update_clang_options.zig+1-1
...@@ -965,7 +965,7 @@ fn printUsageAndExit(arg0: []const u8) noreturn {...@@ -965,7 +965,7 @@ fn printUsageAndExit(arg0: []const u8) noreturn {
965 std.process.exit(1);965 std.process.exit(1);
966}966}
967967
968fn printUsage(w: *std.io.Writer, arg0: []const u8) std.io.Writer.Error!void {968fn printUsage(w: *std.Io.Writer, arg0: []const u8) std.Io.Writer.Error!void {
969 try w.print(969 try w.print(
970 \\Usage: {s} /path/to/llvm-tblgen /path/to/git/llvm/llvm-project970 \\Usage: {s} /path/to/llvm-tblgen /path/to/git/llvm/llvm-project
971 \\Alternative Usage: zig run /path/to/git/zig/tools/update_clang_options.zig -- /path/to/llvm-tblgen /path/to/git/llvm/llvm-project971 \\Alternative Usage: zig run /path/to/git/zig/tools/update_clang_options.zig -- /path/to/llvm-tblgen /path/to/git/llvm/llvm-project
tools/update_crc_catalog.zig+1-1
...@@ -194,7 +194,7 @@ fn printUsageAndExit(arg0: []const u8) noreturn {...@@ -194,7 +194,7 @@ fn printUsageAndExit(arg0: []const u8) noreturn {
194 std.process.exit(1);194 std.process.exit(1);
195}195}
196196
197fn printUsage(w: *std.io.Writer, arg0: []const u8) std.io.Writer.Error!void {197fn printUsage(w: *std.Io.Writer, arg0: []const u8) std.Io.Writer.Error!void {
198 return w.print(198 return w.print(
199 \\Usage: {s} /path/git/zig199 \\Usage: {s} /path/git/zig
200 \\200 \\
tools/update_glibc.zig+4-4
...@@ -116,9 +116,9 @@ pub fn main() !void {...@@ -116,9 +116,9 @@ pub fn main() !void {
116 const max_file_size = 10 * 1024 * 1024;116 const max_file_size = 10 * 1024 * 1024;
117117
118 const generic_glibc_contents = generic_glibc_dir.readFileAlloc(118 const generic_glibc_contents = generic_glibc_dir.readFileAlloc(
119 arena,
120 entry.path,119 entry.path,
121 max_file_size,120 arena,
121 .limited(max_file_size),
122 ) catch |err| switch (err) {122 ) catch |err| switch (err) {
123 error.FileNotFound => continue,123 error.FileNotFound => continue,
124 else => |e| fatal("unable to load '{s}/include/{s}': {s}", .{124 else => |e| fatal("unable to load '{s}/include/{s}': {s}", .{
...@@ -126,9 +126,9 @@ pub fn main() !void {...@@ -126,9 +126,9 @@ pub fn main() !void {
126 }),126 }),
127 };127 };
128 const glibc_include_contents = include_dir.readFileAlloc(128 const glibc_include_contents = include_dir.readFileAlloc(
129 arena,
130 entry.path,129 entry.path,
131 max_file_size,130 arena,
131 .limited(max_file_size),
132 ) catch |err| {132 ) catch |err| {
133 fatal("unable to load '{s}/include/{s}': {s}", .{133 fatal("unable to load '{s}/include/{s}': {s}", .{
134 dest_dir_path, entry.path, @errorName(err),134 dest_dir_path, entry.path, @errorName(err),