Skip to content

Instantly share code, notes, and snippets.

@mnemnion
Created July 29, 2024 15:35
Show Gist options
  • Save mnemnion/11e4effbfe977c70fd03977050494ae3 to your computer and use it in GitHub Desktop.
Save mnemnion/11e4effbfe977c70fd03977050494ae3 to your computer and use it in GitHub Desktop.
Nondeterministic Zig Build with a Syscall
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
var prng = std.Random.DefaultPrng.init(blk: {
var seed: u64 = undefined;
std.posix.getrandom(std.mem.asBytes(&seed)) catch @panic("syscall error");
break :blk seed;
});
const rand = prng.random();
const flip = rand.boolean();
const options = b.addOptions();
options.addOption(bool, "coin_flip", flip);
const exe = b.addExecutable(.{
.name = "nondeterminism",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
b.installArtifact(exe);
exe.root_module.addOptions("config", options);
const run_cmd = b.addRunArtifact(exe);
// It does indeed... it does indeed
run_cmd.has_side_effects = true;
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
const exe_unit_tests = b.addTest(.{
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests);
const test_step = b.step("test", "Run unit tests");
test_step.dependOn(&run_exe_unit_tests.step);
}
//! By convention, main.zig is where your main function lives in the case that
//! you are building an executable. If you are making a library, the convention
//! is to delete this file and start with root.zig instead.
const std = @import("std");
const config = @import("config");
fn testFlip(flip: bool, val: usize) bool {
if (flip) {
return val % 2 == 0;
} else {
return val % 2 == 1;
}
}
fn isEvenOrOdd(val: usize) bool {
return testFlip(config.coin_flip, val);
}
pub fn main() !void {
if (isEvenOrOdd(5)) {
std.debug.print("function tests oddness", .{});
} else {
std.debug.print("function tests evenness", .{});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment