Last active
October 1, 2024 17:20
-
-
Save hirrolot/8f47529ffd98ef536f43e66407857dc2 to your computer and use it in GitHub Desktop.
Generic `printf` implementation in Zig
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
fn printf(comptime fmt: []const u8, args: anytype) anyerror!void { | |
const stdout = std.io.getStdOut().writer(); | |
comptime var arg_idx: usize = 0; | |
inline for (fmt) |c| { | |
if (c == '*') { | |
try printArg(stdout, args[arg_idx]); | |
arg_idx += 1; | |
} else { | |
try stdout.print("{c}", .{c}); | |
} | |
} | |
comptime { | |
if (args.len != arg_idx) { | |
@compileError("Unused arguments"); | |
} | |
} | |
} | |
fn printArg(stdout: std.fs.File.Writer, arg: anytype) anyerror!void { | |
if (@typeInfo(@TypeOf(arg)) == .Pointer) { | |
try stdout.writeAll(arg); | |
} else { | |
try stdout.print("{any}", .{arg}); | |
} | |
} | |
pub fn main() !void { | |
try printf("Mr. John has * contacts in *.\n", .{ 42, "New York" }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment