Created
May 23, 2022 17:22
-
-
Save matu3ba/8a578245d2e54d23d42d0c727b1ec673 to your computer and use it in GitHub Desktop.
Zig simple runner through function pointer
This file contains hidden or 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"); | |
const builtin = @import("builtin"); | |
const FnProto = switch (builtin.zig_backend) { | |
// workaround until we replace stage1 with stage2 | |
.stage1 => ?fn (*Runner) anyerror!void, | |
else => ?*fn (*Runner) anyerror!void, | |
}; | |
const Runner = struct { | |
file: std.fs.File, | |
pub fn init(file: std.fs.File) Runner { | |
return .{ | |
.file = file, | |
}; | |
} | |
pub fn run(runner: *Runner, func: FnProto) anyerror!void { | |
if (func != null) | |
try func.?(runner); | |
} | |
}; | |
fn dumpPrint(runner: *Runner) anyerror!void { | |
try runner.file.writer().writeAll("ok\n"); | |
} | |
test "fnproto" { | |
const stdout = std.io.getStdOut(); | |
var runner = Runner.init(stdout); | |
try runner.run(dumpPrint); | |
// doesnt work: | |
//var dump_print = dumpPrint(&runner); | |
//try runner.run(dump_print); | |
// stage2 | |
//try runner.run(&dumpPrint); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment