authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-07-15 21:04:00-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-07-16 17:20:02-07:00
log1a20b467ea3f480306317a6145d910d8c44a9b48
treea65bab55b8f1718a23ca09502d7442d249950e0e
parent680358767e30ac386e6727ffc9295820c598d6b9

std.zig: update to new I/O API


1 files changed, 25 insertions(+), 33 deletions(-)

lib/std/zig.zig+25-33
......@@ -2,6 +2,12 @@
22//! source lives here. These APIs are provided as-is and have absolutely no API
33//! guarantees whatsoever.
44
5const std = @import("std.zig");
6const tokenizer = @import("zig/tokenizer.zig");
7const assert = std.debug.assert;
8const Allocator = std.mem.Allocator;
9const Writer = std.Io.Writer;
10
511pub const ErrorBundle = @import("zig/ErrorBundle.zig");
612pub const Server = @import("zig/Server.zig");
713pub const Client = @import("zig/Client.zig");
......@@ -355,11 +361,6 @@ pub fn serializeCpuAlloc(ally: Allocator, cpu: std.Target.Cpu) Allocator.Error![
355361 return buffer.toOwnedSlice();
356362}
357363
358const std = @import("std.zig");
359const tokenizer = @import("zig/tokenizer.zig");
360const assert = std.debug.assert;
361const Allocator = std.mem.Allocator;
362
363364/// Return a Formatter for a Zig identifier, escaping it with `@""` syntax if needed.
364365///
365366/// See also `fmtIdFlags`.
......@@ -425,7 +426,7 @@ pub const FormatId = struct {
425426 };
426427
427428 /// Print the string as a Zig identifier, escaping it with `@""` syntax if needed.
428 fn render(ctx: FormatId, writer: *std.io.Writer) std.io.Writer.Error!void {
429 fn render(ctx: FormatId, writer: *Writer) Writer.Error!void {
429430 const bytes = ctx.bytes;
430431 if (isValidId(bytes) and
431432 (ctx.flags.allow_primitive or !std.zig.isPrimitive(bytes)) and
......@@ -463,7 +464,7 @@ test fmtChar {
463464}
464465
465466/// Print the string as escaped contents of a double quoted string.
466pub fn stringEscape(bytes: []const u8, w: *std.io.Writer) std.io.Writer.Error!void {
467pub fn stringEscape(bytes: []const u8, w: *Writer) Writer.Error!void {
467468 for (bytes) |byte| switch (byte) {
468469 '\n' => try w.writeAll("\\n"),
469470 '\r' => try w.writeAll("\\r"),
......@@ -480,7 +481,7 @@ pub fn stringEscape(bytes: []const u8, w: *std.io.Writer) std.io.Writer.Error!vo
480481}
481482
482483/// Print the string as escaped contents of a single-quoted string.
483pub fn charEscape(bytes: []const u8, w: *std.io.Writer) std.io.Writer.Error!void {
484pub fn charEscape(bytes: []const u8, w: *Writer) Writer.Error!void {
484485 for (bytes) |byte| switch (byte) {
485486 '\n' => try w.writeAll("\\n"),
486487 '\r' => try w.writeAll("\\r"),
......@@ -529,20 +530,18 @@ test isUnderscore {
529530 try std.testing.expect(!isUnderscore("\\x5f"));
530531}
531532
532pub fn readSourceFileToEndAlloc(gpa: Allocator, input: std.fs.File, size_hint: ?usize) ![:0]u8 {
533 const source_code = input.readToEndAllocOptions(
534 gpa,
535 max_src_size,
536 size_hint,
537 .of(u8),
538 0,
539 ) catch |err| switch (err) {
533pub fn readSourceFileToEndAlloc(gpa: Allocator, input: std.fs.File, size_hint: usize) ![:0]u8 {
534 var buffer: std.ArrayListAlignedUnmanaged(u8, .@"2") = .empty;
535 defer buffer.deinit(gpa);
536
537 try buffer.ensureUnusedCapacity(gpa, size_hint);
538
539 input.readIntoArrayList(gpa, .limited(max_src_size), .@"2", &buffer) catch |err| switch (err) {
540540 error.ConnectionResetByPeer => unreachable,
541541 error.ConnectionTimedOut => unreachable,
542542 error.NotOpenForReading => unreachable,
543543 else => |e| return e,
544544 };
545 errdefer gpa.free(source_code);
546545
547546 // Detect unsupported file types with their Byte Order Mark
548547 const unsupported_boms = [_][]const u8{
......@@ -551,30 +550,23 @@ pub fn readSourceFileToEndAlloc(gpa: Allocator, input: std.fs.File, size_hint: ?
551550 "\xfe\xff", // UTF-16 big endian
552551 };
553552 for (unsupported_boms) |bom| {
554 if (std.mem.startsWith(u8, source_code, bom)) {
553 if (std.mem.startsWith(u8, buffer.items, bom)) {
555554 return error.UnsupportedEncoding;
556555 }
557556 }
558557
559558 // If the file starts with a UTF-16 little endian BOM, translate it to UTF-8
560 if (std.mem.startsWith(u8, source_code, "\xff\xfe")) {
561 if (source_code.len % 2 != 0) return error.InvalidEncoding;
562 // TODO: after wrangle-writer-buffering branch is merged,
563 // avoid this unnecessary allocation
564 const aligned_copy = try gpa.alloc(u16, source_code.len / 2);
565 defer gpa.free(aligned_copy);
566 @memcpy(std.mem.sliceAsBytes(aligned_copy), source_code);
567 const source_code_utf8 = std.unicode.utf16LeToUtf8AllocZ(gpa, aligned_copy) catch |err| switch (err) {
559 if (std.mem.startsWith(u8, buffer.items, "\xff\xfe")) {
560 if (buffer.items.len % 2 != 0) return error.InvalidEncoding;
561 return std.unicode.utf16LeToUtf8AllocZ(gpa, @ptrCast(buffer.items)) catch |err| switch (err) {
568562 error.DanglingSurrogateHalf => error.UnsupportedEncoding,
569563 error.ExpectedSecondSurrogateHalf => error.UnsupportedEncoding,
570564 error.UnexpectedSecondSurrogateHalf => error.UnsupportedEncoding,
571565 else => |e| return e,
572566 };
573 gpa.free(source_code);
574 return source_code_utf8;
575567 }
576568
577 return source_code;
569 return buffer.toOwnedSliceSentinel(gpa, 0);
578570}
579571
580572pub fn printAstErrorsToStderr(gpa: Allocator, tree: Ast, path: []const u8, color: Color) !void {
......@@ -621,7 +613,7 @@ pub fn parseTargetQueryOrReportFatalError(
621613 var help_text = std.ArrayList(u8).init(allocator);
622614 defer help_text.deinit();
623615 for (diags.arch.?.allCpuModels()) |cpu| {
624 help_text.writer().print(" {s}\n", .{cpu.name}) catch break :help;
616 help_text.print(" {s}\n", .{cpu.name}) catch break :help;
625617 }
626618 std.log.info("available CPUs for architecture '{s}':\n{s}", .{
627619 @tagName(diags.arch.?), help_text.items,
......@@ -634,7 +626,7 @@ pub fn parseTargetQueryOrReportFatalError(
634626 var help_text = std.ArrayList(u8).init(allocator);
635627 defer help_text.deinit();
636628 for (diags.arch.?.allFeaturesList()) |feature| {
637 help_text.writer().print(" {s}: {s}\n", .{ feature.name, feature.description }) catch break :help;
629 help_text.print(" {s}: {s}\n", .{ feature.name, feature.description }) catch break :help;
638630 }
639631 std.log.info("available CPU features for architecture '{s}':\n{s}", .{
640632 @tagName(diags.arch.?), help_text.items,
......@@ -647,7 +639,7 @@ pub fn parseTargetQueryOrReportFatalError(
647639 var help_text = std.ArrayList(u8).init(allocator);
648640 defer help_text.deinit();
649641 inline for (@typeInfo(std.Target.ObjectFormat).@"enum".fields) |field| {
650 help_text.writer().print(" {s}\n", .{field.name}) catch break :help;
642 help_text.print(" {s}\n", .{field.name}) catch break :help;
651643 }
652644 std.log.info("available object formats:\n{s}", .{help_text.items});
653645 }
......@@ -658,7 +650,7 @@ pub fn parseTargetQueryOrReportFatalError(
658650 var help_text = std.ArrayList(u8).init(allocator);
659651 defer help_text.deinit();
660652 inline for (@typeInfo(std.Target.Cpu.Arch).@"enum".fields) |field| {
661 help_text.writer().print(" {s}\n", .{field.name}) catch break :help;
653 help_text.print(" {s}\n", .{field.name}) catch break :help;
662654 }
663655 std.log.info("available architectures:\n{s} native\n", .{help_text.items});
664656 }