0.15.1: Use ?std.process.Child.Term with Io.Writer

Learning Zig by contributing, I would like to update:

to use Io.Writer. This is where I am at:

fn fmtTerm(term: ?std.process.Child.Term) std.fmt.Formatter([]const u8, formatTerm) {
    return .{ .data = term };
}
pub fn formatTerm(bytes: []const u8, w: *std.io.Writer) !void {
    // Recover the pointer to the Child.Term
    const term_ptr = @as(?*std.process.Child.Term, bytes.ptr);
    const term = if (term_ptr) |p| p.* else null;

    if (term) |t| switch (t) {
        .Exited => |code| try w.print("exited with code {}", .{code}),
        .Signal => |sig| try w.print("terminated with signal {}", .{sig}),
        .Stopped => |sig| try w.print("stopped with signal {}", .{sig}),
        .Unknown => |code| try w.print(
            "terminated for unknown reason with code {}",
            .{code}
        ),
    } else {
        try w.writeAll("exited with any code");
    }
}

where I am stuck at consolidating ?*std.process.Child.Term to the new formatting usage. But I am not sure whether I am even on the right track here. Any hints and links would be much appreciated.

Take Term instead of []const u8.

Your usage of writer seems fine.
Also, Formatter is deprecated in favour of, and an alias to, Alt.

IIUC I should use:

fn fmtTerm(term: ?std.process.Child.Term) std.fmt.Alt(?std.process.Child.Term, formatTerm) {
    return .{ .data = term };
}
pub fn formatTerm(term: ?std.process.Child.Term, w: *std.io.Writer) !void {
    if (term) |t| switch (t) {
        .Exited => |code| try w.print("exited with code {}", .{code}),
        .Signal => |sig| try w.print("terminated with signal {}", .{sig}),
        .Stopped => |sig| try w.print("stopped with signal {}", .{sig}),
        .Unknown => |code| try w.print(
            "terminated for unknown reason with code {}",
            .{code}
        ),
    } else {
        try w.writeAll("exited with any code");
    }
}

which seems to work.

Thanks!

1 Like