authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-08-07 23:09:40-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-08-28 18:30:57-07:00
log57dbc9e74a3f19802e4592f35061f1524c218a8f
tree02adaff978e089c10fdccc46564ad3393a1a0391
parent5cb8cdef1026f0b5d1c18cc5d5e6525cddf65d67

std.Io: delete GenericWriter


17 files changed, 35 insertions(+), 644 deletions(-)

lib/std/Build/Step/CheckObject.zig+25-27
......@@ -257,7 +257,7 @@ const Check = struct {
257257 fn dumpSection(allocator: Allocator, name: [:0]const u8) Check {
258258 var check = Check.create(allocator, .dump_section);
259259 const off: u32 = @intCast(check.data.items.len);
260 check.data.writer().print("{s}\x00", .{name}) catch @panic("OOM");
260 check.data.print("{s}\x00", .{name}) catch @panic("OOM");
261261 check.payload = .{ .dump_section = off };
262262 return check;
263263 }
......@@ -1320,7 +1320,8 @@ const MachODumper = struct {
13201320 }
13211321 bindings.deinit();
13221322 }
1323 try ctx.parseBindInfo(data, &bindings);
1323 var data_reader: std.Io.Reader = .fixed(data);
1324 try ctx.parseBindInfo(&data_reader, &bindings);
13241325 mem.sort(Binding, bindings.items, {}, Binding.lessThan);
13251326 for (bindings.items) |binding| {
13261327 try writer.print("0x{x} [addend: {d}]", .{ binding.address, binding.addend });
......@@ -1335,11 +1336,7 @@ const MachODumper = struct {
13351336 }
13361337 }
13371338
1338 fn parseBindInfo(ctx: ObjectContext, data: []const u8, bindings: *std.array_list.Managed(Binding)) !void {
1339 var stream = std.io.fixedBufferStream(data);
1340 var creader = std.io.countingReader(stream.reader());
1341 const reader = creader.reader();
1342
1339 fn parseBindInfo(ctx: ObjectContext, reader: *std.Io.Reader, bindings: *std.array_list.Managed(Binding)) !void {
13431340 var seg_id: ?u8 = null;
13441341 var tag: Binding.Tag = .self;
13451342 var ordinal: u16 = 0;
......@@ -1350,7 +1347,7 @@ const MachODumper = struct {
13501347 defer name_buf.deinit();
13511348
13521349 while (true) {
1353 const byte = reader.readByte() catch break;
1350 const byte = reader.takeByte() catch break;
13541351 const opc = byte & macho.BIND_OPCODE_MASK;
13551352 const imm = byte & macho.BIND_IMMEDIATE_MASK;
13561353 switch (opc) {
......@@ -1371,18 +1368,17 @@ const MachODumper = struct {
13711368 },
13721369 macho.BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB => {
13731370 seg_id = imm;
1374 offset = try std.leb.readUleb128(u64, reader);
1371 offset = try reader.takeLeb128(u64);
13751372 },
13761373 macho.BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM => {
13771374 name_buf.clearRetainingCapacity();
1378 try reader.readUntilDelimiterArrayList(&name_buf, 0, std.math.maxInt(u32));
1379 try name_buf.append(0);
1375 try name_buf.appendSlice(try reader.takeDelimiterInclusive(0));
13801376 },
13811377 macho.BIND_OPCODE_SET_ADDEND_SLEB => {
1382 addend = try std.leb.readIleb128(i64, reader);
1378 addend = try reader.takeLeb128(i64);
13831379 },
13841380 macho.BIND_OPCODE_ADD_ADDR_ULEB => {
1385 const x = try std.leb.readUleb128(u64, reader);
1381 const x = try reader.takeLeb128(u64);
13861382 offset = @intCast(@as(i64, @intCast(offset)) + @as(i64, @bitCast(x)));
13871383 },
13881384 macho.BIND_OPCODE_DO_BIND,
......@@ -1397,14 +1393,14 @@ const MachODumper = struct {
13971393 switch (opc) {
13981394 macho.BIND_OPCODE_DO_BIND => {},
13991395 macho.BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB => {
1400 add_addr = try std.leb.readUleb128(u64, reader);
1396 add_addr = try reader.takeLeb128(u64);
14011397 },
14021398 macho.BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED => {
14031399 add_addr = imm * @sizeOf(u64);
14041400 },
14051401 macho.BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB => {
1406 count = try std.leb.readUleb128(u64, reader);
1407 skip = try std.leb.readUleb128(u64, reader);
1402 count = try reader.takeLeb128(u64);
1403 skip = try reader.takeLeb128(u64);
14081404 },
14091405 else => unreachable,
14101406 }
......@@ -1621,8 +1617,9 @@ const MachODumper = struct {
16211617 var ctx = ObjectContext{ .gpa = gpa, .data = bytes, .header = hdr };
16221618 try ctx.parse();
16231619
1624 var output = std.array_list.Managed(u8).init(gpa);
1625 const writer = output.writer();
1620 var output: std.Io.Writer.Allocating = .init(gpa);
1621 defer output.deinit();
1622 const writer = &output.writer;
16261623
16271624 switch (check.kind) {
16281625 .headers => {
......@@ -1787,8 +1784,9 @@ const ElfDumper = struct {
17871784 try ctx.objects.append(gpa, .{ .name = name, .off = stream.pos, .len = size });
17881785 }
17891786
1790 var output = std.array_list.Managed(u8).init(gpa);
1791 const writer = output.writer();
1787 var output: std.Io.Writer.Allocating = .init(gpa);
1788 defer output.deinit();
1789 const writer = &output.writer;
17921790
17931791 switch (check.kind) {
17941792 .archive_symtab => if (ctx.symtab.items.len > 0) {
......@@ -1944,8 +1942,9 @@ const ElfDumper = struct {
19441942 else => {},
19451943 };
19461944
1947 var output = std.array_list.Managed(u8).init(gpa);
1948 const writer = output.writer();
1945 var output: std.Io.Writer.Allocating = .init(gpa);
1946 defer output.deinit();
1947 const writer = &output.writer;
19491948
19501949 switch (check.kind) {
19511950 .headers => {
......@@ -2398,10 +2397,10 @@ const WasmDumper = struct {
23982397 return error.UnsupportedWasmVersion;
23992398 }
24002399
2401 var output = std.array_list.Managed(u8).init(gpa);
2400 var output: std.Io.Writer.Allocating = .init(gpa);
24022401 defer output.deinit();
2403 parseAndDumpInner(step, check, bytes, &fbs, &output) catch |err| switch (err) {
2404 error.EndOfStream => try output.appendSlice("\n<UnexpectedEndOfStream>"),
2402 parseAndDumpInner(step, check, bytes, &fbs, &output.writer) catch |err| switch (err) {
2403 error.EndOfStream => try output.writer.writeAll("\n<UnexpectedEndOfStream>"),
24052404 else => |e| return e,
24062405 };
24072406 return output.toOwnedSlice();
......@@ -2412,10 +2411,9 @@ const WasmDumper = struct {
24122411 check: Check,
24132412 bytes: []const u8,
24142413 fbs: *std.io.FixedBufferStream([]const u8),
2415 output: *std.array_list.Managed(u8),
2414 writer: *std.Io.Writer,
24162415 ) !void {
24172416 const reader = fbs.reader();
2418 const writer = output.writer();
24192417
24202418 switch (check.kind) {
24212419 .headers => {
lib/std/Io.zig-121
......@@ -144,19 +144,6 @@ pub fn GenericReader(
144144 return @errorCast(self.any().readAllAlloc(allocator, max_size));
145145 }
146146
147 pub inline fn readUntilDelimiterArrayList(
148 self: Self,
149 array_list: *std.array_list.Managed(u8),
150 delimiter: u8,
151 max_size: usize,
152 ) (NoEofError || Allocator.Error || error{StreamTooLong})!void {
153 return @errorCast(self.any().readUntilDelimiterArrayList(
154 array_list,
155 delimiter,
156 max_size,
157 ));
158 }
159
160147 pub inline fn readUntilDelimiterAlloc(
161148 self: Self,
162149 allocator: Allocator,
......@@ -326,103 +313,8 @@ pub fn GenericReader(
326313 };
327314}
328315
329/// Deprecated in favor of `Writer`.
330pub fn GenericWriter(
331 comptime Context: type,
332 comptime WriteError: type,
333 comptime writeFn: fn (context: Context, bytes: []const u8) WriteError!usize,
334) type {
335 return struct {
336 context: Context,
337
338 const Self = @This();
339 pub const Error = WriteError;
340
341 pub inline fn write(self: Self, bytes: []const u8) Error!usize {
342 return writeFn(self.context, bytes);
343 }
344
345 pub inline fn writeAll(self: Self, bytes: []const u8) Error!void {
346 return @errorCast(self.any().writeAll(bytes));
347 }
348
349 pub inline fn print(self: Self, comptime format: []const u8, args: anytype) Error!void {
350 return @errorCast(self.any().print(format, args));
351 }
352
353 pub inline fn writeByte(self: Self, byte: u8) Error!void {
354 return @errorCast(self.any().writeByte(byte));
355 }
356
357 pub inline fn writeByteNTimes(self: Self, byte: u8, n: usize) Error!void {
358 return @errorCast(self.any().writeByteNTimes(byte, n));
359 }
360
361 pub inline fn writeBytesNTimes(self: Self, bytes: []const u8, n: usize) Error!void {
362 return @errorCast(self.any().writeBytesNTimes(bytes, n));
363 }
364
365 pub inline fn writeInt(self: Self, comptime T: type, value: T, endian: std.builtin.Endian) Error!void {
366 return @errorCast(self.any().writeInt(T, value, endian));
367 }
368
369 pub inline fn writeStruct(self: Self, value: anytype) Error!void {
370 return @errorCast(self.any().writeStruct(value));
371 }
372
373 pub inline fn writeStructEndian(self: Self, value: anytype, endian: std.builtin.Endian) Error!void {
374 return @errorCast(self.any().writeStructEndian(value, endian));
375 }
376
377 pub inline fn any(self: *const Self) AnyWriter {
378 return .{
379 .context = @ptrCast(&self.context),
380 .writeFn = typeErasedWriteFn,
381 };
382 }
383
384 fn typeErasedWriteFn(context: *const anyopaque, bytes: []const u8) anyerror!usize {
385 const ptr: *const Context = @ptrCast(@alignCast(context));
386 return writeFn(ptr.*, bytes);
387 }
388
389 /// Helper for bridging to the new `Writer` API while upgrading.
390 pub fn adaptToNewApi(self: *const Self, buffer: []u8) Adapter {
391 return .{
392 .derp_writer = self.*,
393 .new_interface = .{
394 .buffer = buffer,
395 .vtable = &.{ .drain = Adapter.drain },
396 },
397 };
398 }
399
400 pub const Adapter = struct {
401 derp_writer: Self,
402 new_interface: Writer,
403 err: ?Error = null,
404
405 fn drain(w: *std.io.Writer, data: []const []const u8, splat: usize) std.io.Writer.Error!usize {
406 _ = splat;
407 const a: *@This() = @alignCast(@fieldParentPtr("new_interface", w));
408 const buffered = w.buffered();
409 if (buffered.len != 0) return w.consume(a.derp_writer.write(buffered) catch |err| {
410 a.err = err;
411 return error.WriteFailed;
412 });
413 return a.derp_writer.write(data[0]) catch |err| {
414 a.err = err;
415 return error.WriteFailed;
416 };
417 }
418 };
419 };
420}
421
422316/// Deprecated in favor of `Reader`.
423317pub const AnyReader = @import("Io/DeprecatedReader.zig");
424/// Deprecated in favor of `Writer`.
425pub const AnyWriter = @import("Io/DeprecatedWriter.zig");
426318/// Deprecated in favor of `Reader`.
427319pub const FixedBufferStream = @import("Io/fixed_buffer_stream.zig").FixedBufferStream;
428320/// Deprecated in favor of `Reader`.
......@@ -434,19 +326,6 @@ pub const countingReader = @import("Io/counting_reader.zig").countingReader;
434326
435327pub const tty = @import("Io/tty.zig");
436328
437/// Deprecated in favor of `Writer.Discarding`.
438pub const null_writer: NullWriter = .{ .context = {} };
439/// Deprecated in favor of `Writer.Discarding`.
440pub const NullWriter = GenericWriter(void, error{}, dummyWrite);
441fn dummyWrite(context: void, data: []const u8) error{}!usize {
442 _ = context;
443 return data.len;
444}
445
446test null_writer {
447 null_writer.writeAll("yay" ** 10) catch |err| switch (err) {};
448}
449
450329pub fn poll(
451330 gpa: Allocator,
452331 comptime StreamEnum: type,
lib/std/Io/DeprecatedReader.zig-94
......@@ -93,100 +93,6 @@ pub fn readAllAlloc(self: Self, allocator: mem.Allocator, max_size: usize) anyer
9393 return try array_list.toOwnedSlice();
9494}
9595
96/// Deprecated: use `streamUntilDelimiter` with ArrayList's writer instead.
97/// Replaces the `std.array_list.Managed` contents by reading from the stream until `delimiter` is found.
98/// Does not include the delimiter in the result.
99/// If the `std.array_list.Managed` length would exceed `max_size`, `error.StreamTooLong` is returned and the
100/// `std.array_list.Managed` is populated with `max_size` bytes from the stream.
101pub fn readUntilDelimiterArrayList(
102 self: Self,
103 array_list: *std.array_list.Managed(u8),
104 delimiter: u8,
105 max_size: usize,
106) anyerror!void {
107 array_list.shrinkRetainingCapacity(0);
108 try self.streamUntilDelimiter(array_list.writer(), delimiter, max_size);
109}
110
111/// Deprecated: use `streamUntilDelimiter` with ArrayList's writer instead.
112/// Allocates enough memory to read until `delimiter`. If the allocated
113/// memory would be greater than `max_size`, returns `error.StreamTooLong`.
114/// Caller owns returned memory.
115/// If this function returns an error, the contents from the stream read so far are lost.
116pub fn readUntilDelimiterAlloc(
117 self: Self,
118 allocator: mem.Allocator,
119 delimiter: u8,
120 max_size: usize,
121) anyerror![]u8 {
122 var array_list = std.array_list.Managed(u8).init(allocator);
123 defer array_list.deinit();
124 try self.streamUntilDelimiter(array_list.writer(), delimiter, max_size);
125 return try array_list.toOwnedSlice();
126}
127
128/// Deprecated: use `streamUntilDelimiter` with FixedBufferStream's writer instead.
129/// Reads from the stream until specified byte is found. If the buffer is not
130/// large enough to hold the entire contents, `error.StreamTooLong` is returned.
131/// If end-of-stream is found, `error.EndOfStream` is returned.
132/// Returns a slice of the stream data, with ptr equal to `buf.ptr`. The
133/// delimiter byte is written to the output buffer but is not included
134/// in the returned slice.
135pub fn readUntilDelimiter(self: Self, buf: []u8, delimiter: u8) anyerror![]u8 {
136 var fbs = std.io.fixedBufferStream(buf);
137 try self.streamUntilDelimiter(fbs.writer(), delimiter, fbs.buffer.len);
138 const output = fbs.getWritten();
139 buf[output.len] = delimiter; // emulating old behaviour
140 return output;
141}
142
143/// Deprecated: use `streamUntilDelimiter` with ArrayList's (or any other's) writer instead.
144/// Allocates enough memory to read until `delimiter` or end-of-stream.
145/// If the allocated memory would be greater than `max_size`, returns
146/// `error.StreamTooLong`. If end-of-stream is found, returns the rest
147/// of the stream. If this function is called again after that, returns
148/// null.
149/// Caller owns returned memory.
150/// If this function returns an error, the contents from the stream read so far are lost.
151pub fn readUntilDelimiterOrEofAlloc(
152 self: Self,
153 allocator: mem.Allocator,
154 delimiter: u8,
155 max_size: usize,
156) anyerror!?[]u8 {
157 var array_list = std.array_list.Managed(u8).init(allocator);
158 defer array_list.deinit();
159 self.streamUntilDelimiter(array_list.writer(), delimiter, max_size) catch |err| switch (err) {
160 error.EndOfStream => if (array_list.items.len == 0) {
161 return null;
162 },
163 else => |e| return e,
164 };
165 return try array_list.toOwnedSlice();
166}
167
168/// Deprecated: use `streamUntilDelimiter` with FixedBufferStream's writer instead.
169/// Reads from the stream until specified byte is found. If the buffer is not
170/// large enough to hold the entire contents, `error.StreamTooLong` is returned.
171/// If end-of-stream is found, returns the rest of the stream. If this
172/// function is called again after that, returns null.
173/// Returns a slice of the stream data, with ptr equal to `buf.ptr`. The
174/// delimiter byte is written to the output buffer but is not included
175/// in the returned slice.
176pub fn readUntilDelimiterOrEof(self: Self, buf: []u8, delimiter: u8) anyerror!?[]u8 {
177 var fbs = std.io.fixedBufferStream(buf);
178 self.streamUntilDelimiter(fbs.writer(), delimiter, fbs.buffer.len) catch |err| switch (err) {
179 error.EndOfStream => if (fbs.getWritten().len == 0) {
180 return null;
181 },
182
183 else => |e| return e,
184 };
185 const output = fbs.getWritten();
186 buf[output.len] = delimiter; // emulating old behaviour
187 return output;
188}
189
19096/// Appends to the `writer` contents by reading from the stream until `delimiter` is found.
19197/// Does not write the delimiter itself.
19298/// If `optional_max_size` is not null and amount of written bytes exceeds `optional_max_size`,
lib/std/Io/DeprecatedWriter.zig deleted-114
......@@ -1,114 +0,0 @@
1const std = @import("../std.zig");
2const assert = std.debug.assert;
3const mem = std.mem;
4const native_endian = @import("builtin").target.cpu.arch.endian();
5
6context: *const anyopaque,
7writeFn: *const fn (context: *const anyopaque, bytes: []const u8) anyerror!usize,
8
9const Self = @This();
10pub const Error = anyerror;
11
12pub fn write(self: Self, bytes: []const u8) anyerror!usize {
13 return self.writeFn(self.context, bytes);
14}
15
16pub fn writeAll(self: Self, bytes: []const u8) anyerror!void {
17 var index: usize = 0;
18 while (index != bytes.len) {
19 index += try self.write(bytes[index..]);
20 }
21}
22
23pub fn print(self: Self, comptime format: []const u8, args: anytype) anyerror!void {
24 return std.fmt.format(self, format, args);
25}
26
27pub fn writeByte(self: Self, byte: u8) anyerror!void {
28 const array = [1]u8{byte};
29 return self.writeAll(&array);
30}
31
32pub fn writeByteNTimes(self: Self, byte: u8, n: usize) anyerror!void {
33 var bytes: [256]u8 = undefined;
34 @memset(bytes[0..], byte);
35
36 var remaining: usize = n;
37 while (remaining > 0) {
38 const to_write = @min(remaining, bytes.len);
39 try self.writeAll(bytes[0..to_write]);
40 remaining -= to_write;
41 }
42}
43
44pub fn writeBytesNTimes(self: Self, bytes: []const u8, n: usize) anyerror!void {
45 var i: usize = 0;
46 while (i < n) : (i += 1) {
47 try self.writeAll(bytes);
48 }
49}
50
51pub inline fn writeInt(self: Self, comptime T: type, value: T, endian: std.builtin.Endian) anyerror!void {
52 var bytes: [@divExact(@typeInfo(T).int.bits, 8)]u8 = undefined;
53 mem.writeInt(std.math.ByteAlignedInt(@TypeOf(value)), &bytes, value, endian);
54 return self.writeAll(&bytes);
55}
56
57pub fn writeStruct(self: Self, value: anytype) anyerror!void {
58 // Only extern and packed structs have defined in-memory layout.
59 comptime assert(@typeInfo(@TypeOf(value)).@"struct".layout != .auto);
60 return self.writeAll(mem.asBytes(&value));
61}
62
63pub fn writeStructEndian(self: Self, value: anytype, endian: std.builtin.Endian) anyerror!void {
64 // TODO: make sure this value is not a reference type
65 if (native_endian == endian) {
66 return self.writeStruct(value);
67 } else {
68 var copy = value;
69 mem.byteSwapAllFields(@TypeOf(value), &copy);
70 return self.writeStruct(copy);
71 }
72}
73
74pub fn writeFile(self: Self, file: std.fs.File) anyerror!void {
75 // TODO: figure out how to adjust std lib abstractions so that this ends up
76 // doing sendfile or maybe even copy_file_range under the right conditions.
77 var buf: [4000]u8 = undefined;
78 while (true) {
79 const n = try file.readAll(&buf);
80 try self.writeAll(buf[0..n]);
81 if (n < buf.len) return;
82 }
83}
84
85/// Helper for bridging to the new `Writer` API while upgrading.
86pub fn adaptToNewApi(self: *const Self, buffer: []u8) Adapter {
87 return .{
88 .derp_writer = self.*,
89 .new_interface = .{
90 .buffer = buffer,
91 .vtable = &.{ .drain = Adapter.drain },
92 },
93 };
94}
95
96pub const Adapter = struct {
97 derp_writer: Self,
98 new_interface: std.io.Writer,
99 err: ?Error = null,
100
101 fn drain(w: *std.io.Writer, data: []const []const u8, splat: usize) std.io.Writer.Error!usize {
102 _ = splat;
103 const a: *@This() = @alignCast(@fieldParentPtr("new_interface", w));
104 const buffered = w.buffered();
105 if (buffered.len != 0) return w.consume(a.derp_writer.write(buffered) catch |err| {
106 a.err = err;
107 return error.WriteFailed;
108 });
109 return a.derp_writer.write(data[0]) catch |err| {
110 a.err = err;
111 return error.WriteFailed;
112 };
113 }
114};
lib/std/Io/fixed_buffer_stream.zig-69
......@@ -17,7 +17,6 @@ pub fn FixedBufferStream(comptime Buffer: type) type {
1717 pub const GetSeekPosError = error{};
1818
1919 pub const Reader = io.GenericReader(*Self, ReadError, read);
20 pub const Writer = io.GenericWriter(*Self, WriteError, write);
2120
2221 const Self = @This();
2322
......@@ -25,10 +24,6 @@ pub fn FixedBufferStream(comptime Buffer: type) type {
2524 return .{ .context = self };
2625 }
2726
28 pub fn writer(self: *Self) Writer {
29 return .{ .context = self };
30 }
31
3227 pub fn read(self: *Self, dest: []u8) ReadError!usize {
3328 const size = @min(dest.len, self.buffer.len - self.pos);
3429 const end = self.pos + size;
......@@ -39,23 +34,6 @@ pub fn FixedBufferStream(comptime Buffer: type) type {
3934 return size;
4035 }
4136
42 /// If the returned number of bytes written is less than requested, the
43 /// buffer is full. Returns `error.NoSpaceLeft` when no bytes would be written.
44 /// Note: `error.NoSpaceLeft` matches the corresponding error from
45 /// `std.fs.File.WriteError`.
46 pub fn write(self: *Self, bytes: []const u8) WriteError!usize {
47 if (bytes.len == 0) return 0;
48 if (self.pos >= self.buffer.len) return error.NoSpaceLeft;
49
50 const n = @min(self.buffer.len - self.pos, bytes.len);
51 @memcpy(self.buffer[self.pos..][0..n], bytes[0..n]);
52 self.pos += n;
53
54 if (n == 0) return error.NoSpaceLeft;
55
56 return n;
57 }
58
5937 pub fn seekTo(self: *Self, pos: u64) SeekError!void {
6038 self.pos = @min(std.math.lossyCast(usize, pos), self.buffer.len);
6139 }
......@@ -84,10 +62,6 @@ pub fn FixedBufferStream(comptime Buffer: type) type {
8462 return self.pos;
8563 }
8664
87 pub fn getWritten(self: Self) Buffer {
88 return self.buffer[0..self.pos];
89 }
90
9165 pub fn reset(self: *Self) void {
9266 self.pos = 0;
9367 }
......@@ -117,49 +91,6 @@ fn Slice(comptime T: type) type {
11791 }
11892}
11993
120test "output" {
121 var buf: [255]u8 = undefined;
122 var fbs = fixedBufferStream(&buf);
123 const stream = fbs.writer();
124
125 try stream.print("{s}{s}!", .{ "Hello", "World" });
126 try testing.expectEqualSlices(u8, "HelloWorld!", fbs.getWritten());
127}
128
129test "output at comptime" {
130 comptime {
131 var buf: [255]u8 = undefined;
132 var fbs = fixedBufferStream(&buf);
133 const stream = fbs.writer();
134
135 try stream.print("{s}{s}!", .{ "Hello", "World" });
136 try testing.expectEqualSlices(u8, "HelloWorld!", fbs.getWritten());
137 }
138}
139
140test "output 2" {
141 var buffer: [10]u8 = undefined;
142 var fbs = fixedBufferStream(&buffer);
143
144 try fbs.writer().writeAll("Hello");
145 try testing.expect(mem.eql(u8, fbs.getWritten(), "Hello"));
146
147 try fbs.writer().writeAll("world");
148 try testing.expect(mem.eql(u8, fbs.getWritten(), "Helloworld"));
149
150 try testing.expectError(error.NoSpaceLeft, fbs.writer().writeAll("!"));
151 try testing.expect(mem.eql(u8, fbs.getWritten(), "Helloworld"));
152
153 fbs.reset();
154 try testing.expect(fbs.getWritten().len == 0);
155
156 try testing.expectError(error.NoSpaceLeft, fbs.writer().writeAll("Hello world!"));
157 try testing.expect(mem.eql(u8, fbs.getWritten(), "Hello worl"));
158
159 try fbs.seekTo((try fbs.getEndPos()) + 1);
160 try testing.expectError(error.NoSpaceLeft, fbs.writer().writeAll("H"));
161}
162
16394test "input" {
16495 const bytes = [_]u8{ 1, 2, 3, 4, 5, 6, 7 };
16596 var fbs = fixedBufferStream(&bytes);
lib/std/array_list.zig-75
......@@ -336,39 +336,6 @@ pub fn AlignedManaged(comptime T: type, comptime alignment: ?mem.Alignment) type
336336 try unmanaged.print(gpa, fmt, args);
337337 }
338338
339 pub const Writer = if (T != u8) void else std.io.GenericWriter(*Self, Allocator.Error, appendWrite);
340
341 /// Initializes a Writer which will append to the list.
342 pub fn writer(self: *Self) Writer {
343 return .{ .context = self };
344 }
345
346 /// Same as `append` except it returns the number of bytes written, which is always the same
347 /// as `m.len`. The purpose of this function existing is to match `std.io.GenericWriter` API.
348 /// Invalidates element pointers if additional memory is needed.
349 fn appendWrite(self: *Self, m: []const u8) Allocator.Error!usize {
350 try self.appendSlice(m);
351 return m.len;
352 }
353
354 pub const FixedWriter = std.io.GenericWriter(*Self, Allocator.Error, appendWriteFixed);
355
356 /// Initializes a Writer which will append to the list but will return
357 /// `error.OutOfMemory` rather than increasing capacity.
358 pub fn fixedWriter(self: *Self) FixedWriter {
359 return .{ .context = self };
360 }
361
362 /// The purpose of this function existing is to match `std.io.GenericWriter` API.
363 fn appendWriteFixed(self: *Self, m: []const u8) error{OutOfMemory}!usize {
364 const available_capacity = self.capacity - self.items.len;
365 if (m.len > available_capacity)
366 return error.OutOfMemory;
367
368 self.appendSliceAssumeCapacity(m);
369 return m.len;
370 }
371
372339 /// Append a value to the list `n` times.
373340 /// Allocates more memory as necessary.
374341 /// Invalidates element pointers if additional memory is needed.
......@@ -1083,48 +1050,6 @@ pub fn Aligned(comptime T: type, comptime alignment: ?mem.Alignment) type {
10831050 self.items.len += w.end;
10841051 }
10851052
1086 /// Deprecated in favor of `print` or `std.io.Writer.Allocating`.
1087 pub const WriterContext = struct {
1088 self: *Self,
1089 allocator: Allocator,
1090 };
1091
1092 /// Deprecated in favor of `print` or `std.io.Writer.Allocating`.
1093 pub const Writer = if (T != u8)
1094 @compileError("The Writer interface is only defined for ArrayList(u8) " ++
1095 "but the given type is ArrayList(" ++ @typeName(T) ++ ")")
1096 else
1097 std.io.GenericWriter(WriterContext, Allocator.Error, appendWrite);
1098
1099 /// Deprecated in favor of `print` or `std.io.Writer.Allocating`.
1100 pub fn writer(self: *Self, gpa: Allocator) Writer {
1101 return .{ .context = .{ .self = self, .allocator = gpa } };
1102 }
1103
1104 /// Deprecated in favor of `print` or `std.io.Writer.Allocating`.
1105 fn appendWrite(context: WriterContext, m: []const u8) Allocator.Error!usize {
1106 try context.self.appendSlice(context.allocator, m);
1107 return m.len;
1108 }
1109
1110 /// Deprecated in favor of `print` or `std.io.Writer.Allocating`.
1111 pub const FixedWriter = std.io.GenericWriter(*Self, Allocator.Error, appendWriteFixed);
1112
1113 /// Deprecated in favor of `print` or `std.io.Writer.Allocating`.
1114 pub fn fixedWriter(self: *Self) FixedWriter {
1115 return .{ .context = self };
1116 }
1117
1118 /// Deprecated in favor of `print` or `std.io.Writer.Allocating`.
1119 fn appendWriteFixed(self: *Self, m: []const u8) error{OutOfMemory}!usize {
1120 const available_capacity = self.capacity - self.items.len;
1121 if (m.len > available_capacity)
1122 return error.OutOfMemory;
1123
1124 self.appendSliceAssumeCapacity(m);
1125 return m.len;
1126 }
1127
11281053 /// Append a value to the list `n` times.
11291054 /// Allocates more memory as necessary.
11301055 /// Invalidates element pointers if additional memory is needed.
lib/std/base64.zig+1-2
......@@ -108,8 +108,7 @@ pub const Base64Encoder = struct {
108108 }
109109 }
110110
111 // dest must be compatible with std.io.GenericWriter's writeAll interface
112 pub fn encodeWriter(encoder: *const Base64Encoder, dest: anytype, source: []const u8) !void {
111 pub fn encodeWriter(encoder: *const Base64Encoder, dest: *std.Io.Writer, source: []const u8) !void {
113112 var chunker = window(u8, source, 3, 3);
114113 while (chunker.next()) |chunk| {
115114 var temp: [5]u8 = undefined;
lib/std/crypto/aegis.zig-12
......@@ -801,18 +801,6 @@ fn AegisMac(comptime T: type) type {
801801 ctx.update(msg);
802802 ctx.final(out);
803803 }
804
805 pub const Error = error{};
806 pub const Writer = std.io.GenericWriter(*Mac, Error, write);
807
808 fn write(self: *Mac, bytes: []const u8) Error!usize {
809 self.update(bytes);
810 return bytes.len;
811 }
812
813 pub fn writer(self: *Mac) Writer {
814 return .{ .context = self };
815 }
816804 };
817805}
818806
lib/std/crypto/blake2.zig-12
......@@ -185,18 +185,6 @@ pub fn Blake2s(comptime out_bits: usize) type {
185185 r.* ^= v[i] ^ v[i + 8];
186186 }
187187 }
188
189 pub const Error = error{};
190 pub const Writer = std.io.GenericWriter(*Self, Error, write);
191
192 fn write(self: *Self, bytes: []const u8) Error!usize {
193 self.update(bytes);
194 return bytes.len;
195 }
196
197 pub fn writer(self: *Self) Writer {
198 return .{ .context = self };
199 }
200188 };
201189}
202190
lib/std/crypto/blake3.zig-12
......@@ -474,18 +474,6 @@ pub const Blake3 = struct {
474474 }
475475 output.rootOutputBytes(out_slice);
476476 }
477
478 pub const Error = error{};
479 pub const Writer = std.io.GenericWriter(*Blake3, Error, write);
480
481 fn write(self: *Blake3, bytes: []const u8) Error!usize {
482 self.update(bytes);
483 return bytes.len;
484 }
485
486 pub fn writer(self: *Blake3) Writer {
487 return .{ .context = self };
488 }
489477};
490478
491479// Use named type declarations to workaround crash with anonymous structs (issue #4373).
lib/std/crypto/codecs/asn1/der/ArrayListReverse.zig+6-11
......@@ -4,6 +4,12 @@
44//! Laid out in memory like:
55//! capacity |--------------------------|
66//! data |-------------|
7
8const std = @import("std");
9const Allocator = std.mem.Allocator;
10const assert = std.debug.assert;
11const testing = std.testing;
12
713data: []u8,
814capacity: usize,
915allocator: Allocator,
......@@ -45,12 +51,6 @@ pub fn prependSlice(self: *ArrayListReverse, data: []const u8) Error!void {
4551 self.data.ptr = begin;
4652}
4753
48pub const Writer = std.io.GenericWriter(*ArrayListReverse, Error, prependSliceSize);
49/// Warning: This writer writes backwards. `fn print` will NOT work as expected.
50pub fn writer(self: *ArrayListReverse) Writer {
51 return .{ .context = self };
52}
53
5454fn prependSliceSize(self: *ArrayListReverse, data: []const u8) Error!usize {
5555 try self.prependSlice(data);
5656 return data.len;
......@@ -77,11 +77,6 @@ pub fn toOwnedSlice(self: *ArrayListReverse) Error![]u8 {
7777 return new_memory;
7878}
7979
80const std = @import("std");
81const Allocator = std.mem.Allocator;
82const assert = std.debug.assert;
83const testing = std.testing;
84
8580test ArrayListReverse {
8681 var b = ArrayListReverse.init(testing.allocator);
8782 defer b.deinit();
lib/std/crypto/sha2.zig-12
......@@ -373,18 +373,6 @@ fn Sha2x32(comptime iv: Iv32, digest_bits: comptime_int) type {
373373
374374 for (&d.s, v) |*dv, vv| dv.* +%= vv;
375375 }
376
377 pub const Error = error{};
378 pub const Writer = std.io.GenericWriter(*Self, Error, write);
379
380 fn write(self: *Self, bytes: []const u8) Error!usize {
381 self.update(bytes);
382 return bytes.len;
383 }
384
385 pub fn writer(self: *Self) Writer {
386 return .{ .context = self };
387 }
388376 };
389377}
390378
lib/std/crypto/sha3.zig-60
......@@ -80,18 +80,6 @@ pub fn Keccak(comptime f: u11, comptime output_bits: u11, comptime default_delim
8080 self.st.pad();
8181 self.st.squeeze(out[0..]);
8282 }
83
84 pub const Error = error{};
85 pub const Writer = std.io.GenericWriter(*Self, Error, write);
86
87 fn write(self: *Self, bytes: []const u8) Error!usize {
88 self.update(bytes);
89 return bytes.len;
90 }
91
92 pub fn writer(self: *Self) Writer {
93 return .{ .context = self };
94 }
9583 };
9684}
9785
......@@ -191,18 +179,6 @@ fn ShakeLike(comptime security_level: u11, comptime default_delim: u8, comptime
191179 pub fn fillBlock(self: *Self) void {
192180 self.st.fillBlock();
193181 }
194
195 pub const Error = error{};
196 pub const Writer = std.io.GenericWriter(*Self, Error, write);
197
198 fn write(self: *Self, bytes: []const u8) Error!usize {
199 self.update(bytes);
200 return bytes.len;
201 }
202
203 pub fn writer(self: *Self) Writer {
204 return .{ .context = self };
205 }
206182 };
207183}
208184
......@@ -284,18 +260,6 @@ fn CShakeLike(comptime security_level: u11, comptime default_delim: u8, comptime
284260 pub fn fillBlock(self: *Self) void {
285261 self.shaker.fillBlock();
286262 }
287
288 pub const Error = error{};
289 pub const Writer = std.io.GenericWriter(*Self, Error, write);
290
291 fn write(self: *Self, bytes: []const u8) Error!usize {
292 self.update(bytes);
293 return bytes.len;
294 }
295
296 pub fn writer(self: *Self) Writer {
297 return .{ .context = self };
298 }
299263 };
300264}
301265
......@@ -390,18 +354,6 @@ fn KMacLike(comptime security_level: u11, comptime default_delim: u8, comptime r
390354 ctx.update(msg);
391355 ctx.final(out);
392356 }
393
394 pub const Error = error{};
395 pub const Writer = std.io.GenericWriter(*Self, Error, write);
396
397 fn write(self: *Self, bytes: []const u8) Error!usize {
398 self.update(bytes);
399 return bytes.len;
400 }
401
402 pub fn writer(self: *Self) Writer {
403 return .{ .context = self };
404 }
405357 };
406358}
407359
......@@ -482,18 +434,6 @@ fn TupleHashLike(comptime security_level: u11, comptime default_delim: u8, compt
482434 }
483435 self.cshaker.squeeze(out);
484436 }
485
486 pub const Error = error{};
487 pub const Writer = std.io.GenericWriter(*Self, Error, write);
488
489 fn write(self: *Self, bytes: []const u8) Error!usize {
490 self.update(bytes);
491 return bytes.len;
492 }
493
494 pub fn writer(self: *Self) Writer {
495 return .{ .context = self };
496 }
497437 };
498438}
499439
lib/std/crypto/siphash.zig-12
......@@ -238,18 +238,6 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize)
238238 pub fn toInt(msg: []const u8, key: *const [key_length]u8) T {
239239 return State.hash(msg, key);
240240 }
241
242 pub const Error = error{};
243 pub const Writer = std.io.GenericWriter(*Self, Error, write);
244
245 fn write(self: *Self, bytes: []const u8) Error!usize {
246 self.update(bytes);
247 return bytes.len;
248 }
249
250 pub fn writer(self: *Self) Writer {
251 return .{ .context = self };
252 }
253241 };
254242}
255243
lib/std/fs/File.zig-8
......@@ -1097,14 +1097,6 @@ pub fn deprecatedReader(file: File) DeprecatedReader {
10971097 return .{ .context = file };
10981098}
10991099
1100/// Deprecated in favor of `Writer`.
1101pub const DeprecatedWriter = io.GenericWriter(File, WriteError, write);
1102
1103/// Deprecated in favor of `Writer`.
1104pub fn deprecatedWriter(file: File) DeprecatedWriter {
1105 return .{ .context = file };
1106}
1107
11081100/// Memoizes key information about a file handle such as:
11091101/// * The size from calling stat, or the error that occurred therein.
11101102/// * The current seek position.
lib/std/json.zig+1-1
......@@ -6,7 +6,7 @@
66//! The high-level `parseFromSlice` and `parseFromTokenSource` deserialize a JSON document into a Zig type.
77//! Parse into a dynamically-typed `Value` to load any JSON value for runtime inspection.
88//!
9//! The low-level `writeStream` emits syntax-conformant JSON tokens to a `std.io.GenericWriter`.
9//! The low-level `writeStream` emits syntax-conformant JSON tokens to a `std.Io.Writer`.
1010//! The high-level `stringify` serializes a Zig or `Value` type into JSON.
1111
1212const builtin = @import("builtin");
src/main.zig+2-2
......@@ -4230,7 +4230,7 @@ fn serveUpdateResults(s: *Server, comp: *Compilation) !void {
42304230 const decl_name = zir.nullTerminatedString(zir.getDeclaration(resolved.inst).name);
42314231
42324232 const gop = try files.getOrPut(gpa, resolved.file);
4233 if (!gop.found_existing) try file_name_bytes.writer(gpa).print("{f}\x00", .{file.path.fmt(comp)});
4233 if (!gop.found_existing) try file_name_bytes.print(gpa, "{f}\x00", .{file.path.fmt(comp)});
42344234
42354235 const codegen_ns = tr.decl_codegen_ns.get(tracked_inst) orelse 0;
42364236 const link_ns = tr.decl_link_ns.get(tracked_inst) orelse 0;
......@@ -7451,7 +7451,7 @@ const Templates = struct {
74517451 i += "_NAME".len;
74527452 continue;
74537453 } else if (std.mem.startsWith(u8, contents[i + 1 ..], "FINGERPRINT")) {
7454 try templates.buffer.writer().print("0x{x}", .{fingerprint.int()});
7454 try templates.buffer.print("0x{x}", .{fingerprint.int()});
74557455 i += "_FINGERPRINT".len;
74567456 continue;
74577457 } else if (std.mem.startsWith(u8, contents[i + 1 ..], "ZIGVER")) {