code
stringlengths 38
801k
| repo_path
stringlengths 6
263
|
---|---|
const std = @import("std");
const fs = std.fs;
const mem = std.mem;
const json = std.json;
const assert = std.debug.assert;
// All references to other features are based on "zig name" as the key.
const FeatureOverride = struct {
llvm_name: []const u8,
/// If true, completely omit the feature; as if it does not exist.
omit: bool = false,
/// If true, omit the feature, but all the dependencies of the feature
/// are added in its place.
flatten: bool = false,
zig_name: ?[]const u8 = null,
desc: ?[]const u8 = null,
extra_deps: []const []const u8 = &.{},
};
const Cpu = struct {
llvm_name: ?[]const u8,
zig_name: []const u8,
features: []const []const u8,
};
const Feature = struct {
llvm_name: ?[]const u8 = null,
zig_name: []const u8,
desc: []const u8,
deps: []const []const u8,
flatten: bool = false,
};
const LlvmTarget = struct {
zig_name: []const u8,
llvm_name: []const u8,
td_name: []const u8,
feature_overrides: []const FeatureOverride = &.{},
extra_cpus: []const Cpu = &.{},
extra_features: []const Feature = &.{},
branch_quota: ?usize = null,
};
const llvm_targets = [_]LlvmTarget{
.{
.zig_name = "aarch64",
.llvm_name = "AArch64",
.td_name = "AArch64.td",
.branch_quota = 2000,
.feature_overrides = &.{
.{
.llvm_name = "CONTEXTIDREL2",
.zig_name = "contextidr_el2",
.desc = "Enable RW operand Context ID Register (EL2)",
},
.{
.llvm_name = "neoversee1",
.zig_name = "neoverse_e1",
},
.{
.llvm_name = "neoversen1",
.zig_name = "neoverse_n1",
},
.{
.llvm_name = "neoversen2",
.zig_name = "neoverse_n2",
},
.{
.llvm_name = "neoversev1",
.zig_name = "neoverse_v1",
},
.{
.llvm_name = "exynosm3",
.zig_name = "exynos_m3",
.flatten = true,
.extra_deps = &.{"v8a"},
},
.{
.llvm_name = "exynosm4",
.zig_name = "exynos_m4",
},
.{
.llvm_name = "v8.1a",
.extra_deps = &.{"v8a"},
},
.{
.llvm_name = "a35",
.flatten = true,
.extra_deps = &.{"v8a"},
},
.{
.llvm_name = "a53",
.flatten = true,
.extra_deps = &.{"v8a"},
},
.{
.llvm_name = "a55",
.flatten = true,
},
.{
.llvm_name = "a57",
.flatten = true,
.extra_deps = &.{"v8a"},
},
.{
.llvm_name = "a64fx",
.flatten = true,
},
.{
.llvm_name = "a72",
.flatten = true,
.extra_deps = &.{"v8a"},
},
.{
.llvm_name = "a73",
.flatten = true,
.extra_deps = &.{"v8a"},
},
.{
.llvm_name = "a75",
.flatten = true,
},
.{
.llvm_name = "a77",
.flatten = true,
},
.{
.llvm_name = "apple-a10",
.flatten = true,
},
.{
.llvm_name = "apple-a11",
.flatten = true,
},
.{
.llvm_name = "apple-a14",
.flatten = true,
},
.{
.llvm_name = "carmel",
.flatten = true,
},
.{
.llvm_name = "cortex-a78",
.flatten = true,
},
.{
.llvm_name = "cortex-x1",
.flatten = true,
},
.{
.llvm_name = "falkor",
.flatten = true,
.extra_deps = &.{"v8a"},
},
.{
.llvm_name = "kryo",
.flatten = true,
.extra_deps = &.{"v8a"},
},
.{
.llvm_name = "saphira",
.flatten = true,
},
.{
.llvm_name = "thunderx",
.flatten = true,
.extra_deps = &.{"v8a"},
},
.{
.llvm_name = "thunderx2t99",
.flatten = true,
},
.{
.llvm_name = "thunderx3t110",
.flatten = true,
},
.{
.llvm_name = "thunderxt81",
.flatten = true,
.extra_deps = &.{"v8a"},
},
.{
.llvm_name = "thunderxt83",
.flatten = true,
.extra_deps = &.{"v8a"},
},
.{
.llvm_name = "thunderxt88",
.flatten = true,
.extra_deps = &.{"v8a"},
},
.{
.llvm_name = "tsv110",
.flatten = true,
},
},
.extra_features = &.{
.{
.zig_name = "v8a",
.desc = "Support ARM v8a instructions",
.deps = &.{ "fp_armv8", "neon" },
},
},
.extra_cpus = &.{
.{
.llvm_name = null,
.zig_name = "exynos_m1",
.features = &.{
"crc",
"crypto",
"exynos_cheap_as_move",
"force_32bit_jump_tables",
"fuse_aes",
"perfmon",
"slow_misaligned_128store",
"slow_paired_128",
"use_postra_scheduler",
"use_reciprocal_square_root",
"v8a",
"zcz_fp",
},
},
.{
.llvm_name = null,
.zig_name = "exynos_m2",
.features = &.{
"crc",
"crypto",
"exynos_cheap_as_move",
"force_32bit_jump_tables",
"fuse_aes",
"perfmon",
"slow_misaligned_128store",
"slow_paired_128",
"use_postra_scheduler",
"v8a",
"zcz_fp",
},
},
.{
.llvm_name = null,
.zig_name = "xgene1",
.features = &.{
"fp_armv8",
"neon",
"perfmon",
"v8a",
},
},
.{
.llvm_name = null,
.zig_name = "emag",
.features = &.{
"crc",
"crypto",
"fp_armv8",
"neon",
"perfmon",
"v8a",
},
},
},
},
.{
.zig_name = "amdgpu",
.llvm_name = "AMDGPU",
.td_name = "AMDGPU.td",
.feature_overrides = &.{
.{
.llvm_name = "DumpCode",
.omit = true,
},
.{
.llvm_name = "dumpcode",
.omit = true,
},
},
},
.{
.zig_name = "arc",
.llvm_name = "ARC",
.td_name = "ARC.td",
},
.{
.zig_name = "arm",
.llvm_name = "ARM",
.td_name = "ARM.td",
.branch_quota = 10000,
.extra_cpus = &.{
.{
.llvm_name = "generic",
.zig_name = "baseline",
.features = &.{"v7a"},
},
.{
.llvm_name = null,
.zig_name = "exynos_m1",
.features = &.{ "v8a", "exynos" },
},
.{
.llvm_name = null,
.zig_name = "exynos_m2",
.features = &.{ "v8a", "exynos" },
},
},
.feature_overrides = &.{
.{
.llvm_name = "cortex-a78",
.flatten = true,
},
.{
.llvm_name = "r5",
.flatten = true,
},
.{
.llvm_name = "r52",
.flatten = true,
},
.{
.llvm_name = "r7",
.flatten = true,
},
.{
.llvm_name = "m7",
.flatten = true,
},
.{
.llvm_name = "krait",
.flatten = true,
},
.{
.llvm_name = "kryo",
.flatten = true,
},
.{
.llvm_name = "cortex-x1",
.flatten = true,
},
.{
.llvm_name = "neoverse-v1",
.flatten = true,
},
.{
.llvm_name = "a5",
.flatten = true,
},
.{
.llvm_name = "a7",
.flatten = true,
},
.{
.llvm_name = "a8",
.flatten = true,
},
.{
.llvm_name = "a9",
.flatten = true,
},
.{
.llvm_name = "a12",
.flatten = true,
},
.{
.llvm_name = "a15",
.flatten = true,
},
.{
.llvm_name = "a17",
.flatten = true,
},
.{
.llvm_name = "a32",
.flatten = true,
},
.{
.llvm_name = "a35",
.flatten = true,
},
.{
.llvm_name = "a53",
.flatten = true,
},
.{
.llvm_name = "a55",
.flatten = true,
},
.{
.llvm_name = "a57",
.flatten = true,
},
.{
.llvm_name = "a72",
.flatten = true,
},
.{
.llvm_name = "a73",
.flatten = true,
},
.{
.llvm_name = "a75",
.flatten = true,
},
.{
.llvm_name = "a77",
.flatten = true,
},
.{
.llvm_name = "a78c",
.flatten = true,
},
.{
.llvm_name = "armv2",
.zig_name = "v2",
.extra_deps = &.{"strict_align"},
},
.{
.llvm_name = "armv2a",
.zig_name = "v2a",
.extra_deps = &.{"strict_align"},
},
.{
.llvm_name = "armv3",
.zig_name = "v3",
.extra_deps = &.{"strict_align"},
},
.{
.llvm_name = "armv3m",
.zig_name = "v3m",
.extra_deps = &.{"strict_align"},
},
.{
.llvm_name = "armv4",
.zig_name = "v4",
.extra_deps = &.{"strict_align"},
},
.{
.llvm_name = "armv4t",
.zig_name = "v4t",
.extra_deps = &.{"strict_align"},
},
.{
.llvm_name = "armv5t",
.zig_name = "v5t",
.extra_deps = &.{"strict_align"},
},
.{
.llvm_name = "armv5te",
.zig_name = "v5te",
.extra_deps = &.{"strict_align"},
},
.{
.llvm_name = "armv5tej",
.zig_name = "v5tej",
.extra_deps = &.{"strict_align"},
},
.{
.llvm_name = "armv6",
.zig_name = "v6",
},
.{
.llvm_name = "armv6-m",
.zig_name = "v6m",
},
.{
.llvm_name = "armv6j",
.zig_name = "v6j",
},
.{
.llvm_name = "armv6k",
.zig_name = "v6k",
},
.{
.llvm_name = "armv6kz",
.zig_name = "v6kz",
},
.{
.llvm_name = "armv6s-m",
.zig_name = "v6sm",
},
.{
.llvm_name = "armv6t2",
.zig_name = "v6t2",
},
.{
.llvm_name = "armv7-a",
.zig_name = "v7a",
},
.{
.llvm_name = "armv7-m",
.zig_name = "v7m",
},
.{
.llvm_name = "armv7-r",
.zig_name = "v7r",
},
.{
.llvm_name = "armv7e-m",
.zig_name = "v7em",
},
.{
.llvm_name = "armv7k",
.zig_name = "v7k",
},
.{
.llvm_name = "armv7s",
.zig_name = "v7s",
},
.{
.llvm_name = "armv7ve",
.zig_name = "v7ve",
},
.{
.llvm_name = "armv8.1-a",
.zig_name = "v8_1a",
},
.{
.llvm_name = "armv8.1-m.main",
.zig_name = "v8_1m_main",
},
.{
.llvm_name = "armv8.2-a",
.zig_name = "v8_2a",
},
.{
.llvm_name = "armv8.3-a",
.zig_name = "v8_3a",
},
.{
.llvm_name = "armv8.4-a",
.zig_name = "v8_4a",
},
.{
.llvm_name = "armv8.5-a",
.zig_name = "v8_5a",
},
.{
.llvm_name = "armv8.6-a",
.zig_name = "v8_6a",
},
.{
.llvm_name = "armv8.7-a",
.zig_name = "v8_7a",
},
.{
.llvm_name = "armv8-a",
.zig_name = "v8a",
},
.{
.llvm_name = "armv8-m.base",
.zig_name = "v8m",
},
.{
.llvm_name = "armv8-m.main",
.zig_name = "v8m_main",
},
.{
.llvm_name = "armv8-r",
.zig_name = "v8r",
},
.{
.llvm_name = "v4t",
.zig_name = "has_v4t",
},
.{
.llvm_name = "v5t",
.zig_name = "has_v5t",
},
.{
.llvm_name = "v5te",
.zig_name = "has_v5te",
},
.{
.llvm_name = "v6",
.zig_name = "has_v6",
},
.{
.llvm_name = "v6k",
.zig_name = "has_v6k",
},
.{
.llvm_name = "v6m",
.zig_name = "has_v6m",
},
.{
.llvm_name = "v6t2",
.zig_name = "has_v6t2",
},
.{
.llvm_name = "v7",
.zig_name = "has_v7",
},
.{
.llvm_name = "v7clrex",
.zig_name = "has_v7clrex",
},
.{
.llvm_name = "v8",
.zig_name = "has_v8",
},
.{
.llvm_name = "v8m",
.zig_name = "has_v8m",
},
.{
.llvm_name = "v8m.main",
.zig_name = "has_v8m_main",
},
.{
.llvm_name = "v8.1a",
.zig_name = "has_v8_1a",
},
.{
.llvm_name = "v8.1m.main",
.zig_name = "has_v8_1m_main",
},
.{
.llvm_name = "v8.2a",
.zig_name = "has_v8_2a",
},
.{
.llvm_name = "v8.3a",
.zig_name = "has_v8_3a",
},
.{
.llvm_name = "v8.4a",
.zig_name = "has_v8_4a",
},
.{
.llvm_name = "v8.5a",
.zig_name = "has_v8_5a",
},
.{
.llvm_name = "v8.6a",
.zig_name = "has_v8_6a",
},
.{
.llvm_name = "v8.7a",
.zig_name = "has_v8_7a",
},
},
},
.{
.zig_name = "avr",
.llvm_name = "AVR",
.td_name = "AVR.td",
},
.{
.zig_name = "bpf",
.llvm_name = "BPF",
.td_name = "BPF.td",
},
.{
.zig_name = "csky",
.llvm_name = "CSKY",
.td_name = "CSKY.td",
},
.{
.zig_name = "hexagon",
.llvm_name = "Hexagon",
.td_name = "Hexagon.td",
},
.{
.zig_name = "lanai",
.llvm_name = "Lanai",
.td_name = "Lanai.td",
},
.{
.zig_name = "msp430",
.llvm_name = "MSP430",
.td_name = "MSP430.td",
},
.{
.zig_name = "mips",
.llvm_name = "Mips",
.td_name = "Mips.td",
},
.{
.zig_name = "nvptx",
.llvm_name = "NVPTX",
.td_name = "NVPTX.td",
},
.{
.zig_name = "powerpc",
.llvm_name = "PowerPC",
.td_name = "PPC.td",
.feature_overrides = &.{
.{
.llvm_name = "ppc32",
.omit = true,
},
},
},
.{
.zig_name = "riscv",
.llvm_name = "RISCV",
.td_name = "RISCV.td",
.extra_cpus = &.{
.{
.llvm_name = null,
.zig_name = "baseline_rv32",
.features = &.{ "a", "c", "d", "f", "m" },
},
.{
.llvm_name = null,
.zig_name = "baseline_rv64",
.features = &.{ "64bit", "a", "c", "d", "f", "m" },
},
},
},
.{
.zig_name = "sparc",
.llvm_name = "Sparc",
.td_name = "Sparc.td",
},
.{
.zig_name = "systemz",
.llvm_name = "SystemZ",
.td_name = "SystemZ.td",
},
.{
.zig_name = "ve",
.llvm_name = "VE",
.td_name = "VE.td",
},
.{
.zig_name = "wasm",
.llvm_name = "WebAssembly",
.td_name = "WebAssembly.td",
},
.{
.zig_name = "x86",
.llvm_name = "X86",
.td_name = "X86.td",
.feature_overrides = &.{
.{
.llvm_name = "64bit-mode",
.omit = true,
},
.{
.llvm_name = "i386",
.zig_name = "_i386",
},
.{
.llvm_name = "i486",
.zig_name = "_i486",
},
.{
.llvm_name = "i586",
.zig_name = "_i586",
},
.{
.llvm_name = "i686",
.zig_name = "_i686",
},
.{
.llvm_name = "lakemont",
.extra_deps = &.{"soft_float"},
},
},
},
.{
.zig_name = "xcore",
.llvm_name = "XCore",
.td_name = "XCore.td",
},
};
pub fn main() anyerror!void {
var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena_state.deinit();
const arena = &arena_state.allocator;
const args = try std.process.argsAlloc(arena);
if (args.len <= 1) {
usageAndExit(std.io.getStdErr(), args[0], 1);
}
if (std.mem.eql(u8, args[1], "--help")) {
usageAndExit(std.io.getStdOut(), args[0], 0);
}
if (args.len < 4) {
usageAndExit(std.io.getStdErr(), args[0], 1);
}
const llvm_tblgen_exe = args[1];
if (std.mem.startsWith(u8, llvm_tblgen_exe, "-")) {
usageAndExit(std.io.getStdErr(), args[0], 1);
}
const llvm_src_root = args[2];
if (std.mem.startsWith(u8, llvm_src_root, "-")) {
usageAndExit(std.io.getStdErr(), args[0], 1);
}
const zig_src_root = args[3];
if (std.mem.startsWith(u8, zig_src_root, "-")) {
usageAndExit(std.io.getStdErr(), args[0], 1);
}
var zig_src_dir = try fs.cwd().openDir(zig_src_root, .{});
defer zig_src_dir.close();
var progress = std.Progress{};
const root_progress = try progress.start("", llvm_targets.len);
defer root_progress.end();
if (std.builtin.single_threaded) {
for (llvm_targets) |llvm_target| {
try processOneTarget(Job{
.llvm_tblgen_exe = llvm_tblgen_exe,
.llvm_src_root = llvm_src_root,
.zig_src_dir = zig_src_dir,
.root_progress = root_progress,
.llvm_target = llvm_target,
});
}
} else {
var threads = try arena.alloc(*std.Thread, llvm_targets.len);
for (llvm_targets) |llvm_target, i| {
threads[i] = try std.Thread.spawn(processOneTarget, .{
.llvm_tblgen_exe = llvm_tblgen_exe,
.llvm_src_root = llvm_src_root,
.zig_src_dir = zig_src_dir,
.root_progress = root_progress,
.llvm_target = llvm_target,
});
}
for (threads) |thread| {
thread.wait();
}
}
}
const Job = struct {
llvm_tblgen_exe: []const u8,
llvm_src_root: []const u8,
zig_src_dir: std.fs.Dir,
root_progress: *std.Progress.Node,
llvm_target: LlvmTarget,
};
fn processOneTarget(job: Job) anyerror!void {
const llvm_target = job.llvm_target;
var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena_state.deinit();
const arena = &arena_state.allocator;
var progress_node = job.root_progress.start(llvm_target.zig_name, 3);
progress_node.activate();
defer progress_node.end();
var tblgen_progress = progress_node.start("invoke llvm-tblgen", 0);
tblgen_progress.activate();
const child_args = [_][]const u8{
job.llvm_tblgen_exe,
"--dump-json",
try std.fmt.allocPrint(arena, "{s}/llvm/lib/Target/{s}/{s}", .{
job.llvm_src_root,
llvm_target.llvm_name,
llvm_target.td_name,
}),
try std.fmt.allocPrint(arena, "-I={s}/llvm/include", .{job.llvm_src_root}),
try std.fmt.allocPrint(arena, "-I={s}/llvm/lib/Target/{s}", .{
job.llvm_src_root, llvm_target.llvm_name,
}),
};
const child_result = try std.ChildProcess.exec(.{
.allocator = arena,
.argv = &child_args,
.max_output_bytes = 200 * 1024 * 1024,
});
tblgen_progress.end();
if (child_result.stderr.len != 0) {
std.debug.warn("{s}\n", .{child_result.stderr});
}
const json_text = switch (child_result.term) {
.Exited => |code| if (code == 0) child_result.stdout else {
std.debug.warn("llvm-tblgen exited with code {d}\n", .{code});
std.process.exit(1);
},
else => {
std.debug.warn("llvm-tblgen crashed\n", .{});
std.process.exit(1);
},
};
var json_parse_progress = progress_node.start("parse JSON", 0);
json_parse_progress.activate();
var parser = json.Parser.init(arena, false);
const tree = try parser.parse(json_text);
json_parse_progress.end();
var render_progress = progress_node.start("render zig code", 0);
render_progress.activate();
const root_map = &tree.root.Object;
var features_table = std.StringHashMap(Feature).init(arena);
var all_features = std.ArrayList(Feature).init(arena);
var all_cpus = std.ArrayList(Cpu).init(arena);
{
var it = root_map.iterator();
root_it: while (it.next()) |kv| {
if (kv.key_ptr.len == 0) continue;
if (kv.key_ptr.*[0] == '!') continue;
if (kv.value_ptr.* != .Object) continue;
if (hasSuperclass(&kv.value_ptr.Object, "SubtargetFeature")) {
const llvm_name = kv.value_ptr.Object.get("Name").?.String;
if (llvm_name.len == 0) continue;
var zig_name = try llvmNameToZigName(arena, llvm_name);
var desc = kv.value_ptr.Object.get("Desc").?.String;
var deps = std.ArrayList([]const u8).init(arena);
var omit = false;
var flatten = false;
const implies = kv.value_ptr.Object.get("Implies").?.Array;
for (implies.items) |imply| {
const other_key = imply.Object.get("def").?.String;
const other_obj = &root_map.getPtr(other_key).?.Object;
const other_llvm_name = other_obj.get("Name").?.String;
const other_zig_name = (try llvmNameToZigNameOmit(
arena,
llvm_target,
other_llvm_name,
)) orelse continue;
try deps.append(other_zig_name);
}
for (llvm_target.feature_overrides) |feature_override| {
if (mem.eql(u8, llvm_name, feature_override.llvm_name)) {
if (feature_override.omit) {
// Still put the feature into the table so that we can
// expand dependencies for the feature overrides marked `flatten`.
omit = true;
}
if (feature_override.flatten) {
flatten = true;
}
if (feature_override.zig_name) |override_name| {
zig_name = override_name;
}
if (feature_override.desc) |override_desc| {
desc = override_desc;
}
for (feature_override.extra_deps) |extra_dep| {
try deps.append(extra_dep);
}
break;
}
}
const feature: Feature = .{
.llvm_name = llvm_name,
.zig_name = zig_name,
.desc = desc,
.deps = deps.items,
.flatten = flatten,
};
try features_table.put(zig_name, feature);
if (!omit and !flatten) {
try all_features.append(feature);
}
}
if (hasSuperclass(&kv.value_ptr.Object, "Processor")) {
const llvm_name = kv.value_ptr.Object.get("Name").?.String;
if (llvm_name.len == 0) continue;
var zig_name = try llvmNameToZigName(arena, llvm_name);
var deps = std.ArrayList([]const u8).init(arena);
const features = kv.value_ptr.Object.get("Features").?.Array;
for (features.items) |feature| {
const feature_key = feature.Object.get("def").?.String;
const feature_obj = &root_map.getPtr(feature_key).?.Object;
const feature_llvm_name = feature_obj.get("Name").?.String;
if (feature_llvm_name.len == 0) continue;
const feature_zig_name = (try llvmNameToZigNameOmit(
arena,
llvm_target,
feature_llvm_name,
)) orelse continue;
try deps.append(feature_zig_name);
}
const tune_features = kv.value_ptr.Object.get("TuneFeatures").?.Array;
for (tune_features.items) |feature| {
const feature_key = feature.Object.get("def").?.String;
const feature_obj = &root_map.getPtr(feature_key).?.Object;
const feature_llvm_name = feature_obj.get("Name").?.String;
if (feature_llvm_name.len == 0) continue;
const feature_zig_name = (try llvmNameToZigNameOmit(
arena,
llvm_target,
feature_llvm_name,
)) orelse continue;
try deps.append(feature_zig_name);
}
for (llvm_target.feature_overrides) |feature_override| {
if (mem.eql(u8, llvm_name, feature_override.llvm_name)) {
if (feature_override.omit) {
continue :root_it;
}
if (feature_override.zig_name) |override_name| {
zig_name = override_name;
}
for (feature_override.extra_deps) |extra_dep| {
try deps.append(extra_dep);
}
break;
}
}
try all_cpus.append(.{
.llvm_name = llvm_name,
.zig_name = zig_name,
.features = deps.items,
});
}
}
}
for (llvm_target.extra_features) |extra_feature| {
try features_table.put(extra_feature.zig_name, extra_feature);
try all_features.append(extra_feature);
}
for (llvm_target.extra_cpus) |extra_cpu| {
try all_cpus.append(extra_cpu);
}
std.sort.sort(Feature, all_features.items, {}, featureLessThan);
std.sort.sort(Cpu, all_cpus.items, {}, cpuLessThan);
const target_sub_path = try fs.path.join(arena, &.{ "lib", "std", "target" });
var target_dir = try job.zig_src_dir.makeOpenPath(target_sub_path, .{});
defer target_dir.close();
const zig_code_basename = try std.fmt.allocPrint(arena, "{s}.zig", .{llvm_target.zig_name});
if (all_features.items.len == 0) {
// We represent this with an empty file.
try target_dir.deleteTree(zig_code_basename);
return;
}
var zig_code_file = try target_dir.createFile(zig_code_basename, .{});
defer zig_code_file.close();
var bw = std.io.bufferedWriter(zig_code_file.writer());
const w = bw.writer();
try w.writeAll(
\\//! This file is auto-generated by tools/update_cpu_features.zig.
\\
\\const std = @import("../std.zig");
\\const CpuFeature = std.Target.Cpu.Feature;
\\const CpuModel = std.Target.Cpu.Model;
\\
\\pub const Feature = enum {
\\
);
for (all_features.items) |feature| {
try w.print(" {},\n", .{std.zig.fmtId(feature.zig_name)});
}
try w.writeAll(
\\};
\\
\\pub usingnamespace CpuFeature.feature_set_fns(Feature);
\\
\\pub const all_features = blk: {
\\
);
if (llvm_target.branch_quota) |branch_quota| {
try w.print(" @setEvalBranchQuota({d});\n", .{branch_quota});
}
try w.writeAll(
\\ const len = @typeInfo(Feature).Enum.fields.len;
\\ std.debug.assert(len <= CpuFeature.Set.needed_bit_count);
\\ var result: [len]CpuFeature = undefined;
\\
);
for (all_features.items) |feature| {
if (feature.llvm_name) |llvm_name| {
try w.print(
\\ result[@enumToInt(Feature.{})] = .{{
\\ .llvm_name = "{}",
\\ .description = "{}",
\\ .dependencies = featureSet(&[_]Feature{{
,
.{
std.zig.fmtId(feature.zig_name),
std.zig.fmtEscapes(llvm_name),
std.zig.fmtEscapes(feature.desc),
},
);
} else {
try w.print(
\\ result[@enumToInt(Feature.{})] = .{{
\\ .llvm_name = null,
\\ .description = "{}",
\\ .dependencies = featureSet(&[_]Feature{{
,
.{
std.zig.fmtId(feature.zig_name),
std.zig.fmtEscapes(feature.desc),
},
);
}
var deps_set = std.StringHashMap(void).init(arena);
for (feature.deps) |dep| {
try putDep(&deps_set, features_table, dep);
}
try pruneFeatures(arena, features_table, &deps_set);
var dependencies = std.ArrayList([]const u8).init(arena);
{
var it = deps_set.keyIterator();
while (it.next()) |key| {
try dependencies.append(key.*);
}
}
std.sort.sort([]const u8, dependencies.items, {}, asciiLessThan);
if (dependencies.items.len == 0) {
try w.writeAll(
\\}),
\\ };
\\
);
} else {
try w.writeAll("\n");
for (dependencies.items) |dep| {
try w.print(" .{},\n", .{std.zig.fmtId(dep)});
}
try w.writeAll(
\\ }),
\\ };
\\
);
}
}
try w.writeAll(
\\ const ti = @typeInfo(Feature);
\\ for (result) |*elem, i| {
\\ elem.index = i;
\\ elem.name = ti.Enum.fields[i].name;
\\ }
\\ break :blk result;
\\};
\\
\\pub const cpu = struct {
\\
);
for (all_cpus.items) |cpu| {
var deps_set = std.StringHashMap(void).init(arena);
for (cpu.features) |feature_zig_name| {
try putDep(&deps_set, features_table, feature_zig_name);
}
try pruneFeatures(arena, features_table, &deps_set);
var cpu_features = std.ArrayList([]const u8).init(arena);
{
var it = deps_set.keyIterator();
while (it.next()) |key| {
try cpu_features.append(key.*);
}
}
std.sort.sort([]const u8, cpu_features.items, {}, asciiLessThan);
if (cpu.llvm_name) |llvm_name| {
try w.print(
\\ pub const {} = CpuModel{{
\\ .name = "{}",
\\ .llvm_name = "{}",
\\ .features = featureSet(&[_]Feature{{
, .{
std.zig.fmtId(cpu.zig_name),
std.zig.fmtEscapes(cpu.zig_name),
std.zig.fmtEscapes(llvm_name),
});
} else {
try w.print(
\\ pub const {} = CpuModel{{
\\ .name = "{}",
\\ .llvm_name = null,
\\ .features = featureSet(&[_]Feature{{
, .{
std.zig.fmtId(cpu.zig_name),
std.zig.fmtEscapes(cpu.zig_name),
});
}
if (cpu_features.items.len == 0) {
try w.writeAll(
\\}),
\\ };
\\
);
} else {
try w.writeAll("\n");
for (cpu_features.items) |feature_zig_name| {
try w.print(" .{},\n", .{std.zig.fmtId(feature_zig_name)});
}
try w.writeAll(
\\ }),
\\ };
\\
);
}
}
try w.writeAll(
\\};
\\
);
try bw.flush();
render_progress.end();
}
fn usageAndExit(file: fs.File, arg0: []const u8, code: u8) noreturn {
file.writer().print(
\\Usage: {s} /path/to/llvm-tblgen /path/git/llvm-project /path/git/zig
\\
\\Updates lib/std/target/<target>.zig from llvm/lib/Target/<Target>/<Target>.td .
\\
\\On a less beefy system, or when debugging, compile with --single-threaded.
\\
, .{arg0}) catch std.process.exit(1);
std.process.exit(code);
}
fn featureLessThan(context: void, a: Feature, b: Feature) bool {
return std.ascii.lessThanIgnoreCase(a.zig_name, b.zig_name);
}
fn cpuLessThan(context: void, a: Cpu, b: Cpu) bool {
return std.ascii.lessThanIgnoreCase(a.zig_name, b.zig_name);
}
fn asciiLessThan(context: void, a: []const u8, b: []const u8) bool {
return std.ascii.lessThanIgnoreCase(a, b);
}
fn llvmNameToZigName(arena: *mem.Allocator, llvm_name: []const u8) ![]const u8 {
const duped = try arena.dupe(u8, llvm_name);
for (duped) |*byte| switch (byte.*) {
'-', '.' => byte.* = '_',
else => continue,
};
return duped;
}
fn llvmNameToZigNameOmit(
arena: *mem.Allocator,
llvm_target: LlvmTarget,
llvm_name: []const u8,
) !?[]const u8 {
for (llvm_target.feature_overrides) |feature_override| {
if (mem.eql(u8, feature_override.llvm_name, llvm_name)) {
if (feature_override.omit) return null;
return feature_override.zig_name orelse break;
}
}
return try llvmNameToZigName(arena, llvm_name);
}
fn hasSuperclass(obj: *json.ObjectMap, class_name: []const u8) bool {
const superclasses_json = obj.get("!superclasses") orelse return false;
for (superclasses_json.Array.items) |superclass_json| {
const superclass = superclass_json.String;
if (std.mem.eql(u8, superclass, class_name)) {
return true;
}
}
return false;
}
fn pruneFeatures(
arena: *mem.Allocator,
features_table: std.StringHashMap(Feature),
deps_set: *std.StringHashMap(void),
) !void {
// For each element, recursively iterate over the dependencies and add
// everything we find to a "deletion set".
// Then, iterate over the deletion set and delete all that stuff from `deps_set`.
var deletion_set = std.StringHashMap(void).init(arena);
{
var it = deps_set.keyIterator();
while (it.next()) |key| {
const feature = features_table.get(key.*).?;
try walkFeatures(features_table, &deletion_set, feature);
}
}
{
var it = deletion_set.keyIterator();
while (it.next()) |key| {
_ = deps_set.remove(key.*);
}
}
}
fn walkFeatures(
features_table: std.StringHashMap(Feature),
deletion_set: *std.StringHashMap(void),
feature: Feature,
) error{OutOfMemory}!void {
for (feature.deps) |dep| {
try deletion_set.put(dep, {});
const other_feature = features_table.get(dep).?;
try walkFeatures(features_table, deletion_set, other_feature);
}
}
fn putDep(
deps_set: *std.StringHashMap(void),
features_table: std.StringHashMap(Feature),
zig_feature_name: []const u8,
) error{OutOfMemory}!void {
const feature = features_table.get(zig_feature_name).?;
if (feature.flatten) {
for (feature.deps) |dep| {
try putDep(deps_set, features_table, dep);
}
} else {
try deps_set.put(zig_feature_name, {});
}
} | tools/update_cpu_features.zig |
const std = @import("std");
const expect = std.testing.expect;
test "continue and break" {
try runContinueAndBreakTest();
try expect(continue_and_break_counter == 8);
}
var continue_and_break_counter: i32 = 0;
fn runContinueAndBreakTest() !void {
var i: i32 = 0;
while (true) {
continue_and_break_counter += 2;
i += 1;
if (i < 4) {
continue;
}
break;
}
try expect(i == 4);
}
test "return with implicit cast from while loop" {
returnWithImplicitCastFromWhileLoopTest() catch unreachable;
}
fn returnWithImplicitCastFromWhileLoopTest() anyerror!void {
while (true) {
return;
}
}
test "while with optional as condition" {
numbers_left = 10;
var sum: i32 = 0;
while (getNumberOrNull()) |value| {
sum += value;
}
try expect(sum == 45);
}
test "while with optional as condition with else" {
numbers_left = 10;
var sum: i32 = 0;
var got_else: i32 = 0;
while (getNumberOrNull()) |value| {
sum += value;
try expect(got_else == 0);
} else {
got_else += 1;
}
try expect(sum == 45);
try expect(got_else == 1);
}
test "while with error union condition" {
numbers_left = 10;
var sum: i32 = 0;
var got_else: i32 = 0;
while (getNumberOrErr()) |value| {
sum += value;
} else |err| {
try expect(err == error.OutOfNumbers);
got_else += 1;
}
try expect(sum == 45);
try expect(got_else == 1);
}
var numbers_left: i32 = undefined;
fn getNumberOrErr() anyerror!i32 {
return if (numbers_left == 0) error.OutOfNumbers else x: {
numbers_left -= 1;
break :x numbers_left;
};
}
fn getNumberOrNull() ?i32 {
return if (numbers_left == 0) null else x: {
numbers_left -= 1;
break :x numbers_left;
};
}
test "while on optional with else result follow else prong" {
const result = while (returnNull()) |value| {
break value;
} else @as(i32, 2);
try expect(result == 2);
}
test "while on optional with else result follow break prong" {
const result = while (returnOptional(10)) |value| {
break value;
} else @as(i32, 2);
try expect(result == 10);
}
test "while on error union with else result follow else prong" {
const result = while (returnError()) |value| {
break value;
} else |_| @as(i32, 2);
try expect(result == 2);
}
test "while on error union with else result follow break prong" {
const result = while (returnSuccess(10)) |value| {
break value;
} else |_| @as(i32, 2);
try expect(result == 10);
}
test "while on bool with else result follow else prong" {
const result = while (returnFalse()) {
break @as(i32, 10);
} else @as(i32, 2);
try expect(result == 2);
}
test "while on bool with else result follow break prong" {
const result = while (returnTrue()) {
break @as(i32, 10);
} else @as(i32, 2);
try expect(result == 10);
}
fn returnNull() ?i32 {
return null;
}
fn returnOptional(x: i32) ?i32 {
return x;
}
fn returnError() anyerror!i32 {
return error.YouWantedAnError;
}
fn returnSuccess(x: i32) anyerror!i32 {
return x;
}
fn returnFalse() bool {
return false;
}
fn returnTrue() bool {
return true;
}
test "while bool 2 break statements and an else" {
const S = struct {
fn entry(t: bool, f: bool) !void {
var ok = false;
ok = while (t) {
if (f) break false;
if (t) break true;
} else false;
try expect(ok);
}
};
try S.entry(true, false);
comptime try S.entry(true, false);
}
test "while optional 2 break statements and an else" {
const S = struct {
fn entry(opt_t: ?bool, f: bool) !void {
var ok = false;
ok = while (opt_t) |t| {
if (f) break false;
if (t) break true;
} else false;
try expect(ok);
}
};
try S.entry(true, false);
comptime try S.entry(true, false);
}
test "while error 2 break statements and an else" {
const S = struct {
fn entry(opt_t: anyerror!bool, f: bool) !void {
var ok = false;
ok = while (opt_t) |t| {
if (f) break false;
if (t) break true;
} else |_| false;
try expect(ok);
}
};
try S.entry(true, false);
comptime try S.entry(true, false);
} | test/behavior/while_stage1.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayListUnmanaged = std.ArrayListUnmanaged;
const max_line_len = 4096;
pub const History = struct {
allocator: Allocator,
hist: ArrayListUnmanaged([]const u8) = .{},
max_len: usize = 100,
current: usize = 0,
const Self = @This();
/// Creates a new empty history
pub fn empty(allocator: Allocator) Self {
return Self{
.allocator = allocator,
};
}
/// Deinitializes the history
pub fn deinit(self: *Self) void {
for (self.hist.items) |x| self.allocator.free(x);
self.hist.deinit(self.allocator);
}
/// Ensures that at most self.max_len items are in the history
fn truncate(self: *Self) void {
if (self.hist.items.len > self.max_len) {
const surplus = self.hist.items.len - self.max_len;
for (self.hist.items[0..surplus]) |x| self.allocator.free(x);
std.mem.copy([]const u8, self.hist.items[0..self.max_len], self.hist.items[surplus..]);
self.hist.shrinkAndFree(self.allocator, self.max_len);
}
}
/// Adds this line to the history. Does not take ownership of the line, but
/// instead copies it
pub fn add(self: *Self, line: []const u8) !void {
if (self.hist.items.len < 1 or !std.mem.eql(u8, line, self.hist.items[self.hist.items.len - 1])) {
try self.hist.append(self.allocator, try self.allocator.dupe(u8, line));
self.truncate();
}
}
/// Removes the last item (newest item) of the history
pub fn pop(self: *Self) void {
self.allocator.free(self.hist.pop());
}
/// Loads the history from a file
pub fn load(self: *Self, path: []const u8) !void {
const file = try std.fs.cwd().openFile(path, .{});
defer file.close();
const reader = file.reader();
while (reader.readUntilDelimiterAlloc(self.allocator, '\n', max_line_len)) |line| {
try self.hist.append(self.allocator, line);
} else |err| {
switch (err) {
error.EndOfStream => return,
else => return err,
}
}
self.truncate();
}
/// Saves the history to a file
pub fn save(self: *Self, path: []const u8) !void {
const file = try std.fs.cwd().createFile(path, .{});
defer file.close();
for (self.hist.items) |line| {
try file.writeAll(line);
try file.writeAll("\n");
}
}
/// Sets the maximum number of history items. If more history
/// items than len exist, this will truncate the history to the
/// len most recent items.
pub fn setMaxLen(self: *Self, len: usize) !void {
self.max_len = len;
self.truncate();
}
};
test "history" {
var hist = History.empty(std.testing.allocator);
defer hist.deinit();
try hist.add("Hello");
hist.pop();
} | src/history.zig |
const std = @import("std");
const builtin = @import("builtin");
const io = std.io;
const Allocator = std.mem.Allocator;
const deflate_const = @import("deflate_const.zig");
const hm_code = @import("huffman_code.zig");
const token = @import("token.zig");
// The first length code.
const length_codes_start = 257;
// The number of codegen codes.
const codegen_code_count = 19;
const bad_code = 255;
// buffer_flush_size indicates the buffer size
// after which bytes are flushed to the writer.
// Should preferably be a multiple of 6, since
// we accumulate 6 bytes between writes to the buffer.
const buffer_flush_size = 240;
// buffer_size is the actual output byte buffer size.
// It must have additional headroom for a flush
// which can contain up to 8 bytes.
const buffer_size = buffer_flush_size + 8;
// The number of extra bits needed by length code X - LENGTH_CODES_START.
var length_extra_bits = [_]u8{
0, 0, 0, // 257
0, 0, 0, 0, 0, 1, 1, 1, 1, 2, // 260
2, 2, 2, 3, 3, 3, 3, 4, 4, 4, // 270
4, 5, 5, 5, 5, 0, // 280
};
// The length indicated by length code X - LENGTH_CODES_START.
var length_base = [_]u32{
0, 1, 2, 3, 4, 5, 6, 7, 8, 10,
12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
64, 80, 96, 112, 128, 160, 192, 224, 255,
};
// offset code word extra bits.
var offset_extra_bits = [_]i8{
0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
};
var offset_base = [_]u32{
0x000000, 0x000001, 0x000002, 0x000003, 0x000004,
0x000006, 0x000008, 0x00000c, 0x000010, 0x000018,
0x000020, 0x000030, 0x000040, 0x000060, 0x000080,
0x0000c0, 0x000100, 0x000180, 0x000200, 0x000300,
0x000400, 0x000600, 0x000800, 0x000c00, 0x001000,
0x001800, 0x002000, 0x003000, 0x004000, 0x006000,
};
// The odd order in which the codegen code sizes are written.
var codegen_order = [_]u32{ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
pub fn HuffmanBitWriter(comptime WriterType: type) type {
return struct {
const Self = @This();
pub const Error = WriterType.Error;
// writer is the underlying writer.
// Do not use it directly; use the write method, which ensures
// that Write errors are sticky.
inner_writer: WriterType,
bytes_written: usize,
// Data waiting to be written is bytes[0 .. nbytes]
// and then the low nbits of bits. Data is always written
// sequentially into the bytes array.
bits: u64,
nbits: u32, // number of bits
bytes: [buffer_size]u8,
codegen_freq: [codegen_code_count]u16,
nbytes: u32, // number of bytes
literal_freq: []u16,
offset_freq: []u16,
codegen: []u8,
literal_encoding: hm_code.HuffmanEncoder,
offset_encoding: hm_code.HuffmanEncoder,
codegen_encoding: hm_code.HuffmanEncoder,
err: bool = false,
fixed_literal_encoding: hm_code.HuffmanEncoder,
fixed_offset_encoding: hm_code.HuffmanEncoder,
allocator: Allocator,
huff_offset: hm_code.HuffmanEncoder,
pub fn reset(self: *Self, new_writer: WriterType) void {
self.inner_writer = new_writer;
self.bytes_written = 0;
self.bits = 0;
self.nbits = 0;
self.nbytes = 0;
self.err = false;
}
pub fn flush(self: *Self) Error!void {
if (self.err) {
self.nbits = 0;
return;
}
var n = self.nbytes;
while (self.nbits != 0) {
self.bytes[n] = @truncate(u8, self.bits);
self.bits >>= 8;
if (self.nbits > 8) { // Avoid underflow
self.nbits -= 8;
} else {
self.nbits = 0;
}
n += 1;
}
self.bits = 0;
try self.write(self.bytes[0..n]);
self.nbytes = 0;
}
fn write(self: *Self, b: []u8) Error!void {
if (self.err) {
return;
}
self.bytes_written += try self.inner_writer.write(b);
}
fn writeBits(self: *Self, b: u32, nb: u32) Error!void {
if (self.err) {
return;
}
self.bits |= @intCast(u64, b) << @intCast(u6, self.nbits);
self.nbits += nb;
if (self.nbits >= 48) {
var bits = self.bits;
self.bits >>= 48;
self.nbits -= 48;
var n = self.nbytes;
var bytes = self.bytes[n .. n + 6];
bytes[0] = @truncate(u8, bits);
bytes[1] = @truncate(u8, bits >> 8);
bytes[2] = @truncate(u8, bits >> 16);
bytes[3] = @truncate(u8, bits >> 24);
bytes[4] = @truncate(u8, bits >> 32);
bytes[5] = @truncate(u8, bits >> 40);
n += 6;
if (n >= buffer_flush_size) {
try self.write(self.bytes[0..n]);
n = 0;
}
self.nbytes = n;
}
}
pub fn writeBytes(self: *Self, bytes: []u8) Error!void {
if (self.err) {
return;
}
var n = self.nbytes;
if (self.nbits & 7 != 0) {
self.err = true; // unfinished bits
return;
}
while (self.nbits != 0) {
self.bytes[n] = @truncate(u8, self.bits);
self.bits >>= 8;
self.nbits -= 8;
n += 1;
}
if (n != 0) {
try self.write(self.bytes[0..n]);
}
self.nbytes = 0;
try self.write(bytes);
}
// RFC 1951 3.2.7 specifies a special run-length encoding for specifying
// the literal and offset lengths arrays (which are concatenated into a single
// array). This method generates that run-length encoding.
//
// The result is written into the codegen array, and the frequencies
// of each code is written into the codegen_freq array.
// Codes 0-15 are single byte codes. Codes 16-18 are followed by additional
// information. Code bad_code is an end marker
//
// num_literals: The number of literals in literal_encoding
// num_offsets: The number of offsets in offset_encoding
// lit_enc: The literal encoder to use
// off_enc: The offset encoder to use
fn generateCodegen(
self: *Self,
num_literals: u32,
num_offsets: u32,
lit_enc: *hm_code.HuffmanEncoder,
off_enc: *hm_code.HuffmanEncoder,
) void {
for (self.codegen_freq) |_, i| {
self.codegen_freq[i] = 0;
}
// Note that we are using codegen both as a temporary variable for holding
// a copy of the frequencies, and as the place where we put the result.
// This is fine because the output is always shorter than the input used
// so far.
var codegen = self.codegen; // cache
// Copy the concatenated code sizes to codegen. Put a marker at the end.
var cgnl = codegen[0..num_literals];
for (cgnl) |_, i| {
cgnl[i] = @intCast(u8, lit_enc.codes[i].len);
}
cgnl = codegen[num_literals .. num_literals + num_offsets];
for (cgnl) |_, i| {
cgnl[i] = @intCast(u8, off_enc.codes[i].len);
}
codegen[num_literals + num_offsets] = bad_code;
var size = codegen[0];
var count: i32 = 1;
var out_index: u32 = 0;
var in_index: u32 = 1;
while (size != bad_code) : (in_index += 1) {
// INVARIANT: We have seen "count" copies of size that have not yet
// had output generated for them.
var next_size = codegen[in_index];
if (next_size == size) {
count += 1;
continue;
}
// We need to generate codegen indicating "count" of size.
if (size != 0) {
codegen[out_index] = size;
out_index += 1;
self.codegen_freq[size] += 1;
count -= 1;
while (count >= 3) {
var n: i32 = 6;
if (n > count) {
n = count;
}
codegen[out_index] = 16;
out_index += 1;
codegen[out_index] = @intCast(u8, n - 3);
out_index += 1;
self.codegen_freq[16] += 1;
count -= n;
}
} else {
while (count >= 11) {
var n: i32 = 138;
if (n > count) {
n = count;
}
codegen[out_index] = 18;
out_index += 1;
codegen[out_index] = @intCast(u8, n - 11);
out_index += 1;
self.codegen_freq[18] += 1;
count -= n;
}
if (count >= 3) {
// 3 <= count <= 10
codegen[out_index] = 17;
out_index += 1;
codegen[out_index] = @intCast(u8, count - 3);
out_index += 1;
self.codegen_freq[17] += 1;
count = 0;
}
}
count -= 1;
while (count >= 0) : (count -= 1) {
codegen[out_index] = size;
out_index += 1;
self.codegen_freq[size] += 1;
}
// Set up invariant for next time through the loop.
size = next_size;
count = 1;
}
// Marker indicating the end of the codegen.
codegen[out_index] = bad_code;
}
// dynamicSize returns the size of dynamically encoded data in bits.
fn dynamicSize(
self: *Self,
lit_enc: *hm_code.HuffmanEncoder, // literal encoder
off_enc: *hm_code.HuffmanEncoder, // offset encoder
extra_bits: u32,
) DynamicSize {
var num_codegens = self.codegen_freq.len;
while (num_codegens > 4 and self.codegen_freq[codegen_order[num_codegens - 1]] == 0) {
num_codegens -= 1;
}
var header = 3 + 5 + 5 + 4 + (3 * num_codegens) +
self.codegen_encoding.bitLength(self.codegen_freq[0..]) +
self.codegen_freq[16] * 2 +
self.codegen_freq[17] * 3 +
self.codegen_freq[18] * 7;
var size = header +
lit_enc.bitLength(self.literal_freq) +
off_enc.bitLength(self.offset_freq) +
extra_bits;
return DynamicSize{
.size = @intCast(u32, size),
.num_codegens = @intCast(u32, num_codegens),
};
}
// fixedSize returns the size of dynamically encoded data in bits.
fn fixedSize(self: *Self, extra_bits: u32) u32 {
return 3 +
self.fixed_literal_encoding.bitLength(self.literal_freq) +
self.fixed_offset_encoding.bitLength(self.offset_freq) +
extra_bits;
}
// storedSizeFits calculates the stored size, including header.
// The function returns the size in bits and whether the block
// fits inside a single block.
fn storedSizeFits(in: ?[]u8) StoredSize {
if (in == null) {
return .{ .size = 0, .storable = false };
}
if (in.?.len <= deflate_const.max_store_block_size) {
return .{ .size = @intCast(u32, (in.?.len + 5) * 8), .storable = true };
}
return .{ .size = 0, .storable = false };
}
fn writeCode(self: *Self, c: hm_code.HuffCode) Error!void {
if (self.err) {
return;
}
self.bits |= @intCast(u64, c.code) << @intCast(u6, self.nbits);
self.nbits += @intCast(u32, c.len);
if (self.nbits >= 48) {
var bits = self.bits;
self.bits >>= 48;
self.nbits -= 48;
var n = self.nbytes;
var bytes = self.bytes[n .. n + 6];
bytes[0] = @truncate(u8, bits);
bytes[1] = @truncate(u8, bits >> 8);
bytes[2] = @truncate(u8, bits >> 16);
bytes[3] = @truncate(u8, bits >> 24);
bytes[4] = @truncate(u8, bits >> 32);
bytes[5] = @truncate(u8, bits >> 40);
n += 6;
if (n >= buffer_flush_size) {
try self.write(self.bytes[0..n]);
n = 0;
}
self.nbytes = n;
}
}
// Write the header of a dynamic Huffman block to the output stream.
//
// num_literals: The number of literals specified in codegen
// num_offsets: The number of offsets specified in codegen
// num_codegens: The number of codegens used in codegen
// is_eof: Is it the end-of-file? (end of stream)
fn writeDynamicHeader(
self: *Self,
num_literals: u32,
num_offsets: u32,
num_codegens: u32,
is_eof: bool,
) Error!void {
if (self.err) {
return;
}
var first_bits: u32 = 4;
if (is_eof) {
first_bits = 5;
}
try self.writeBits(first_bits, 3);
try self.writeBits(@intCast(u32, num_literals - 257), 5);
try self.writeBits(@intCast(u32, num_offsets - 1), 5);
try self.writeBits(@intCast(u32, num_codegens - 4), 4);
var i: u32 = 0;
while (i < num_codegens) : (i += 1) {
var value = @intCast(u32, self.codegen_encoding.codes[codegen_order[i]].len);
try self.writeBits(@intCast(u32, value), 3);
}
i = 0;
while (true) {
var code_word: u32 = @intCast(u32, self.codegen[i]);
i += 1;
if (code_word == bad_code) {
break;
}
try self.writeCode(self.codegen_encoding.codes[@intCast(u32, code_word)]);
switch (code_word) {
16 => {
try self.writeBits(@intCast(u32, self.codegen[i]), 2);
i += 1;
},
17 => {
try self.writeBits(@intCast(u32, self.codegen[i]), 3);
i += 1;
},
18 => {
try self.writeBits(@intCast(u32, self.codegen[i]), 7);
i += 1;
},
else => {},
}
}
}
pub fn writeStoredHeader(self: *Self, length: usize, is_eof: bool) Error!void {
if (self.err) {
return;
}
var flag: u32 = 0;
if (is_eof) {
flag = 1;
}
try self.writeBits(flag, 3);
try self.flush();
try self.writeBits(@intCast(u32, length), 16);
try self.writeBits(@intCast(u32, ~@intCast(u16, length)), 16);
}
fn writeFixedHeader(self: *Self, is_eof: bool) Error!void {
if (self.err) {
return;
}
// Indicate that we are a fixed Huffman block
var value: u32 = 2;
if (is_eof) {
value = 3;
}
try self.writeBits(value, 3);
}
// Write a block of tokens with the smallest encoding.
// The original input can be supplied, and if the huffman encoded data
// is larger than the original bytes, the data will be written as a
// stored block.
// If the input is null, the tokens will always be Huffman encoded.
pub fn writeBlock(
self: *Self,
tokens: []const token.Token,
eof: bool,
input: ?[]u8,
) Error!void {
if (self.err) {
return;
}
var lit_and_off = self.indexTokens(tokens);
var num_literals = lit_and_off.num_literals;
var num_offsets = lit_and_off.num_offsets;
var extra_bits: u32 = 0;
var ret = storedSizeFits(input);
var stored_size = ret.size;
var storable = ret.storable;
if (storable) {
// We only bother calculating the costs of the extra bits required by
// the length of offset fields (which will be the same for both fixed
// and dynamic encoding), if we need to compare those two encodings
// against stored encoding.
var length_code: u32 = length_codes_start + 8;
while (length_code < num_literals) : (length_code += 1) {
// First eight length codes have extra size = 0.
extra_bits += @intCast(u32, self.literal_freq[length_code]) *
@intCast(u32, length_extra_bits[length_code - length_codes_start]);
}
var offset_code: u32 = 4;
while (offset_code < num_offsets) : (offset_code += 1) {
// First four offset codes have extra size = 0.
extra_bits += @intCast(u32, self.offset_freq[offset_code]) *
@intCast(u32, offset_extra_bits[offset_code]);
}
}
// Figure out smallest code.
// Fixed Huffman baseline.
var literal_encoding = &self.fixed_literal_encoding;
var offset_encoding = &self.fixed_offset_encoding;
var size = self.fixedSize(extra_bits);
// Dynamic Huffman?
var num_codegens: u32 = 0;
// Generate codegen and codegenFrequencies, which indicates how to encode
// the literal_encoding and the offset_encoding.
self.generateCodegen(
num_literals,
num_offsets,
&self.literal_encoding,
&self.offset_encoding,
);
self.codegen_encoding.generate(self.codegen_freq[0..], 7);
var dynamic_size = self.dynamicSize(
&self.literal_encoding,
&self.offset_encoding,
extra_bits,
);
var dyn_size = dynamic_size.size;
num_codegens = dynamic_size.num_codegens;
if (dyn_size < size) {
size = dyn_size;
literal_encoding = &self.literal_encoding;
offset_encoding = &self.offset_encoding;
}
// Stored bytes?
if (storable and stored_size < size) {
try self.writeStoredHeader(input.?.len, eof);
try self.writeBytes(input.?);
return;
}
// Huffman.
if (@ptrToInt(literal_encoding) == @ptrToInt(&self.fixed_literal_encoding)) {
try self.writeFixedHeader(eof);
} else {
try self.writeDynamicHeader(num_literals, num_offsets, num_codegens, eof);
}
// Write the tokens.
try self.writeTokens(tokens, literal_encoding.codes, offset_encoding.codes);
}
// writeBlockDynamic encodes a block using a dynamic Huffman table.
// This should be used if the symbols used have a disproportionate
// histogram distribution.
// If input is supplied and the compression savings are below 1/16th of the
// input size the block is stored.
pub fn writeBlockDynamic(
self: *Self,
tokens: []const token.Token,
eof: bool,
input: ?[]u8,
) Error!void {
if (self.err) {
return;
}
var total_tokens = self.indexTokens(tokens);
var num_literals = total_tokens.num_literals;
var num_offsets = total_tokens.num_offsets;
// Generate codegen and codegenFrequencies, which indicates how to encode
// the literal_encoding and the offset_encoding.
self.generateCodegen(
num_literals,
num_offsets,
&self.literal_encoding,
&self.offset_encoding,
);
self.codegen_encoding.generate(self.codegen_freq[0..], 7);
var dynamic_size = self.dynamicSize(&self.literal_encoding, &self.offset_encoding, 0);
var size = dynamic_size.size;
var num_codegens = dynamic_size.num_codegens;
// Store bytes, if we don't get a reasonable improvement.
var stored_size = storedSizeFits(input);
var ssize = stored_size.size;
var storable = stored_size.storable;
if (storable and ssize < (size + (size >> 4))) {
try self.writeStoredHeader(input.?.len, eof);
try self.writeBytes(input.?);
return;
}
// Write Huffman table.
try self.writeDynamicHeader(num_literals, num_offsets, num_codegens, eof);
// Write the tokens.
try self.writeTokens(tokens, self.literal_encoding.codes, self.offset_encoding.codes);
}
const TotalIndexedTokens = struct {
num_literals: u32,
num_offsets: u32,
};
// Indexes a slice of tokens followed by an end_block_marker, and updates
// literal_freq and offset_freq, and generates literal_encoding
// and offset_encoding.
// The number of literal and offset tokens is returned.
fn indexTokens(self: *Self, tokens: []const token.Token) TotalIndexedTokens {
var num_literals: u32 = 0;
var num_offsets: u32 = 0;
for (self.literal_freq) |_, i| {
self.literal_freq[i] = 0;
}
for (self.offset_freq) |_, i| {
self.offset_freq[i] = 0;
}
for (tokens) |t| {
if (t < token.match_type) {
self.literal_freq[token.literal(t)] += 1;
continue;
}
var length = token.length(t);
var offset = token.offset(t);
self.literal_freq[length_codes_start + token.lengthCode(length)] += 1;
self.offset_freq[token.offsetCode(offset)] += 1;
}
// add end_block_marker token at the end
self.literal_freq[token.literal(deflate_const.end_block_marker)] += 1;
// get the number of literals
num_literals = @intCast(u32, self.literal_freq.len);
while (self.literal_freq[num_literals - 1] == 0) {
num_literals -= 1;
}
// get the number of offsets
num_offsets = @intCast(u32, self.offset_freq.len);
while (num_offsets > 0 and self.offset_freq[num_offsets - 1] == 0) {
num_offsets -= 1;
}
if (num_offsets == 0) {
// We haven't found a single match. If we want to go with the dynamic encoding,
// we should count at least one offset to be sure that the offset huffman tree could be encoded.
self.offset_freq[0] = 1;
num_offsets = 1;
}
self.literal_encoding.generate(self.literal_freq, 15);
self.offset_encoding.generate(self.offset_freq, 15);
return TotalIndexedTokens{
.num_literals = num_literals,
.num_offsets = num_offsets,
};
}
// Writes a slice of tokens to the output followed by and end_block_marker.
// codes for literal and offset encoding must be supplied.
fn writeTokens(
self: *Self,
tokens: []const token.Token,
le_codes: []hm_code.HuffCode,
oe_codes: []hm_code.HuffCode,
) Error!void {
if (self.err) {
return;
}
for (tokens) |t| {
if (t < token.match_type) {
try self.writeCode(le_codes[token.literal(t)]);
continue;
}
// Write the length
var length = token.length(t);
var length_code = token.lengthCode(length);
try self.writeCode(le_codes[length_code + length_codes_start]);
var extra_length_bits = @intCast(u32, length_extra_bits[length_code]);
if (extra_length_bits > 0) {
var extra_length = @intCast(u32, length - length_base[length_code]);
try self.writeBits(extra_length, extra_length_bits);
}
// Write the offset
var offset = token.offset(t);
var offset_code = token.offsetCode(offset);
try self.writeCode(oe_codes[offset_code]);
var extra_offset_bits = @intCast(u32, offset_extra_bits[offset_code]);
if (extra_offset_bits > 0) {
var extra_offset = @intCast(u32, offset - offset_base[offset_code]);
try self.writeBits(extra_offset, extra_offset_bits);
}
}
// add end_block_marker at the end
try self.writeCode(le_codes[token.literal(deflate_const.end_block_marker)]);
}
// Encodes a block of bytes as either Huffman encoded literals or uncompressed bytes
// if the results only gains very little from compression.
pub fn writeBlockHuff(self: *Self, eof: bool, input: []u8) Error!void {
if (self.err) {
return;
}
// Clear histogram
for (self.literal_freq) |_, i| {
self.literal_freq[i] = 0;
}
// Add everything as literals
histogram(input, &self.literal_freq);
self.literal_freq[deflate_const.end_block_marker] = 1;
const num_literals = deflate_const.end_block_marker + 1;
self.offset_freq[0] = 1;
const num_offsets = 1;
self.literal_encoding.generate(self.literal_freq, 15);
// Figure out smallest code.
// Always use dynamic Huffman or Store
var num_codegens: u32 = 0;
// Generate codegen and codegenFrequencies, which indicates how to encode
// the literal_encoding and the offset_encoding.
self.generateCodegen(
num_literals,
num_offsets,
&self.literal_encoding,
&self.huff_offset,
);
self.codegen_encoding.generate(self.codegen_freq[0..], 7);
var dynamic_size = self.dynamicSize(&self.literal_encoding, &self.huff_offset, 0);
var size = dynamic_size.size;
num_codegens = dynamic_size.num_codegens;
// Store bytes, if we don't get a reasonable improvement.
var stored_size_ret = storedSizeFits(input);
var ssize = stored_size_ret.size;
var storable = stored_size_ret.storable;
if (storable and ssize < (size + (size >> 4))) {
try self.writeStoredHeader(input.len, eof);
try self.writeBytes(input);
return;
}
// Huffman.
try self.writeDynamicHeader(num_literals, num_offsets, num_codegens, eof);
var encoding = self.literal_encoding.codes[0..257];
var n = self.nbytes;
for (input) |t| {
// Bitwriting inlined, ~30% speedup
var c = encoding[t];
self.bits |= @intCast(u64, c.code) << @intCast(u6, self.nbits);
self.nbits += @intCast(u32, c.len);
if (self.nbits < 48) {
continue;
}
// Store 6 bytes
var bits = self.bits;
self.bits >>= 48;
self.nbits -= 48;
var bytes = self.bytes[n .. n + 6];
bytes[0] = @truncate(u8, bits);
bytes[1] = @truncate(u8, bits >> 8);
bytes[2] = @truncate(u8, bits >> 16);
bytes[3] = @truncate(u8, bits >> 24);
bytes[4] = @truncate(u8, bits >> 32);
bytes[5] = @truncate(u8, bits >> 40);
n += 6;
if (n < buffer_flush_size) {
continue;
}
try self.write(self.bytes[0..n]);
if (self.err) {
return; // Return early in the event of write failures
}
n = 0;
}
self.nbytes = n;
try self.writeCode(encoding[deflate_const.end_block_marker]);
}
pub fn deinit(self: *Self) void {
self.allocator.free(self.literal_freq);
self.allocator.free(self.offset_freq);
self.allocator.free(self.codegen);
self.literal_encoding.deinit();
self.codegen_encoding.deinit();
self.offset_encoding.deinit();
self.fixed_literal_encoding.deinit();
self.fixed_offset_encoding.deinit();
self.huff_offset.deinit();
}
};
}
const DynamicSize = struct {
size: u32,
num_codegens: u32,
};
const StoredSize = struct {
size: u32,
storable: bool,
};
pub fn huffmanBitWriter(allocator: Allocator, writer: anytype) !HuffmanBitWriter(@TypeOf(writer)) {
var offset_freq = [1]u16{0} ** deflate_const.offset_code_count;
offset_freq[0] = 1;
// huff_offset is a static offset encoder used for huffman only encoding.
// It can be reused since we will not be encoding offset values.
var huff_offset = try hm_code.newHuffmanEncoder(allocator, deflate_const.offset_code_count);
huff_offset.generate(offset_freq[0..], 15);
return HuffmanBitWriter(@TypeOf(writer)){
.inner_writer = writer,
.bytes_written = 0,
.bits = 0,
.nbits = 0,
.nbytes = 0,
.bytes = [1]u8{0} ** buffer_size,
.codegen_freq = [1]u16{0} ** codegen_code_count,
.literal_freq = try allocator.alloc(u16, deflate_const.max_num_lit),
.offset_freq = try allocator.alloc(u16, deflate_const.offset_code_count),
.codegen = try allocator.alloc(u8, deflate_const.max_num_lit + deflate_const.offset_code_count + 1),
.literal_encoding = try hm_code.newHuffmanEncoder(allocator, deflate_const.max_num_lit),
.codegen_encoding = try hm_code.newHuffmanEncoder(allocator, codegen_code_count),
.offset_encoding = try hm_code.newHuffmanEncoder(allocator, deflate_const.offset_code_count),
.allocator = allocator,
.fixed_literal_encoding = try hm_code.generateFixedLiteralEncoding(allocator),
.fixed_offset_encoding = try hm_code.generateFixedOffsetEncoding(allocator),
.huff_offset = huff_offset,
};
}
// histogram accumulates a histogram of b in h.
//
// h.len must be >= 256, and h's elements must be all zeroes.
fn histogram(b: []u8, h: *[]u16) void {
var lh = h.*[0..256];
for (b) |t| {
lh[t] += 1;
}
}
// tests
const expect = std.testing.expect;
const fmt = std.fmt;
const math = std.math;
const mem = std.mem;
const testing = std.testing;
const ArrayList = std.ArrayList;
test "writeBlockHuff" {
// Tests huffman encoding against reference files to detect possible regressions.
// If encoding/bit allocation changes you can regenerate these files
try testBlockHuff(
"huffman-null-max.input",
"huffman-null-max.golden",
);
try testBlockHuff(
"huffman-pi.input",
"huffman-pi.golden",
);
try testBlockHuff(
"huffman-rand-1k.input",
"huffman-rand-1k.golden",
);
try testBlockHuff(
"huffman-rand-limit.input",
"huffman-rand-limit.golden",
);
try testBlockHuff(
"huffman-rand-max.input",
"huffman-rand-max.golden",
);
try testBlockHuff(
"huffman-shifts.input",
"huffman-shifts.golden",
);
try testBlockHuff(
"huffman-text.input",
"huffman-text.golden",
);
try testBlockHuff(
"huffman-text-shift.input",
"huffman-text-shift.golden",
);
try testBlockHuff(
"huffman-zero.input",
"huffman-zero.golden",
);
}
fn testBlockHuff(in_name: []const u8, want_name: []const u8) !void {
// Skip wasi because it does not support std.fs.openDirAbsolute()
if (builtin.os.tag == .wasi) return error.SkipZigTest;
const current_dir = try std.fs.openDirAbsolute(std.fs.path.dirname(@src().file).?, .{});
const testdata_dir = try current_dir.openDir("testdata", .{});
const in_file = try testdata_dir.openFile(in_name, .{ .read = true });
defer in_file.close();
const want_file = try testdata_dir.openFile(want_name, .{ .read = true });
defer want_file.close();
var in = try in_file.reader().readAllAlloc(testing.allocator, math.maxInt(usize));
defer testing.allocator.free(in);
var want = try want_file.reader().readAllAlloc(testing.allocator, math.maxInt(usize));
defer testing.allocator.free(want);
var buf = ArrayList(u8).init(testing.allocator);
defer buf.deinit();
var bw = try huffmanBitWriter(testing.allocator, buf.writer());
defer bw.deinit();
try bw.writeBlockHuff(false, in);
try bw.flush();
try expect(mem.eql(u8, buf.items, want));
// Test if the writer produces the same output after reset.
var buf_after_reset = ArrayList(u8).init(testing.allocator);
defer buf_after_reset.deinit();
bw.reset(buf_after_reset.writer());
try bw.writeBlockHuff(false, in);
try bw.flush();
try expect(mem.eql(u8, buf_after_reset.items, buf.items));
try expect(mem.eql(u8, buf_after_reset.items, want));
try testWriterEOF(.write_huffman_block, &[0]token.Token{}, in);
}
const HuffTest = struct {
tokens: []const token.Token,
input: []const u8 = "", // File name of input data matching the tokens.
want: []const u8 = "", // File name of data with the expected output with input available.
want_no_input: []const u8 = "", // File name of the expected output when no input is available.
};
const ml = 0x7fc00000; // Maximum length token. Used to reduce the size of writeBlockTests
const writeBlockTests = &[_]HuffTest{
HuffTest{
.input = "huffman-null-max.input",
.want = "huffman-null-max.{s}.expect",
.want_no_input = "huffman-null-max.{s}.expect-noinput",
.tokens = &[_]token.Token{
0x0, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, 0x0, 0x0,
},
},
HuffTest{
.input = "huffman-pi.input",
.want = "huffman-pi.{s}.expect",
.want_no_input = "huffman-pi.{s}.expect-noinput",
.tokens = &[_]token.Token{
0x33, 0x2e, 0x31, 0x34, 0x31, 0x35, 0x39,
0x32, 0x36, 0x35, 0x33, 0x35, 0x38, 0x39,
0x37, 0x39, 0x33, 0x32, 0x33, 0x38, 0x34,
0x36, 0x32, 0x36, 0x34, 0x33, 0x33, 0x38,
0x33, 0x32, 0x37, 0x39, 0x35, 0x30, 0x32,
0x38, 0x38, 0x34, 0x31, 0x39, 0x37, 0x31,
0x36, 0x39, 0x33, 0x39, 0x39, 0x33, 0x37,
0x35, 0x31, 0x30, 0x35, 0x38, 0x32, 0x30,
0x39, 0x37, 0x34, 0x39, 0x34, 0x34, 0x35,
0x39, 0x32, 0x33, 0x30, 0x37, 0x38, 0x31,
0x36, 0x34, 0x30, 0x36, 0x32, 0x38, 0x36,
0x32, 0x30, 0x38, 0x39, 0x39, 0x38, 0x36,
0x32, 0x38, 0x30, 0x33, 0x34, 0x38, 0x32,
0x35, 0x33, 0x34, 0x32, 0x31, 0x31, 0x37,
0x30, 0x36, 0x37, 0x39, 0x38, 0x32, 0x31,
0x34, 0x38, 0x30, 0x38, 0x36, 0x35, 0x31,
0x33, 0x32, 0x38, 0x32, 0x33, 0x30, 0x36,
0x36, 0x34, 0x37, 0x30, 0x39, 0x33, 0x38,
0x34, 0x34, 0x36, 0x30, 0x39, 0x35, 0x35,
0x30, 0x35, 0x38, 0x32, 0x32, 0x33, 0x31,
0x37, 0x32, 0x35, 0x33, 0x35, 0x39, 0x34,
0x30, 0x38, 0x31, 0x32, 0x38, 0x34, 0x38,
0x31, 0x31, 0x31, 0x37, 0x34, 0x4040007e, 0x34,
0x31, 0x30, 0x32, 0x37, 0x30, 0x31, 0x39,
0x33, 0x38, 0x35, 0x32, 0x31, 0x31, 0x30,
0x35, 0x35, 0x35, 0x39, 0x36, 0x34, 0x34,
0x36, 0x32, 0x32, 0x39, 0x34, 0x38, 0x39,
0x35, 0x34, 0x39, 0x33, 0x30, 0x33, 0x38,
0x31, 0x40400012, 0x32, 0x38, 0x38, 0x31, 0x30,
0x39, 0x37, 0x35, 0x36, 0x36, 0x35, 0x39,
0x33, 0x33, 0x34, 0x34, 0x36, 0x40400047, 0x37,
0x35, 0x36, 0x34, 0x38, 0x32, 0x33, 0x33,
0x37, 0x38, 0x36, 0x37, 0x38, 0x33, 0x31,
0x36, 0x35, 0x32, 0x37, 0x31, 0x32, 0x30,
0x31, 0x39, 0x30, 0x39, 0x31, 0x34, 0x4040001a,
0x35, 0x36, 0x36, 0x39, 0x32, 0x33, 0x34,
0x36, 0x404000b2, 0x36, 0x31, 0x30, 0x34, 0x35,
0x34, 0x33, 0x32, 0x36, 0x40400032, 0x31, 0x33,
0x33, 0x39, 0x33, 0x36, 0x30, 0x37, 0x32,
0x36, 0x30, 0x32, 0x34, 0x39, 0x31, 0x34,
0x31, 0x32, 0x37, 0x33, 0x37, 0x32, 0x34,
0x35, 0x38, 0x37, 0x30, 0x30, 0x36, 0x36,
0x30, 0x36, 0x33, 0x31, 0x35, 0x35, 0x38,
0x38, 0x31, 0x37, 0x34, 0x38, 0x38, 0x31,
0x35, 0x32, 0x30, 0x39, 0x32, 0x30, 0x39,
0x36, 0x32, 0x38, 0x32, 0x39, 0x32, 0x35,
0x34, 0x30, 0x39, 0x31, 0x37, 0x31, 0x35,
0x33, 0x36, 0x34, 0x33, 0x36, 0x37, 0x38,
0x39, 0x32, 0x35, 0x39, 0x30, 0x33, 0x36,
0x30, 0x30, 0x31, 0x31, 0x33, 0x33, 0x30,
0x35, 0x33, 0x30, 0x35, 0x34, 0x38, 0x38,
0x32, 0x30, 0x34, 0x36, 0x36, 0x35, 0x32,
0x31, 0x33, 0x38, 0x34, 0x31, 0x34, 0x36,
0x39, 0x35, 0x31, 0x39, 0x34, 0x31, 0x35,
0x31, 0x31, 0x36, 0x30, 0x39, 0x34, 0x33,
0x33, 0x30, 0x35, 0x37, 0x32, 0x37, 0x30,
0x33, 0x36, 0x35, 0x37, 0x35, 0x39, 0x35,
0x39, 0x31, 0x39, 0x35, 0x33, 0x30, 0x39,
0x32, 0x31, 0x38, 0x36, 0x31, 0x31, 0x37,
0x404000e9, 0x33, 0x32, 0x40400009, 0x39, 0x33, 0x31,
0x30, 0x35, 0x31, 0x31, 0x38, 0x35, 0x34,
0x38, 0x30, 0x37, 0x4040010e, 0x33, 0x37, 0x39,
0x39, 0x36, 0x32, 0x37, 0x34, 0x39, 0x35,
0x36, 0x37, 0x33, 0x35, 0x31, 0x38, 0x38,
0x35, 0x37, 0x35, 0x32, 0x37, 0x32, 0x34,
0x38, 0x39, 0x31, 0x32, 0x32, 0x37, 0x39,
0x33, 0x38, 0x31, 0x38, 0x33, 0x30, 0x31,
0x31, 0x39, 0x34, 0x39, 0x31, 0x32, 0x39,
0x38, 0x33, 0x33, 0x36, 0x37, 0x33, 0x33,
0x36, 0x32, 0x34, 0x34, 0x30, 0x36, 0x35,
0x36, 0x36, 0x34, 0x33, 0x30, 0x38, 0x36,
0x30, 0x32, 0x31, 0x33, 0x39, 0x34, 0x39,
0x34, 0x36, 0x33, 0x39, 0x35, 0x32, 0x32,
0x34, 0x37, 0x33, 0x37, 0x31, 0x39, 0x30,
0x37, 0x30, 0x32, 0x31, 0x37, 0x39, 0x38,
0x40800099, 0x37, 0x30, 0x32, 0x37, 0x37, 0x30,
0x35, 0x33, 0x39, 0x32, 0x31, 0x37, 0x31,
0x37, 0x36, 0x32, 0x39, 0x33, 0x31, 0x37,
0x36, 0x37, 0x35, 0x40800232, 0x37, 0x34, 0x38,
0x31, 0x40400006, 0x36, 0x36, 0x39, 0x34, 0x30,
0x404001e7, 0x30, 0x30, 0x30, 0x35, 0x36, 0x38,
0x31, 0x32, 0x37, 0x31, 0x34, 0x35, 0x32,
0x36, 0x33, 0x35, 0x36, 0x30, 0x38, 0x32,
0x37, 0x37, 0x38, 0x35, 0x37, 0x37, 0x31,
0x33, 0x34, 0x32, 0x37, 0x35, 0x37, 0x37,
0x38, 0x39, 0x36, 0x40400129, 0x33, 0x36, 0x33,
0x37, 0x31, 0x37, 0x38, 0x37, 0x32, 0x31,
0x34, 0x36, 0x38, 0x34, 0x34, 0x30, 0x39,
0x30, 0x31, 0x32, 0x32, 0x34, 0x39, 0x35,
0x33, 0x34, 0x33, 0x30, 0x31, 0x34, 0x36,
0x35, 0x34, 0x39, 0x35, 0x38, 0x35, 0x33,
0x37, 0x31, 0x30, 0x35, 0x30, 0x37, 0x39,
0x404000ca, 0x36, 0x40400153, 0x38, 0x39, 0x32, 0x33,
0x35, 0x34, 0x404001c9, 0x39, 0x35, 0x36, 0x31,
0x31, 0x32, 0x31, 0x32, 0x39, 0x30, 0x32,
0x31, 0x39, 0x36, 0x30, 0x38, 0x36, 0x34,
0x30, 0x33, 0x34, 0x34, 0x31, 0x38, 0x31,
0x35, 0x39, 0x38, 0x31, 0x33, 0x36, 0x32,
0x39, 0x37, 0x37, 0x34, 0x40400074, 0x30, 0x39,
0x39, 0x36, 0x30, 0x35, 0x31, 0x38, 0x37,
0x30, 0x37, 0x32, 0x31, 0x31, 0x33, 0x34,
0x39, 0x40800000, 0x38, 0x33, 0x37, 0x32, 0x39,
0x37, 0x38, 0x30, 0x34, 0x39, 0x39, 0x404002da,
0x39, 0x37, 0x33, 0x31, 0x37, 0x33, 0x32,
0x38, 0x4040018a, 0x36, 0x33, 0x31, 0x38, 0x35,
0x40400301, 0x404002e8, 0x34, 0x35, 0x35, 0x33, 0x34,
0x36, 0x39, 0x30, 0x38, 0x33, 0x30, 0x32,
0x36, 0x34, 0x32, 0x35, 0x32, 0x32, 0x33,
0x30, 0x404002e3, 0x40400267, 0x38, 0x35, 0x30, 0x33,
0x35, 0x32, 0x36, 0x31, 0x39, 0x33, 0x31,
0x31, 0x40400212, 0x31, 0x30, 0x31, 0x30, 0x30,
0x30, 0x33, 0x31, 0x33, 0x37, 0x38, 0x33,
0x38, 0x37, 0x35, 0x32, 0x38, 0x38, 0x36,
0x35, 0x38, 0x37, 0x35, 0x33, 0x33, 0x32,
0x30, 0x38, 0x33, 0x38, 0x31, 0x34, 0x32,
0x30, 0x36, 0x40400140, 0x4040012b, 0x31, 0x34, 0x37,
0x33, 0x30, 0x33, 0x35, 0x39, 0x4080032e, 0x39,
0x30, 0x34, 0x32, 0x38, 0x37, 0x35, 0x35,
0x34, 0x36, 0x38, 0x37, 0x33, 0x31, 0x31,
0x35, 0x39, 0x35, 0x40400355, 0x33, 0x38, 0x38,
0x32, 0x33, 0x35, 0x33, 0x37, 0x38, 0x37,
0x35, 0x4080037f, 0x39, 0x4040013a, 0x31, 0x40400148, 0x38,
0x30, 0x35, 0x33, 0x4040018a, 0x32, 0x32, 0x36,
0x38, 0x30, 0x36, 0x36, 0x31, 0x33, 0x30,
0x30, 0x31, 0x39, 0x32, 0x37, 0x38, 0x37,
0x36, 0x36, 0x31, 0x31, 0x31, 0x39, 0x35,
0x39, 0x40400237, 0x36, 0x40800124, 0x38, 0x39, 0x33,
0x38, 0x30, 0x39, 0x35, 0x32, 0x35, 0x37,
0x32, 0x30, 0x31, 0x30, 0x36, 0x35, 0x34,
0x38, 0x35, 0x38, 0x36, 0x33, 0x32, 0x37,
0x4040009a, 0x39, 0x33, 0x36, 0x31, 0x35, 0x33,
0x40400220, 0x4080015c, 0x32, 0x33, 0x30, 0x33, 0x30,
0x31, 0x39, 0x35, 0x32, 0x30, 0x33, 0x35,
0x33, 0x30, 0x31, 0x38, 0x35, 0x32, 0x40400171,
0x40400075, 0x33, 0x36, 0x32, 0x32, 0x35, 0x39,
0x39, 0x34, 0x31, 0x33, 0x40400254, 0x34, 0x39,
0x37, 0x32, 0x31, 0x37, 0x404000de, 0x33, 0x34,
0x37, 0x39, 0x31, 0x33, 0x31, 0x35, 0x31,
0x35, 0x35, 0x37, 0x34, 0x38, 0x35, 0x37,
0x32, 0x34, 0x32, 0x34, 0x35, 0x34, 0x31,
0x35, 0x30, 0x36, 0x39, 0x4040013f, 0x38, 0x32,
0x39, 0x35, 0x33, 0x33, 0x31, 0x31, 0x36,
0x38, 0x36, 0x31, 0x37, 0x32, 0x37, 0x38,
0x40400337, 0x39, 0x30, 0x37, 0x35, 0x30, 0x39,
0x4040010d, 0x37, 0x35, 0x34, 0x36, 0x33, 0x37,
0x34, 0x36, 0x34, 0x39, 0x33, 0x39, 0x33,
0x31, 0x39, 0x32, 0x35, 0x35, 0x30, 0x36,
0x30, 0x34, 0x30, 0x30, 0x39, 0x4040026b, 0x31,
0x36, 0x37, 0x31, 0x31, 0x33, 0x39, 0x30,
0x30, 0x39, 0x38, 0x40400335, 0x34, 0x30, 0x31,
0x32, 0x38, 0x35, 0x38, 0x33, 0x36, 0x31,
0x36, 0x30, 0x33, 0x35, 0x36, 0x33, 0x37,
0x30, 0x37, 0x36, 0x36, 0x30, 0x31, 0x30,
0x34, 0x40400172, 0x38, 0x31, 0x39, 0x34, 0x32,
0x39, 0x4080041e, 0x404000ef, 0x4040028b, 0x37, 0x38, 0x33,
0x37, 0x34, 0x404004a8, 0x38, 0x32, 0x35, 0x35,
0x33, 0x37, 0x40800209, 0x32, 0x36, 0x38, 0x4040002e,
0x34, 0x30, 0x34, 0x37, 0x404001d1, 0x34, 0x404004b5,
0x4040038d, 0x38, 0x34, 0x404003a8, 0x36, 0x40c0031f, 0x33,
0x33, 0x31, 0x33, 0x36, 0x37, 0x37, 0x30,
0x32, 0x38, 0x39, 0x38, 0x39, 0x31, 0x35,
0x32, 0x40400062, 0x35, 0x32, 0x31, 0x36, 0x32,
0x30, 0x35, 0x36, 0x39, 0x36, 0x40400411, 0x30,
0x35, 0x38, 0x40400477, 0x35, 0x40400498, 0x35, 0x31,
0x31, 0x40400209, 0x38, 0x32, 0x34, 0x33, 0x30,
0x30, 0x33, 0x35, 0x35, 0x38, 0x37, 0x36,
0x34, 0x30, 0x32, 0x34, 0x37, 0x34, 0x39,
0x36, 0x34, 0x37, 0x33, 0x32, 0x36, 0x33,
0x4040043e, 0x39, 0x39, 0x32, 0x4040044b, 0x34, 0x32,
0x36, 0x39, 0x40c002c5, 0x37, 0x404001d6, 0x34, 0x4040053d,
0x4040041d, 0x39, 0x33, 0x34, 0x31, 0x37, 0x404001ad,
0x31, 0x32, 0x4040002a, 0x34, 0x4040019e, 0x31, 0x35,
0x30, 0x33, 0x30, 0x32, 0x38, 0x36, 0x31,
0x38, 0x32, 0x39, 0x37, 0x34, 0x35, 0x35,
0x35, 0x37, 0x30, 0x36, 0x37, 0x34, 0x40400135,
0x35, 0x30, 0x35, 0x34, 0x39, 0x34, 0x35,
0x38, 0x404001c5, 0x39, 0x40400051, 0x35, 0x36, 0x404001ec,
0x37, 0x32, 0x31, 0x30, 0x37, 0x39, 0x40400159,
0x33, 0x30, 0x4040010a, 0x33, 0x32, 0x31, 0x31,
0x36, 0x35, 0x33, 0x34, 0x34, 0x39, 0x38,
0x37, 0x32, 0x30, 0x32, 0x37, 0x4040011b, 0x30,
0x32, 0x33, 0x36, 0x34, 0x4040022e, 0x35, 0x34,
0x39, 0x39, 0x31, 0x31, 0x39, 0x38, 0x40400418,
0x34, 0x4040011b, 0x35, 0x33, 0x35, 0x36, 0x36,
0x33, 0x36, 0x39, 0x40400450, 0x32, 0x36, 0x35,
0x404002e4, 0x37, 0x38, 0x36, 0x32, 0x35, 0x35,
0x31, 0x404003da, 0x31, 0x37, 0x35, 0x37, 0x34,
0x36, 0x37, 0x32, 0x38, 0x39, 0x30, 0x39,
0x37, 0x37, 0x37, 0x37, 0x40800453, 0x30, 0x30,
0x30, 0x404005fd, 0x37, 0x30, 0x404004df, 0x36, 0x404003e9,
0x34, 0x39, 0x31, 0x4040041e, 0x40400297, 0x32, 0x31,
0x34, 0x37, 0x37, 0x32, 0x33, 0x35, 0x30,
0x31, 0x34, 0x31, 0x34, 0x40400643, 0x33, 0x35,
0x36, 0x404004af, 0x31, 0x36, 0x31, 0x33, 0x36,
0x31, 0x31, 0x35, 0x37, 0x33, 0x35, 0x32,
0x35, 0x40400504, 0x33, 0x34, 0x4040005b, 0x31, 0x38,
0x4040047b, 0x38, 0x34, 0x404005e7, 0x33, 0x33, 0x32,
0x33, 0x39, 0x30, 0x37, 0x33, 0x39, 0x34,
0x31, 0x34, 0x33, 0x33, 0x33, 0x34, 0x35,
0x34, 0x37, 0x37, 0x36, 0x32, 0x34, 0x40400242,
0x32, 0x35, 0x31, 0x38, 0x39, 0x38, 0x33,
0x35, 0x36, 0x39, 0x34, 0x38, 0x35, 0x35,
0x36, 0x32, 0x30, 0x39, 0x39, 0x32, 0x31,
0x39, 0x32, 0x32, 0x32, 0x31, 0x38, 0x34,
0x32, 0x37, 0x4040023e, 0x32, 0x404000ba, 0x36, 0x38,
0x38, 0x37, 0x36, 0x37, 0x31, 0x37, 0x39,
0x30, 0x40400055, 0x30, 0x40800106, 0x36, 0x36, 0x404003e7,
0x38, 0x38, 0x36, 0x32, 0x37, 0x32, 0x404006dc,
0x31, 0x37, 0x38, 0x36, 0x30, 0x38, 0x35,
0x37, 0x40400073, 0x33, 0x408002fc, 0x37, 0x39, 0x37,
0x36, 0x36, 0x38, 0x31, 0x404002bd, 0x30, 0x30,
0x39, 0x35, 0x33, 0x38, 0x38, 0x40400638, 0x33,
0x404006a5, 0x30, 0x36, 0x38, 0x30, 0x30, 0x36,
0x34, 0x32, 0x32, 0x35, 0x31, 0x32, 0x35,
0x32, 0x4040057b, 0x37, 0x33, 0x39, 0x32, 0x40400297,
0x40400474, 0x34, 0x408006b3, 0x38, 0x36, 0x32, 0x36,
0x39, 0x34, 0x35, 0x404001e5, 0x34, 0x31, 0x39,
0x36, 0x35, 0x32, 0x38, 0x35, 0x30, 0x40400099,
0x4040039c, 0x31, 0x38, 0x36, 0x33, 0x404001be, 0x34,
0x40800154, 0x32, 0x30, 0x33, 0x39, 0x4040058b, 0x34,
0x35, 0x404002bc, 0x32, 0x33, 0x37, 0x4040042c, 0x36,
0x40400510, 0x35, 0x36, 0x40400638, 0x37, 0x31, 0x39,
0x31, 0x37, 0x32, 0x38, 0x40400171, 0x37, 0x36,
0x34, 0x36, 0x35, 0x37, 0x35, 0x37, 0x33,
0x39, 0x40400101, 0x33, 0x38, 0x39, 0x40400748, 0x38,
0x33, 0x32, 0x36, 0x34, 0x35, 0x39, 0x39,
0x35, 0x38, 0x404006a7, 0x30, 0x34, 0x37, 0x38,
0x404001de, 0x40400328, 0x39, 0x4040002d, 0x36, 0x34, 0x30,
0x37, 0x38, 0x39, 0x35, 0x31, 0x4040008e, 0x36,
0x38, 0x33, 0x4040012f, 0x32, 0x35, 0x39, 0x35,
0x37, 0x30, 0x40400468, 0x38, 0x32, 0x32, 0x404002c8,
0x32, 0x4040061b, 0x34, 0x30, 0x37, 0x37, 0x32,
0x36, 0x37, 0x31, 0x39, 0x34, 0x37, 0x38,
0x40400319, 0x38, 0x32, 0x36, 0x30, 0x31, 0x34,
0x37, 0x36, 0x39, 0x39, 0x30, 0x39, 0x404004e8,
0x30, 0x31, 0x33, 0x36, 0x33, 0x39, 0x34,
0x34, 0x33, 0x4040027f, 0x33, 0x30, 0x40400105, 0x32,
0x30, 0x33, 0x34, 0x39, 0x36, 0x32, 0x35,
0x32, 0x34, 0x35, 0x31, 0x37, 0x404003b5, 0x39,
0x36, 0x35, 0x31, 0x34, 0x33, 0x31, 0x34,
0x32, 0x39, 0x38, 0x30, 0x39, 0x31, 0x39,
0x30, 0x36, 0x35, 0x39, 0x32, 0x40400282, 0x37,
0x32, 0x32, 0x31, 0x36, 0x39, 0x36, 0x34,
0x36, 0x40400419, 0x4040007a, 0x35, 0x4040050e, 0x34, 0x40800565,
0x38, 0x40400559, 0x39, 0x37, 0x4040057b, 0x35, 0x34,
0x4040049d, 0x4040023e, 0x37, 0x4040065a, 0x38, 0x34, 0x36,
0x38, 0x31, 0x33, 0x4040008c, 0x36, 0x38, 0x33,
0x38, 0x36, 0x38, 0x39, 0x34, 0x32, 0x37,
0x37, 0x34, 0x31, 0x35, 0x35, 0x39, 0x39,
0x31, 0x38, 0x35, 0x4040005a, 0x32, 0x34, 0x35,
0x39, 0x35, 0x33, 0x39, 0x35, 0x39, 0x34,
0x33, 0x31, 0x404005b7, 0x37, 0x40400012, 0x36, 0x38,
0x30, 0x38, 0x34, 0x35, 0x404002e7, 0x37, 0x33,
0x4040081e, 0x39, 0x35, 0x38, 0x34, 0x38, 0x36,
0x35, 0x33, 0x38, 0x404006e8, 0x36, 0x32, 0x404000f2,
0x36, 0x30, 0x39, 0x404004b6, 0x36, 0x30, 0x38,
0x30, 0x35, 0x31, 0x32, 0x34, 0x33, 0x38,
0x38, 0x34, 0x4040013a, 0x4040000b, 0x34, 0x31, 0x33,
0x4040030f, 0x37, 0x36, 0x32, 0x37, 0x38, 0x40400341,
0x37, 0x31, 0x35, 0x4040059b, 0x33, 0x35, 0x39,
0x39, 0x37, 0x37, 0x30, 0x30, 0x31, 0x32,
0x39, 0x40400472, 0x38, 0x39, 0x34, 0x34, 0x31,
0x40400277, 0x36, 0x38, 0x35, 0x35, 0x4040005f, 0x34,
0x30, 0x36, 0x33, 0x404008e6, 0x32, 0x30, 0x37,
0x32, 0x32, 0x40400158, 0x40800203, 0x34, 0x38, 0x31,
0x35, 0x38, 0x40400205, 0x404001fe, 0x4040027a, 0x40400298, 0x33,
0x39, 0x34, 0x35, 0x32, 0x32, 0x36, 0x37,
0x40c00496, 0x38, 0x4040058a, 0x32, 0x31, 0x404002ea, 0x32,
0x40400387, 0x35, 0x34, 0x36, 0x36, 0x36, 0x4040051b,
0x32, 0x33, 0x39, 0x38, 0x36, 0x34, 0x35,
0x36, 0x404004c4, 0x31, 0x36, 0x33, 0x35, 0x40800253,
0x40400811, 0x37, 0x404008ad, 0x39, 0x38, 0x4040045e, 0x39,
0x33, 0x36, 0x33, 0x34, 0x4040075b, 0x37, 0x34,
0x33, 0x32, 0x34, 0x4040047b, 0x31, 0x35, 0x30,
0x37, 0x36, 0x404004bb, 0x37, 0x39, 0x34, 0x35,
0x31, 0x30, 0x39, 0x4040003e, 0x30, 0x39, 0x34,
0x30, 0x404006a6, 0x38, 0x38, 0x37, 0x39, 0x37,
0x31, 0x30, 0x38, 0x39, 0x33, 0x404008f0, 0x36,
0x39, 0x31, 0x33, 0x36, 0x38, 0x36, 0x37,
0x32, 0x4040025b, 0x404001fe, 0x35, 0x4040053f, 0x40400468, 0x40400801,
0x31, 0x37, 0x39, 0x32, 0x38, 0x36, 0x38,
0x404008cc, 0x38, 0x37, 0x34, 0x37, 0x4080079e, 0x38,
0x32, 0x34, 0x4040097a, 0x38, 0x4040025b, 0x37, 0x31,
0x34, 0x39, 0x30, 0x39, 0x36, 0x37, 0x35,
0x39, 0x38, 0x404006ef, 0x33, 0x36, 0x35, 0x40400134,
0x38, 0x31, 0x4040005c, 0x40400745, 0x40400936, 0x36, 0x38,
0x32, 0x39, 0x4040057e, 0x38, 0x37, 0x32, 0x32,
0x36, 0x35, 0x38, 0x38, 0x30, 0x40400611, 0x35,
0x40400249, 0x34, 0x32, 0x37, 0x30, 0x34, 0x37,
0x37, 0x35, 0x35, 0x4040081e, 0x33, 0x37, 0x39,
0x36, 0x34, 0x31, 0x34, 0x35, 0x31, 0x35,
0x32, 0x404005fd, 0x32, 0x33, 0x34, 0x33, 0x36,
0x34, 0x35, 0x34, 0x404005de, 0x34, 0x34, 0x34,
0x37, 0x39, 0x35, 0x4040003c, 0x40400523, 0x408008e6, 0x34,
0x31, 0x4040052a, 0x33, 0x40400304, 0x35, 0x32, 0x33,
0x31, 0x40800841, 0x31, 0x36, 0x36, 0x31, 0x404008b2,
0x35, 0x39, 0x36, 0x39, 0x35, 0x33, 0x36,
0x32, 0x33, 0x31, 0x34, 0x404005ff, 0x32, 0x34,
0x38, 0x34, 0x39, 0x33, 0x37, 0x31, 0x38,
0x37, 0x31, 0x31, 0x30, 0x31, 0x34, 0x35,
0x37, 0x36, 0x35, 0x34, 0x40400761, 0x30, 0x32,
0x37, 0x39, 0x39, 0x33, 0x34, 0x34, 0x30,
0x33, 0x37, 0x34, 0x32, 0x30, 0x30, 0x37,
0x4040093f, 0x37, 0x38, 0x35, 0x33, 0x39, 0x30,
0x36, 0x32, 0x31, 0x39, 0x40800299, 0x40400345, 0x38,
0x34, 0x37, 0x408003d2, 0x38, 0x33, 0x33, 0x32,
0x31, 0x34, 0x34, 0x35, 0x37, 0x31, 0x40400284,
0x40400776, 0x34, 0x33, 0x35, 0x30, 0x40400928, 0x40400468,
0x35, 0x33, 0x31, 0x39, 0x31, 0x30, 0x34,
0x38, 0x34, 0x38, 0x31, 0x30, 0x30, 0x35,
0x33, 0x37, 0x30, 0x36, 0x404008bc, 0x4080059d, 0x40800781,
0x31, 0x40400559, 0x37, 0x4040031b, 0x35, 0x404007ec, 0x4040040c,
0x36, 0x33, 0x408007dc, 0x34, 0x40400971, 0x4080034e, 0x408003f5,
0x38, 0x4080052d, 0x40800887, 0x39, 0x40400187, 0x39, 0x31,
0x404008ce, 0x38, 0x31, 0x34, 0x36, 0x37, 0x35,
0x31, 0x4040062b, 0x31, 0x32, 0x33, 0x39, 0x40c001a9,
0x39, 0x30, 0x37, 0x31, 0x38, 0x36, 0x34,
0x39, 0x34, 0x32, 0x33, 0x31, 0x39, 0x36,
0x31, 0x35, 0x36, 0x404001ec, 0x404006bc, 0x39, 0x35,
0x40400926, 0x40400469, 0x4040011b, 0x36, 0x30, 0x33, 0x38,
0x40400a25, 0x4040016f, 0x40400384, 0x36, 0x32, 0x4040045a, 0x35,
0x4040084c, 0x36, 0x33, 0x38, 0x39, 0x33, 0x37,
0x37, 0x38, 0x37, 0x404008c5, 0x404000f8, 0x39, 0x37,
0x39, 0x32, 0x30, 0x37, 0x37, 0x33, 0x404005d7,
0x32, 0x31, 0x38, 0x32, 0x35, 0x36, 0x404007df,
0x36, 0x36, 0x404006d6, 0x34, 0x32, 0x4080067e, 0x36,
0x404006e6, 0x34, 0x34, 0x40400024, 0x35, 0x34, 0x39,
0x32, 0x30, 0x32, 0x36, 0x30, 0x35, 0x40400ab3,
0x408003e4, 0x32, 0x30, 0x31, 0x34, 0x39, 0x404004d2,
0x38, 0x35, 0x30, 0x37, 0x33, 0x40400599, 0x36,
0x36, 0x36, 0x30, 0x40400194, 0x32, 0x34, 0x33,
0x34, 0x30, 0x40400087, 0x30, 0x4040076b, 0x38, 0x36,
0x33, 0x40400956, 0x404007e4, 0x4040042b, 0x40400174, 0x35, 0x37,
0x39, 0x36, 0x32, 0x36, 0x38, 0x35, 0x36,
0x40400140, 0x35, 0x30, 0x38, 0x40400523, 0x35, 0x38,
0x37, 0x39, 0x36, 0x39, 0x39, 0x40400711, 0x35,
0x37, 0x34, 0x40400a18, 0x38, 0x34, 0x30, 0x404008b3,
0x31, 0x34, 0x35, 0x39, 0x31, 0x4040078c, 0x37,
0x30, 0x40400234, 0x30, 0x31, 0x40400be7, 0x31, 0x32,
0x40400c74, 0x30, 0x404003c3, 0x33, 0x39, 0x40400b2a, 0x40400112,
0x37, 0x31, 0x35, 0x404003b0, 0x34, 0x32, 0x30,
0x40800bf2, 0x39, 0x40400bc2, 0x30, 0x37, 0x40400341, 0x40400795,
0x40400aaf, 0x40400c62, 0x32, 0x31, 0x40400960, 0x32, 0x35,
0x31, 0x4040057b, 0x40400944, 0x39, 0x32, 0x404001b2, 0x38,
0x32, 0x36, 0x40400b66, 0x32, 0x40400278, 0x33, 0x32,
0x31, 0x35, 0x37, 0x39, 0x31, 0x39, 0x38,
0x34, 0x31, 0x34, 0x4080087b, 0x39, 0x31, 0x36,
0x34, 0x408006e8, 0x39, 0x40800b58, 0x404008db, 0x37, 0x32,
0x32, 0x40400321, 0x35, 0x404008a4, 0x40400141, 0x39, 0x31,
0x30, 0x404000bc, 0x40400c5b, 0x35, 0x32, 0x38, 0x30,
0x31, 0x37, 0x40400231, 0x37, 0x31, 0x32, 0x40400914,
0x38, 0x33, 0x32, 0x40400373, 0x31, 0x40400589, 0x30,
0x39, 0x33, 0x35, 0x33, 0x39, 0x36, 0x35,
0x37, 0x4040064b, 0x31, 0x30, 0x38, 0x33, 0x40400069,
0x35, 0x31, 0x4040077a, 0x40400d5a, 0x31, 0x34, 0x34,
0x34, 0x32, 0x31, 0x30, 0x30, 0x40400202, 0x30,
0x33, 0x4040019c, 0x31, 0x31, 0x30, 0x33, 0x40400c81,
0x40400009, 0x40400026, 0x40c00602, 0x35, 0x31, 0x36, 0x404005d9,
0x40800883, 0x4040092a, 0x35, 0x40800c42, 0x38, 0x35, 0x31,
0x37, 0x31, 0x34, 0x33, 0x37, 0x40400605, 0x4040006d,
0x31, 0x35, 0x35, 0x36, 0x35, 0x30, 0x38,
0x38, 0x404003b9, 0x39, 0x38, 0x39, 0x38, 0x35,
0x39, 0x39, 0x38, 0x32, 0x33, 0x38, 0x404001cf,
0x404009ba, 0x33, 0x4040016c, 0x4040043e, 0x404009c3, 0x38, 0x40800e05,
0x33, 0x32, 0x40400107, 0x35, 0x40400305, 0x33, 0x404001ca,
0x39, 0x4040041b, 0x39, 0x38, 0x4040087d, 0x34, 0x40400cb8,
0x37, 0x4040064b, 0x30, 0x37, 0x404000e5, 0x34, 0x38,
0x31, 0x34, 0x31, 0x40400539, 0x38, 0x35, 0x39,
0x34, 0x36, 0x31, 0x40400bc9, 0x38, 0x30,
},
},
HuffTest{
.input = "huffman-rand-1k.input",
.want = "huffman-rand-1k.{s}.expect",
.want_no_input = "huffman-rand-1k.{s}.expect-noinput",
.tokens = &[_]token.Token{
0xf8, 0x8b, 0x96, 0x76, 0x48, 0xd, 0x85, 0x94, 0x25, 0x80, 0xaf, 0xc2, 0xfe, 0x8d,
0xe8, 0x20, 0xeb, 0x17, 0x86, 0xc9, 0xb7, 0xc5, 0xde, 0x6, 0xea, 0x7d, 0x18, 0x8b,
0xe7, 0x3e, 0x7, 0xda, 0xdf, 0xff, 0x6c, 0x73, 0xde, 0xcc, 0xe7, 0x6d, 0x8d, 0x4,
0x19, 0x49, 0x7f, 0x47, 0x1f, 0x48, 0x15, 0xb0, 0xe8, 0x9e, 0xf2, 0x31, 0x59, 0xde,
0x34, 0xb4, 0x5b, 0xe5, 0xe0, 0x9, 0x11, 0x30, 0xc2, 0x88, 0x5b, 0x7c, 0x5d, 0x14,
0x13, 0x6f, 0x23, 0xa9, 0xd, 0xbc, 0x2d, 0x23, 0xbe, 0xd9, 0xed, 0x75, 0x4, 0x6c,
0x99, 0xdf, 0xfd, 0x70, 0x66, 0xe6, 0xee, 0xd9, 0xb1, 0x9e, 0x6e, 0x83, 0x59, 0xd5,
0xd4, 0x80, 0x59, 0x98, 0x77, 0x89, 0x43, 0x38, 0xc9, 0xaf, 0x30, 0x32, 0x9a, 0x20,
0x1b, 0x46, 0x3d, 0x67, 0x6e, 0xd7, 0x72, 0x9e, 0x4e, 0x21, 0x4f, 0xc6, 0xe0, 0xd4,
0x7b, 0x4, 0x8d, 0xa5, 0x3, 0xf6, 0x5, 0x9b, 0x6b, 0xdc, 0x2a, 0x93, 0x77, 0x28,
0xfd, 0xb4, 0x62, 0xda, 0x20, 0xe7, 0x1f, 0xab, 0x6b, 0x51, 0x43, 0x39, 0x2f, 0xa0,
0x92, 0x1, 0x6c, 0x75, 0x3e, 0xf4, 0x35, 0xfd, 0x43, 0x2e, 0xf7, 0xa4, 0x75, 0xda,
0xea, 0x9b, 0xa, 0x64, 0xb, 0xe0, 0x23, 0x29, 0xbd, 0xf7, 0xe7, 0x83, 0x3c, 0xfb,
0xdf, 0xb3, 0xae, 0x4f, 0xa4, 0x47, 0x55, 0x99, 0xde, 0x2f, 0x96, 0x6e, 0x1c, 0x43,
0x4c, 0x87, 0xe2, 0x7c, 0xd9, 0x5f, 0x4c, 0x7c, 0xe8, 0x90, 0x3, 0xdb, 0x30, 0x95,
0xd6, 0x22, 0xc, 0x47, 0xb8, 0x4d, 0x6b, 0xbd, 0x24, 0x11, 0xab, 0x2c, 0xd7, 0xbe,
0x6e, 0x7a, 0xd6, 0x8, 0xa3, 0x98, 0xd8, 0xdd, 0x15, 0x6a, 0xfa, 0x93, 0x30, 0x1,
0x25, 0x1d, 0xa2, 0x74, 0x86, 0x4b, 0x6a, 0x95, 0xe8, 0xe1, 0x4e, 0xe, 0x76, 0xb9,
0x49, 0xa9, 0x5f, 0xa0, 0xa6, 0x63, 0x3c, 0x7e, 0x7e, 0x20, 0x13, 0x4f, 0xbb, 0x66,
0x92, 0xb8, 0x2e, 0xa4, 0xfa, 0x48, 0xcb, 0xae, 0xb9, 0x3c, 0xaf, 0xd3, 0x1f, 0xe1,
0xd5, 0x8d, 0x42, 0x6d, 0xf0, 0xfc, 0x8c, 0xc, 0x0, 0xde, 0x40, 0xab, 0x8b, 0x47,
0x97, 0x4e, 0xa8, 0xcf, 0x8e, 0xdb, 0xa6, 0x8b, 0x20, 0x9, 0x84, 0x7a, 0x66, 0xe5,
0x98, 0x29, 0x2, 0x95, 0xe6, 0x38, 0x32, 0x60, 0x3, 0xe3, 0x9a, 0x1e, 0x54, 0xe8,
0x63, 0x80, 0x48, 0x9c, 0xe7, 0x63, 0x33, 0x6e, 0xa0, 0x65, 0x83, 0xfa, 0xc6, 0xba,
0x7a, 0x43, 0x71, 0x5, 0xf5, 0x68, 0x69, 0x85, 0x9c, 0xba, 0x45, 0xcd, 0x6b, 0xb,
0x19, 0xd1, 0xbb, 0x7f, 0x70, 0x85, 0x92, 0xd1, 0xb4, 0x64, 0x82, 0xb1, 0xe4, 0x62,
0xc5, 0x3c, 0x46, 0x1f, 0x92, 0x31, 0x1c, 0x4e, 0x41, 0x77, 0xf7, 0xe7, 0x87, 0xa2,
0xf, 0x6e, 0xe8, 0x92, 0x3, 0x6b, 0xa, 0xe7, 0xa9, 0x3b, 0x11, 0xda, 0x66, 0x8a,
0x29, 0xda, 0x79, 0xe1, 0x64, 0x8d, 0xe3, 0x54, 0xd4, 0xf5, 0xef, 0x64, 0x87, 0x3b,
0xf4, 0xc2, 0xf4, 0x71, 0x13, 0xa9, 0xe9, 0xe0, 0xa2, 0x6, 0x14, 0xab, 0x5d, 0xa7,
0x96, 0x0, 0xd6, 0xc3, 0xcc, 0x57, 0xed, 0x39, 0x6a, 0x25, 0xcd, 0x76, 0xea, 0xba,
0x3a, 0xf2, 0xa1, 0x95, 0x5d, 0xe5, 0x71, 0xcf, 0x9c, 0x62, 0x9e, 0x6a, 0xfa, 0xd5,
0x31, 0xd1, 0xa8, 0x66, 0x30, 0x33, 0xaa, 0x51, 0x17, 0x13, 0x82, 0x99, 0xc8, 0x14,
0x60, 0x9f, 0x4d, 0x32, 0x6d, 0xda, 0x19, 0x26, 0x21, 0xdc, 0x7e, 0x2e, 0x25, 0x67,
0x72, 0xca, 0xf, 0x92, 0xcd, 0xf6, 0xd6, 0xcb, 0x97, 0x8a, 0x33, 0x58, 0x73, 0x70,
0x91, 0x1d, 0xbf, 0x28, 0x23, 0xa3, 0xc, 0xf1, 0x83, 0xc3, 0xc8, 0x56, 0x77, 0x68,
0xe3, 0x82, 0xba, 0xb9, 0x57, 0x56, 0x57, 0x9c, 0xc3, 0xd6, 0x14, 0x5, 0x3c, 0xb1,
0xaf, 0x93, 0xc8, 0x8a, 0x57, 0x7f, 0x53, 0xfa, 0x2f, 0xaa, 0x6e, 0x66, 0x83, 0xfa,
0x33, 0xd1, 0x21, 0xab, 0x1b, 0x71, 0xb4, 0x7c, 0xda, 0xfd, 0xfb, 0x7f, 0x20, 0xab,
0x5e, 0xd5, 0xca, 0xfd, 0xdd, 0xe0, 0xee, 0xda, 0xba, 0xa8, 0x27, 0x99, 0x97, 0x69,
0xc1, 0x3c, 0x82, 0x8c, 0xa, 0x5c, 0x2d, 0x5b, 0x88, 0x3e, 0x34, 0x35, 0x86, 0x37,
0x46, 0x79, 0xe1, 0xaa, 0x19, 0xfb, 0xaa, 0xde, 0x15, 0x9, 0xd, 0x1a, 0x57, 0xff,
0xb5, 0xf, 0xf3, 0x2b, 0x5a, 0x6a, 0x4d, 0x19, 0x77, 0x71, 0x45, 0xdf, 0x4f, 0xb3,
0xec, 0xf1, 0xeb, 0x18, 0x53, 0x3e, 0x3b, 0x47, 0x8, 0x9a, 0x73, 0xa0, 0x5c, 0x8c,
0x5f, 0xeb, 0xf, 0x3a, 0xc2, 0x43, 0x67, 0xb4, 0x66, 0x67, 0x80, 0x58, 0xe, 0xc1,
0xec, 0x40, 0xd4, 0x22, 0x94, 0xca, 0xf9, 0xe8, 0x92, 0xe4, 0x69, 0x38, 0xbe, 0x67,
0x64, 0xca, 0x50, 0xc7, 0x6, 0x67, 0x42, 0x6e, 0xa3, 0xf0, 0xb7, 0x6c, 0xf2, 0xe8,
0x5f, 0xb1, 0xaf, 0xe7, 0xdb, 0xbb, 0x77, 0xb5, 0xf8, 0xcb, 0x8, 0xc4, 0x75, 0x7e,
0xc0, 0xf9, 0x1c, 0x7f, 0x3c, 0x89, 0x2f, 0xd2, 0x58, 0x3a, 0xe2, 0xf8, 0x91, 0xb6,
0x7b, 0x24, 0x27, 0xe9, 0xae, 0x84, 0x8b, 0xde, 0x74, 0xac, 0xfd, 0xd9, 0xb7, 0x69,
0x2a, 0xec, 0x32, 0x6f, 0xf0, 0x92, 0x84, 0xf1, 0x40, 0xc, 0x8a, 0xbc, 0x39, 0x6e,
0x2e, 0x73, 0xd4, 0x6e, 0x8a, 0x74, 0x2a, 0xdc, 0x60, 0x1f, 0xa3, 0x7, 0xde, 0x75,
0x8b, 0x74, 0xc8, 0xfe, 0x63, 0x75, 0xf6, 0x3d, 0x63, 0xac, 0x33, 0x89, 0xc3, 0xf0,
0xf8, 0x2d, 0x6b, 0xb4, 0x9e, 0x74, 0x8b, 0x5c, 0x33, 0xb4, 0xca, 0xa8, 0xe4, 0x99,
0xb6, 0x90, 0xa1, 0xef, 0xf, 0xd3, 0x61, 0xb2, 0xc6, 0x1a, 0x94, 0x7c, 0x44, 0x55,
0xf4, 0x45, 0xff, 0x9e, 0xa5, 0x5a, 0xc6, 0xa0, 0xe8, 0x2a, 0xc1, 0x8d, 0x6f, 0x34,
0x11, 0xb9, 0xbe, 0x4e, 0xd9, 0x87, 0x97, 0x73, 0xcf, 0x3d, 0x23, 0xae, 0xd5, 0x1a,
0x5e, 0xae, 0x5d, 0x6a, 0x3, 0xf9, 0x22, 0xd, 0x10, 0xd9, 0x47, 0x69, 0x15, 0x3f,
0xee, 0x52, 0xa3, 0x8, 0xd2, 0x3c, 0x51, 0xf4, 0xf8, 0x9d, 0xe4, 0x98, 0x89, 0xc8,
0x67, 0x39, 0xd5, 0x5e, 0x35, 0x78, 0x27, 0xe8, 0x3c, 0x80, 0xae, 0x79, 0x71, 0xd2,
0x93, 0xf4, 0xaa, 0x51, 0x12, 0x1c, 0x4b, 0x1b, 0xe5, 0x6e, 0x15, 0x6f, 0xe4, 0xbb,
0x51, 0x9b, 0x45, 0x9f, 0xf9, 0xc4, 0x8c, 0x2a, 0xfb, 0x1a, 0xdf, 0x55, 0xd3, 0x48,
0x93, 0x27, 0x1, 0x26, 0xc2, 0x6b, 0x55, 0x6d, 0xa2, 0xfb, 0x84, 0x8b, 0xc9, 0x9e,
0x28, 0xc2, 0xef, 0x1a, 0x24, 0xec, 0x9b, 0xae, 0xbd, 0x60, 0xe9, 0x15, 0x35, 0xee,
0x42, 0xa4, 0x33, 0x5b, 0xfa, 0xf, 0xb6, 0xf7, 0x1, 0xa6, 0x2, 0x4c, 0xca, 0x90,
0x58, 0x3a, 0x96, 0x41, 0xe7, 0xcb, 0x9, 0x8c, 0xdb, 0x85, 0x4d, 0xa8, 0x89, 0xf3,
0xb5, 0x8e, 0xfd, 0x75, 0x5b, 0x4f, 0xed, 0xde, 0x3f, 0xeb, 0x38, 0xa3, 0xbe, 0xb0,
0x73, 0xfc, 0xb8, 0x54, 0xf7, 0x4c, 0x30, 0x67, 0x2e, 0x38, 0xa2, 0x54, 0x18, 0xba,
0x8, 0xbf, 0xf2, 0x39, 0xd5, 0xfe, 0xa5, 0x41, 0xc6, 0x66, 0x66, 0xba, 0x81, 0xef,
0x67, 0xe4, 0xe6, 0x3c, 0xc, 0xca, 0xa4, 0xa, 0x79, 0xb3, 0x57, 0x8b, 0x8a, 0x75,
0x98, 0x18, 0x42, 0x2f, 0x29, 0xa3, 0x82, 0xef, 0x9f, 0x86, 0x6, 0x23, 0xe1, 0x75,
0xfa, 0x8, 0xb1, 0xde, 0x17, 0x4a,
},
},
HuffTest{
.input = "huffman-rand-limit.input",
.want = "huffman-rand-limit.{s}.expect",
.want_no_input = "huffman-rand-limit.{s}.expect-noinput",
.tokens = &[_]token.Token{
0x61, 0x51c00000, 0xa, 0xf8, 0x8b, 0x96, 0x76, 0x48, 0xa, 0x85, 0x94, 0x25, 0x80,
0xaf, 0xc2, 0xfe, 0x8d, 0xe8, 0x20, 0xeb, 0x17, 0x86, 0xc9, 0xb7, 0xc5, 0xde,
0x6, 0xea, 0x7d, 0x18, 0x8b, 0xe7, 0x3e, 0x7, 0xda, 0xdf, 0xff, 0x6c, 0x73,
0xde, 0xcc, 0xe7, 0x6d, 0x8d, 0x4, 0x19, 0x49, 0x7f, 0x47, 0x1f, 0x48, 0x15,
0xb0, 0xe8, 0x9e, 0xf2, 0x31, 0x59, 0xde, 0x34, 0xb4, 0x5b, 0xe5, 0xe0, 0x9,
0x11, 0x30, 0xc2, 0x88, 0x5b, 0x7c, 0x5d, 0x14, 0x13, 0x6f, 0x23, 0xa9, 0xa,
0xbc, 0x2d, 0x23, 0xbe, 0xd9, 0xed, 0x75, 0x4, 0x6c, 0x99, 0xdf, 0xfd, 0x70,
0x66, 0xe6, 0xee, 0xd9, 0xb1, 0x9e, 0x6e, 0x83, 0x59, 0xd5, 0xd4, 0x80, 0x59,
0x98, 0x77, 0x89, 0x43, 0x38, 0xc9, 0xaf, 0x30, 0x32, 0x9a, 0x20, 0x1b, 0x46,
0x3d, 0x67, 0x6e, 0xd7, 0x72, 0x9e, 0x4e, 0x21, 0x4f, 0xc6, 0xe0, 0xd4, 0x7b,
0x4, 0x8d, 0xa5, 0x3, 0xf6, 0x5, 0x9b, 0x6b, 0xdc, 0x2a, 0x93, 0x77, 0x28,
0xfd, 0xb4, 0x62, 0xda, 0x20, 0xe7, 0x1f, 0xab, 0x6b, 0x51, 0x43, 0x39, 0x2f,
0xa0, 0x92, 0x1, 0x6c, 0x75, 0x3e, 0xf4, 0x35, 0xfd, 0x43, 0x2e, 0xf7, 0xa4,
0x75, 0xda, 0xea, 0x9b, 0xa,
},
},
HuffTest{
.input = "huffman-shifts.input",
.want = "huffman-shifts.{s}.expect",
.want_no_input = "huffman-shifts.{s}.expect-noinput",
.tokens = &[_]token.Token{
0x31, 0x30, 0x7fc00001, 0x7fc00001, 0x7fc00001, 0x7fc00001, 0x7fc00001,
0x7fc00001, 0x7fc00001, 0x7fc00001, 0x7fc00001, 0x7fc00001, 0x7fc00001, 0x7fc00001,
0x7fc00001, 0x7fc00001, 0x7fc00001, 0x52400001, 0xd, 0xa, 0x32,
0x33, 0x7fc00001, 0x7fc00001, 0x7fc00001, 0x7fc00001, 0x7fc00001, 0x7fc00001,
0x7fc00001, 0x7fc00001, 0x7fc00001, 0x7f400001,
},
},
HuffTest{
.input = "huffman-text-shift.input",
.want = "huffman-text-shift.{s}.expect",
.want_no_input = "huffman-text-shift.{s}.expect-noinput",
.tokens = &[_]token.Token{
0x2f, 0x2f, 0x43, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68,
0x74, 0x32, 0x30, 0x30, 0x39, 0x54, 0x68, 0x47, 0x6f, 0x41,
0x75, 0x74, 0x68, 0x6f, 0x72, 0x2e, 0x41, 0x6c, 0x6c, 0x40800016,
0x72, 0x72, 0x76, 0x64, 0x2e, 0xd, 0xa, 0x2f, 0x2f, 0x55,
0x6f, 0x66, 0x74, 0x68, 0x69, 0x6f, 0x75, 0x72, 0x63, 0x63,
0x6f, 0x64, 0x69, 0x67, 0x6f, 0x76, 0x72, 0x6e, 0x64, 0x62,
0x79, 0x42, 0x53, 0x44, 0x2d, 0x74, 0x79, 0x6c, 0x40400020, 0x6c,
0x69, 0x63, 0x6e, 0x74, 0x68, 0x74, 0x63, 0x6e, 0x62, 0x66,
0x6f, 0x75, 0x6e, 0x64, 0x69, 0x6e, 0x74, 0x68, 0x4c, 0x49,
0x43, 0x45, 0x4e, 0x53, 0x45, 0x66, 0x69, 0x6c, 0x2e, 0xd,
0xa, 0xd, 0xa, 0x70, 0x63, 0x6b, 0x67, 0x6d, 0x69, 0x6e,
0x4040000a, 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x22, 0x6f, 0x22,
0x4040000c, 0x66, 0x75, 0x6e, 0x63, 0x6d, 0x69, 0x6e, 0x28, 0x29,
0x7b, 0xd, 0xa, 0x9, 0x76, 0x72, 0x62, 0x3d, 0x6d, 0x6b,
0x28, 0x5b, 0x5d, 0x62, 0x79, 0x74, 0x2c, 0x36, 0x35, 0x35,
0x33, 0x35, 0x29, 0xd, 0xa, 0x9, 0x66, 0x2c, 0x5f, 0x3a,
0x3d, 0x6f, 0x2e, 0x43, 0x72, 0x74, 0x28, 0x22, 0x68, 0x75,
0x66, 0x66, 0x6d, 0x6e, 0x2d, 0x6e, 0x75, 0x6c, 0x6c, 0x2d,
0x6d, 0x78, 0x2e, 0x69, 0x6e, 0x22, 0x40800021, 0x2e, 0x57, 0x72,
0x69, 0x74, 0x28, 0x62, 0x29, 0xd, 0xa, 0x7d, 0xd, 0xa,
0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a,
0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54,
0x55, 0x56, 0x58, 0x78, 0x79, 0x7a, 0x21, 0x22, 0x23, 0xc2,
0xa4, 0x25, 0x26, 0x2f, 0x3f, 0x22,
},
},
HuffTest{
.input = "huffman-text.input",
.want = "huffman-text.{s}.expect",
.want_no_input = "huffman-text.{s}.expect-noinput",
.tokens = &[_]token.Token{
0x2f, 0x2f, 0x20, 0x7a, 0x69, 0x67, 0x20, 0x76,
0x30, 0x2e, 0x31, 0x30, 0x2e, 0x30, 0x0a, 0x2f,
0x2f, 0x20, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65,
0x20, 0x61, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x40400004,
0x6c, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
0x20, 0x30, 0x78, 0x30, 0x30, 0x0a, 0x63, 0x6f,
0x6e, 0x73, 0x74, 0x20, 0x73, 0x74, 0x64, 0x20,
0x3d, 0x20, 0x40, 0x69, 0x6d, 0x70, 0x6f, 0x72,
0x74, 0x28, 0x22, 0x73, 0x74, 0x64, 0x22, 0x29,
0x3b, 0x0a, 0x0a, 0x70, 0x75, 0x62, 0x20, 0x66,
0x6e, 0x20, 0x6d, 0x61, 0x69, 0x6e, 0x28, 0x29,
0x20, 0x21, 0x76, 0x6f, 0x69, 0x64, 0x20, 0x7b,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x76, 0x61, 0x72,
0x20, 0x62, 0x20, 0x3d, 0x20, 0x5b, 0x31, 0x5d,
0x75, 0x38, 0x7b, 0x30, 0x7d, 0x20, 0x2a, 0x2a,
0x20, 0x36, 0x35, 0x35, 0x33, 0x35, 0x3b, 0x4080001e,
0x40c00055, 0x66, 0x20, 0x3d, 0x20, 0x74, 0x72, 0x79,
0x4040005d, 0x2e, 0x66, 0x73, 0x2e, 0x63, 0x77, 0x64,
0x28, 0x29, 0x2e, 0x40c0008f, 0x46, 0x69, 0x6c, 0x65,
0x28, 0x4080002a, 0x40400000, 0x22, 0x68, 0x75, 0x66, 0x66,
0x6d, 0x61, 0x6e, 0x2d, 0x6e, 0x75, 0x6c, 0x6c,
0x2d, 0x6d, 0x61, 0x78, 0x2e, 0x69, 0x6e, 0x22,
0x2c, 0x4180001e, 0x2e, 0x7b, 0x20, 0x2e, 0x72, 0x65,
0x61, 0x64, 0x4080004e, 0x75, 0x65, 0x20, 0x7d, 0x40c0001a,
0x29, 0x40c0006b, 0x64, 0x65, 0x66, 0x65, 0x72, 0x20,
0x66, 0x2e, 0x63, 0x6c, 0x6f, 0x73, 0x65, 0x28,
0x404000b6, 0x40400015, 0x5f, 0x4100007b, 0x66, 0x2e, 0x77, 0x72,
0x69, 0x74, 0x65, 0x41, 0x6c, 0x6c, 0x28, 0x62,
0x5b, 0x30, 0x2e, 0x2e, 0x5d, 0x29, 0x3b, 0x0a,
0x7d, 0x0a,
},
},
HuffTest{
.input = "huffman-zero.input",
.want = "huffman-zero.{s}.expect",
.want_no_input = "huffman-zero.{s}.expect-noinput",
.tokens = &[_]token.Token{ 0x30, ml, 0x4b800000 },
},
HuffTest{
.input = "",
.want = "",
.want_no_input = "null-long-match.{s}.expect-noinput",
.tokens = &[_]token.Token{
0x0, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml, ml,
ml, ml, ml, 0x41400000,
},
},
};
const TestType = enum {
write_block,
write_dyn_block, // write dynamic block
write_huffman_block,
fn to_s(self: TestType) []const u8 {
return switch (self) {
.write_block => "wb",
.write_dyn_block => "dyn",
.write_huffman_block => "huff",
};
}
};
test "writeBlock" {
// tests if the writeBlock encoding has changed.
const ttype: TestType = .write_block;
try testBlock(writeBlockTests[0], ttype);
try testBlock(writeBlockTests[1], ttype);
try testBlock(writeBlockTests[2], ttype);
try testBlock(writeBlockTests[3], ttype);
try testBlock(writeBlockTests[4], ttype);
try testBlock(writeBlockTests[5], ttype);
try testBlock(writeBlockTests[6], ttype);
try testBlock(writeBlockTests[7], ttype);
try testBlock(writeBlockTests[8], ttype);
}
test "writeBlockDynamic" {
// tests if the writeBlockDynamic encoding has changed.
const ttype: TestType = .write_dyn_block;
try testBlock(writeBlockTests[0], ttype);
try testBlock(writeBlockTests[1], ttype);
try testBlock(writeBlockTests[2], ttype);
try testBlock(writeBlockTests[3], ttype);
try testBlock(writeBlockTests[4], ttype);
try testBlock(writeBlockTests[5], ttype);
try testBlock(writeBlockTests[6], ttype);
try testBlock(writeBlockTests[7], ttype);
try testBlock(writeBlockTests[8], ttype);
}
// testBlock tests a block against its references,
// or regenerate the references, if "-update" flag is set.
fn testBlock(comptime ht: HuffTest, ttype: TestType) !void {
// Skip wasi because it does not support std.fs.openDirAbsolute()
if (builtin.os.tag == .wasi) return error.SkipZigTest;
var want_name: []u8 = undefined;
var want_name_no_input: []u8 = undefined;
var input: []u8 = undefined;
var want: []u8 = undefined;
var want_ni: []u8 = undefined; // want no input: what we expect when input is empty
const current_dir = try std.fs.openDirAbsolute(std.fs.path.dirname(@src().file).?, .{});
const testdata_dir = try current_dir.openDir("testdata", .{});
var want_name_type = if (ht.want.len == 0) .{} else .{ttype.to_s()};
want_name = try fmt.allocPrint(testing.allocator, ht.want, want_name_type);
defer testing.allocator.free(want_name);
if (!mem.eql(u8, ht.input, "")) {
const in_file = try testdata_dir.openFile(ht.input, .{ .read = true });
input = try in_file.reader().readAllAlloc(testing.allocator, math.maxInt(usize));
defer testing.allocator.free(input);
const want_file = try testdata_dir.openFile(want_name, .{ .read = true });
want = try want_file.reader().readAllAlloc(testing.allocator, math.maxInt(usize));
defer testing.allocator.free(want);
var buf = ArrayList(u8).init(testing.allocator);
var bw = try huffmanBitWriter(testing.allocator, buf.writer());
try writeToType(ttype, &bw, ht.tokens, input);
var got = buf.items;
try expect(mem.eql(u8, got, want)); // expect writeBlock to yield expected result
// Test if the writer produces the same output after reset.
buf.deinit();
buf = ArrayList(u8).init(testing.allocator);
defer buf.deinit();
bw.reset(buf.writer());
defer bw.deinit();
try writeToType(ttype, &bw, ht.tokens, input);
try bw.flush();
got = buf.items;
try expect(mem.eql(u8, got, want)); // expect writeBlock to yield expected result
try testWriterEOF(.write_block, ht.tokens, input);
}
want_name_no_input = try fmt.allocPrint(testing.allocator, ht.want_no_input, .{ttype.to_s()});
defer testing.allocator.free(want_name_no_input);
const want_no_input_file = try testdata_dir.openFile(want_name_no_input, .{ .read = true });
want_ni = try want_no_input_file.reader().readAllAlloc(testing.allocator, math.maxInt(usize));
defer testing.allocator.free(want_ni);
var buf = ArrayList(u8).init(testing.allocator);
var bw = try huffmanBitWriter(testing.allocator, buf.writer());
try writeToType(ttype, &bw, ht.tokens, null);
var got = buf.items;
try expect(mem.eql(u8, got, want_ni)); // expect writeBlock to yield expected result
try expect(got[0] & 1 != 1); // expect no EOF
// Test if the writer produces the same output after reset.
buf.deinit();
buf = ArrayList(u8).init(testing.allocator);
defer buf.deinit();
bw.reset(buf.writer());
defer bw.deinit();
try writeToType(ttype, &bw, ht.tokens, null);
try bw.flush();
got = buf.items;
try expect(mem.eql(u8, got, want_ni)); // expect writeBlock to yield expected result
try testWriterEOF(.write_block, ht.tokens, &[0]u8{});
}
fn writeToType(ttype: TestType, bw: anytype, tok: []const token.Token, input: ?[]u8) !void {
switch (ttype) {
.write_block => try bw.writeBlock(tok, false, input),
.write_dyn_block => try bw.writeBlockDynamic(tok, false, input),
else => unreachable,
}
try bw.flush();
}
// Tests if the written block contains an EOF marker.
fn testWriterEOF(ttype: TestType, ht_tokens: []const token.Token, input: []u8) !void {
var buf = ArrayList(u8).init(testing.allocator);
defer buf.deinit();
var bw = try huffmanBitWriter(testing.allocator, buf.writer());
defer bw.deinit();
switch (ttype) {
.write_block => try bw.writeBlock(ht_tokens, true, input),
.write_dyn_block => try bw.writeBlockDynamic(ht_tokens, true, input),
.write_huffman_block => try bw.writeBlockHuff(true, input),
}
try bw.flush();
var b = buf.items;
try expect(b.len > 0);
try expect(b[0] & 1 == 1);
} | lib/std/compress/deflate/huffman_bit_writer.zig |
const std = @import("std");
const Type = @import("ElementType.zig").Enum;
const Element = @This();
// TODO: There are some common types of attribute that aren't necessarily strings (e.g. class),
// this should probably become a union of string, integer, and list of string.
const AttributeMap = std.StringHashMap([]const u8);
pub const Child = union(enum) {
text: []const u8,
element: Element,
};
const Children = std.TailQueue(Child);
// TODO: Should element_type be a union enum instead of plain member?
element_type: Type,
allocator: std.mem.Allocator,
attributes: AttributeMap,
parent: ?*Element,
children: Children = .{},
pub fn init(
parent: ?*Element,
element_type: Type,
allocator: std.mem.Allocator,
) Element {
return .{
.parent = parent,
.element_type = element_type,
.allocator = allocator,
.attributes = AttributeMap.init(allocator),
};
}
pub fn deinit(self: *Element) void {
self.attributes.deinit();
while (self.children.popFirst()) |child| {
switch (child.data) {
.element => child.data.element.deinit(),
else => {},
}
self.allocator.destroy(child);
}
}
pub fn addElement(self: *Element, child: Type) !*Element {
var node = try self.allocator.create(Children.Node);
self.children.append(node);
node.data = .{ .element = Element.init(self, child, self.allocator) };
return &node.data.element;
}
pub fn addText(self: *Element, child: []const u8) ![]const u8 {
var node = try self.allocator.create(Children.Node);
self.children.append(node);
node.data = .{ .text = child };
return node.data.text;
}
/// Returns the nesting depth of non-inline elements of self
fn getBlockDepth(self: *const Element) u8 {
if (self.parent) |parent| {
if (self.element_type.isInline()) {
return parent.getBlockDepth();
} else {
return parent.getBlockDepth() + 1;
}
} else {
return 0;
}
}
fn formatIndentation(
tab_count: usize,
tab_width: usize,
writer: anytype,
) !void {
var i: usize = tab_count * tab_width;
while (i > 0) : (i -= 1) {
try writer.writeByte(' ');
}
}
fn formatAttributes(
self: *const Element,
writer: anytype,
) !void {
var iter = self.attributes.iterator();
while (iter.next()) |attribute| {
try writer.print(" {s}={s}", .{ attribute.key_ptr.*, attribute.value_ptr.* });
}
}
fn formatChildren(
self: *const Element,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
var iter = self.children.first;
while (iter) |node| : (iter = node.next) {
switch (node.data) {
.text => |t| {
try writer.print("{s}", .{t});
},
.element => |e| {
try e.format(fmt, options, writer);
},
}
}
}
pub fn format(
self: *const Element,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) @TypeOf(writer).Error!void {
_ = options;
const name = @tagName(self.element_type);
if (fmt.len == 0) {
try writer.writeByte('{');
try writer.print("Element tag={s}", .{name});
try self.formatAttributes(writer);
try writer.writeAll(" children=");
try self.formatChildren(fmt, options, writer);
try writer.writeByte('}');
} else if (comptime std.mem.eql(u8, "html", fmt)) {
try writer.print("<{s}", .{name});
try self.formatAttributes(writer);
try writer.writeByte('>');
if (!self.element_type.isInline()) {
try writer.writeByte('\n');
try Element.formatIndentation(self.getBlockDepth() + 1, options.width orelse 2, writer);
}
try self.formatChildren(fmt, options, writer);
if (!self.element_type.isInline()) {
try writer.writeByte('\n');
try Element.formatIndentation(self.getBlockDepth(), options.width orelse 2, writer);
}
try writer.print("</{s}>", .{name});
} else {
@compileLog(fmt);
@compileError("Element format must be {} or {html}");
}
}
test "Element formatting as html" {
var buf = [_]u8{0} ** 1024;
var p1 = Element.init(null, .p, std.testing.allocator);
defer p1.deinit();
var p2 = try p1.addElement(.p);
var a = try p2.addElement(.a);
try a.attributes.put("class", "bold");
_ = try a.addText("hello, ");
_ = try p1.addText("world!");
try std.testing.expectEqualStrings(
\\<p>
\\ <p>
\\ <a class=bold>hello, </a>
\\ </p>world!
\\</p>
, try std.fmt.bufPrint(&buf, "{html}", .{p1}));
} | src/web/html/Element.zig |
pub const SYS = enum(usize) {
io_setup = 0x00,
io_destroy = 0x01,
io_submit = 0x02,
io_cancel = 0x03,
io_getevents = 0x04,
setxattr = 0x05,
lsetxattr = 0x06,
fsetxattr = 0x07,
getxattr = 0x08,
lgetxattr = 0x09,
fgetxattr = 0x0a,
listxattr = 0x0b,
llistxattr = 0x0c,
flistxattr = 0x0d,
removexattr = 0x0e,
lremovexattr = 0x0f,
fremovexattr = 0x10,
getcwd = 0x11,
lookup_dcookie = 0x12,
eventfd2 = 0x13,
epoll_create1 = 0x14,
epoll_ctl = 0x15,
epoll_pwait = 0x16,
dup = 0x17,
dup3 = 0x18,
fcntl = 0x19,
inotify_init1 = 0x1a,
inotify_add_watch = 0x1b,
inotify_rm_watch = 0x1c,
ioctl = 0x1d,
ioprio_set = 0x1e,
ioprio_get = 0x1f,
flock = 0x20,
mknodat = 0x21,
mkdirat = 0x22,
unlinkat = 0x23,
symlinkat = 0x24,
linkat = 0x25,
renameat = 0x26,
umount2 = 0x27,
mount = 0x28,
pivot_root = 0x29,
nfsservctl = 0x2a,
statfs = 0x2b,
fstatfs = 0x2c,
truncate = 0x2d,
ftruncate = 0x2e,
fallocate = 0x2f,
faccessat = 0x30,
chdir = 0x31,
fchdir = 0x32,
chroot = 0x33,
fchmod = 0x34,
fchmodat = 0x35,
fchownat = 0x36,
fchown = 0x37,
openat = 0x38,
close = 0x39,
vhangup = 0x3a,
pipe2 = 0x3b,
quotactl = 0x3c,
getdents64 = 0x3d,
lseek = 0x3e,
read = 0x3f,
write = 0x40,
readv = 0x41,
writev = 0x42,
pread64 = 0x43,
pwrite64 = 0x44,
preadv = 0x45,
pwritev = 0x46,
sendfile = 0x47,
pselect6 = 0x48,
ppoll = 0x49,
signalfd4 = 0x4a,
vmsplice = 0x4b,
splice = 0x4c,
tee = 0x4d,
readlinkat = 0x4e,
newfstatat = 0x4f,
fstat = 0x50,
sync = 0x51,
fsync = 0x52,
fdatasync = 0x53,
sync_file_range = 0x54,
timerfd_create = 0x55,
timerfd_settime = 0x56,
timerfd_gettime = 0x57,
utimensat = 0x58,
acct = 0x59,
capget = 0x5a,
capset = 0x5b,
personality = 0x5c,
exit = 0x5d,
exit_group = 0x5e,
waitid = 0x5f,
set_tid_address = 0x60,
unshare = 0x61,
futex = 0x62,
set_robust_list = 0x63,
get_robust_list = 0x64,
nanosleep = 0x65,
getitimer = 0x66,
setitimer = 0x67,
kexec_load = 0x68,
init_module = 0x69,
delete_module = 0x6a,
timer_create = 0x6b,
timer_gettime = 0x6c,
timer_getoverrun = 0x6d,
timer_settime = 0x6e,
timer_delete = 0x6f,
clock_settime = 0x70,
clock_gettime = 0x71,
clock_getres = 0x72,
clock_nanosleep = 0x73,
syslog = 0x74,
ptrace = 0x75,
sched_setparam = 0x76,
sched_setscheduler = 0x77,
sched_getscheduler = 0x78,
sched_getparam = 0x79,
sched_setaffinity = 0x7a,
sched_getaffinity = 0x7b,
sched_yield = 0x7c,
sched_get_priority_max = 0x7d,
sched_get_priority_min = 0x7e,
sched_rr_get_interval = 0x7f,
restart_syscall = 0x80,
kill = 0x81,
tkill = 0x82,
tgkill = 0x83,
sigaltstack = 0x84,
rt_sigsuspend = 0x85,
rt_sigaction = 0x86,
rt_sigprocmask = 0x87,
rt_sigpending = 0x88,
rt_sigtimedwait = 0x89,
rt_sigqueueinfo = 0x8a,
rt_sigreturn = 0x8b,
setpriority = 0x8c,
getpriority = 0x8d,
reboot = 0x8e,
setregid = 0x8f,
setgid = 0x90,
setreuid = 0x91,
setuid = 0x92,
setresuid = 0x93,
getresuid = 0x94,
setresgid = 0x95,
getresgid = 0x96,
setfsuid = 0x97,
setfsgid = 0x98,
times = 0x99,
setpgid = 0x9a,
getpgid = 0x9b,
getsid = 0x9c,
setsid = 0x9d,
getgroups = 0x9e,
setgroups = 0x9f,
uname = 0xa0,
sethostname = 0xa1,
setdomainname = 0xa2,
getrlimit = 0xa3,
setrlimit = 0xa4,
getrusage = 0xa5,
umask = 0xa6,
prctl = 0xa7,
getcpu = 0xa8,
gettimeofday = 0xa9,
settimeofday = 0xaa,
adjtimex = 0xab,
getpid = 0xac,
getppid = 0xad,
getuid = 0xae,
geteuid = 0xaf,
getgid = 0xb0,
getegid = 0xb1,
gettid = 0xb2,
sysinfo = 0xb3,
mq_open = 0xb4,
mq_unlink = 0xb5,
mq_timedsend = 0xb6,
mq_timedreceive = 0xb7,
mq_notify = 0xb8,
mq_getsetattr = 0xb9,
msgget = 0xba,
msgctl = 0xbb,
msgrcv = 0xbc,
msgsnd = 0xbd,
semget = 0xbe,
semctl = 0xbf,
semtimedop = 0xc0,
semop = 0xc1,
shmget = 0xc2,
shmctl = 0xc3,
shmat = 0xc4,
shmdt = 0xc5,
socket = 0xc6,
socketpair = 0xc7,
bind = 0xc8,
listen = 0xc9,
accept = 0xca,
connect = 0xcb,
getsockname = 0xcc,
getpeername = 0xcd,
sendto = 0xce,
recvfrom = 0xcf,
setsockopt = 0xd0,
getsockopt = 0xd1,
shutdown = 0xd2,
sendmsg = 0xd3,
recvmsg = 0xd4,
readahead = 0xd5,
brk = 0xd6,
munmap = 0xd7,
mremap = 0xd8,
add_key = 0xd9,
request_key = 0xda,
keyctl = 0xdb,
clone = 0xdc,
execve = 0xdd,
mmap = 0xde,
fadvise64 = 0xdf,
swapon = 0xe0,
swapoff = 0xe1,
mprotect = 0xe2,
msync = 0xe3,
mlock = 0xe4,
munlock = 0xe5,
mlockall = 0xe6,
munlockall = 0xe7,
mincore = 0xe8,
madvise = 0xe9,
remap_file_pages = 0xea,
mbind = 0xeb,
get_mempolicy = 0xec,
set_mempolicy = 0xed,
migrate_pages = 0xee,
move_pages = 0xef,
rt_tgsigqueueinfo = 0xf0,
perf_event_open = 0xf1,
accept4 = 0xf2,
recvmmsg = 0xf3,
wait4 = 0x104,
prlimit64 = 0x105,
fanotify_init = 0x106,
fanotify_mark = 0x107,
name_to_handle_at = 0x108,
open_by_handle_at = 0x109,
clock_adjtime = 0x10a,
syncfs = 0x10b,
setns = 0x10c,
sendmmsg = 0x10d,
process_vm_readv = 0x10e,
process_vm_writev = 0x10f,
kcmp = 0x110,
finit_module = 0x111,
sched_setattr = 0x112,
sched_getattr = 0x113,
renameat2 = 0x114,
seccomp = 0x115,
getrandom = 0x116,
memfd_create = 0x117,
bpf = 0x118,
execveat = 0x119,
userfaultfd = 0x11a,
membarrier = 0x11b,
mlock2 = 0x11c,
copy_file_range = 0x11d,
preadv2 = 0x11e,
pwritev2 = 0x11f,
pkey_mprotect = 0x120,
pkey_alloc = 0x121,
pkey_free = 0x122,
statx = 0x123,
}; | src/linux/aarch64/consts.zig |
const std = @import("std");
const Builder = std.build.Builder;
const LibExeObjStep = std.build.LibExeObjStep;
// set this to true to link libc
const should_link_libc = false;
const test_files = [_][]const u8{
// list any zig files with tests here
"src/day01.zig",
"src/day02.zig",
"src/day03.zig",
};
fn linkObject(b: *Builder, obj: *LibExeObjStep) void {
if (should_link_libc) obj.linkLibC();
_ = b;
// Add linking for packages or third party libraries here
}
pub fn build(b: *Builder) void {
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
// Standard release options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
const mode = b.standardReleaseOptions();
const install_all = b.step("install_all", "Install all days");
const run_all = b.step("run_all", "Run all days");
// Set up an exe for each day
var day: u32 = 1;
while (day <= 25) : (day += 1) {
const dayString = b.fmt("day{:0>2}", .{day});
const zigFile = b.fmt("src/{s}.zig", .{dayString});
const exe = b.addExecutable(dayString, zigFile);
exe.setTarget(target);
exe.setBuildMode(mode);
linkObject(b, exe);
exe.install();
const install_cmd = b.addInstallArtifact(exe);
const step_key = b.fmt("install_{s}", .{dayString});
const step_desc = b.fmt("Install {s}.exe", .{dayString});
const install_step = b.step(step_key, step_desc);
install_step.dependOn(&install_cmd.step);
install_all.dependOn(&install_cmd.step);
const run_cmd = exe.run();
run_cmd.step.dependOn(&install_cmd.step);
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_desc = b.fmt("Run {s}", .{dayString});
const run_step = b.step(dayString, run_desc);
run_step.dependOn(&run_cmd.step);
run_all.dependOn(&run_cmd.step);
}
// Set up a step to run all tests
const test_step = b.step("test", "Run all tests");
for (test_files) |file| {
const test_cmd = b.addTest(file);
test_cmd.setTarget(target);
test_cmd.setBuildMode(mode);
linkObject(b, test_cmd);
test_step.dependOn(&test_cmd.step);
}
} | build.zig |
const std = @import("std");
var prng: std.rand.Xoshiro256 = undefined;
var prng_exists = false;
const default_alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvexyz-";
const default_id_size = 21;
const default_mask = 63;
fn random() !void {
// Instantiate a random seed from the os random generator
var seed: u64 = undefined;
try std.os.getrandom(std.mem.asBytes(&seed));
// Instantiate the PRNG using the seed
prng = std.rand.DefaultPrng.init(seed);
prng_exists = true;
}
/// default is the default implementation of a Nanoid. It uses the default len and default alphabet.
pub fn default() ![default_id_size]u8 {
// Instantiate PRNG
if (!prng_exists) {
try random();
}
// Feel a buffer with random bytes
var buf: [default_id_size]u8 = undefined;
prng.random().bytes(&buf);
var i: u8 = 0;
var id: [default_id_size]u8 = undefined;
while (i < default_id_size) {
id[i] = default_alphabet[buf[i] & default_mask];
i += 1;
}
return id;
}
/// customLen implements a nanoid generation that takes an id size.
pub fn customLen(allocator: *std.mem.Allocator, id_size: u32) ![]u8 {
if (!prng_exists) {
try random();
}
var buf = try allocator.alloc(u8, id_size);
prng.random().bytes(buf);
var i: u32 = 0;
const id = try allocator.alloc(u8, id_size);
while (i < id_size) {
id[i] = default_alphabet[buf[i] & default_mask];
i += 1;
}
return id;
}
/// From https://github.com/ai/nanoid/blob/main/index.js:
/// First, a bitmask is necessary to generate the ID. The bitmask makes bytes
/// values closer to the alphabet size. The bitmask calculates the closest
/// `2^31 - 1` number, which exceeds the alphabet size.
/// For example, the bitmask for the alphabet size 30 is 31 (00011111).
fn calcMask(alphabet_size: u32) !u32 {
var size: u32 = if (alphabet_size - 1 == 0) 1 else alphabet_size - 1;
// Count leading zeroes (clz)
const clz = @clz(u32, size);
const p = try std.math.powi(u32, 2, (@typeInfo(u32).Int.bits - clz));
return p - 1;
}
/// From https://github.com/ai/nanoid/blob/main/index.js:
/// Calculate how many random bytes to generate.
/// The number of random bytes gets decided upon the ID size, mask,
/// alphabet size, and magic number 1.6 (using 1.6 peaks at performance
/// according to benchmarks) (source?)
fn countRandBytes(id_size: u32, alphabet_size: u32, mask: u32) u32 {
return @floatToInt(u32, @ceil(1.6 * (@intToFloat(f32, mask * id_size) / @intToFloat(f32, alphabet_size))));
}
/// customAlphabet generates a nanoid given a custom alphabet and a size for the resulting id
pub fn customAlphabet(allocator: *std.mem.Allocator, size: u32, alphabet: []u8) ![]u8 {
// Instantiate PRNG
if (!prng_exists) {
try random();
}
// Calculate mask
const alphabet_size: u32 = @intCast(u32, alphabet.len);
const id_size = @intCast(u32, size);
const mask = try calcMask(alphabet_size);
// Random bytes buffer
const buf_size = countRandBytes(id_size, alphabet_size, mask);
var buf = try allocator.alloc(u8, buf_size);
prng.random().bytes(buf);
// Allocate ID buffer
const id = try allocator.alloc(u8, id_size);
// Generate ID
var i: u8 = 0;
var j: u8 = 0;
var index: u32 = undefined;
while (i < buf_size) {
if (j == id_size) {
return id;
}
index = buf[i] & mask;
if (index < alphabet_size) {
id[j] = alphabet[index];
j += 1;
}
i += 1;
}
return id;
}
test "nanoid default length and alphabet" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
var id = try default();
std.debug.print("{s}\n", .{ id });
try std.testing.expect(id.len == 21);
}
test "nanoid with length 30" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = &arena.allocator();
var id = try customLen(allocator, 30);
std.debug.print("{s}\n", .{ id });
try std.testing.expect(id.len == 30);
}
test "nanoid with length 255" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = &arena.allocator();
var id = try customLen(allocator, 256);
std.debug.print("{s}\n", .{ id });
try std.testing.expect(id.len == 256);
}
test "nanoid with custom alphabet" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = &arena.allocator();
var numbers = "0123456789";
const n = try allocator.alloc(u8, numbers.len);
std.mem.copy(u8, n, numbers);
var id = try customAlphabet(allocator, 25, n);
std.debug.print("{s}\n", .{ id });
try std.testing.expect(id.len == 25);
}
test "mask for alphabet size 8" {
const mask = try calcMask(8);
std.debug.print("{d}\n", .{ mask });
try std.testing.expect(mask == 7);
}
test "mask for alphabet size 30" {
const mask = try calcMask(30);
std.debug.print("{d}\n", .{ mask });
try std.testing.expect(mask == 31);
}
test "mask for alphabet size 254" {
const mask = try calcMask(254);
std.debug.print("{d}\n", .{ mask });
try std.testing.expect(mask == 255);
} | nanoid.zig |
const wlr = @import("wlroots.zig");
const wayland = @import("wayland");
const wl = wayland.server.wl;
pub const Backend = extern struct {
const Impl = opaque {};
impl: *const Impl,
events: extern struct {
destroy: wl.Signal(*Backend),
new_input: wl.Signal(*wlr.InputDevice),
new_output: wl.Signal(*wlr.Output),
},
// backend.h
extern fn wlr_backend_autocreate(server: *wl.Server) ?*Backend;
pub fn autocreate(server: *wl.Server) !*Backend {
return wlr_backend_autocreate(server) orelse error.BackendCreateFailed;
}
extern fn wlr_backend_start(backend: *Backend) bool;
pub fn start(backend: *Backend) !void {
if (!wlr_backend_start(backend)) {
return error.BackendStartFailed;
}
}
extern fn wlr_backend_destroy(backend: *Backend) void;
pub const destroy = wlr_backend_destroy;
extern fn wlr_backend_get_renderer(backend: *Backend) ?*wlr.Renderer;
pub const getRenderer = wlr_backend_get_renderer;
extern fn wlr_backend_get_session(backend: *Backend) ?*wlr.Session;
pub const getSession = wlr_backend_get_session;
// backend/multi.h
extern fn wlr_multi_backend_create(server: *wl.Server) ?*Backend;
pub fn createMulti(server: *wl.Server) !*Backend {
return wlr_multi_backend_create(server) orelse error.BackendCreateFailed;
}
extern fn wlr_multi_backend_add(multi: *Backend, backend: *Backend) bool;
pub const multiAdd = wlr_multi_backend_add;
extern fn wlr_multi_backend_remove(multi: *Backend, backend: *Backend) void;
pub const multiRemove = wlr_multi_backend_remove;
extern fn wlr_backend_is_multi(backend: *Backend) bool;
pub const isMulti = wlr_backend_is_multi;
extern fn wlr_multi_is_empty(backend: *Backend) bool;
pub const multiIsEmpty = wlr_multi_is_empty;
extern fn wlr_multi_for_each_backend(backend: *Backend, callback: fn (backend: *Backend, data: ?*c_void) callconv(.C) void, data: ?*c_void) void;
pub const multiForEachBackend = wlr_multi_for_each_backend;
// backend/noop.h
extern fn wlr_noop_backend_create(server: *wl.Server) ?*Backend;
pub fn createNoop(server: *wl.Server) !*Backend {
return wlr_noop_backend_create(server) orelse error.BackendCreateFailed;
}
extern fn wlr_noop_add_output(noop: *Backend) ?*wlr.Output;
pub fn noopAddOutput(noop: *Backend) !*wlr.Output {
return wlr_noop_add_output(noop) orelse error.OutOfMemory;
}
extern fn wlr_backend_is_noop(backend: *Backend) bool;
pub const isNoop = wlr_backend_is_noop;
}; | src/backend.zig |
const std = @import("std");
const builtin = @import("builtin");
const Vector = std.meta.Vector;
pub const NativeVector = struct {
len: u16,
ChildType: type,
const Self = @This();
/// Returns a native vector of type T.
pub fn init(comptime T: type) NativeVector {
return .{
.len = vectorLen(T),
.ChildType = T,
};
}
/// Returns true if vector operations with type T are supported.
pub fn supportsType(comptime T: type) bool {
return switch (T) {
u8, i8, u16, i16, u32, i32, f32, f64 => true,
u64, i64 => builtin.cpu.arch == .x86_64 and std.Target.x86.featureSetHas(builtin.cpu.features, .avx512f),
else => false,
};
}
/// Returns the number of items that a native vector of type T can hold.
pub fn vectorLen(comptime T: type) u16 {
const arch = builtin.cpu.arch;
// zig fmt: off
const byte_len: u16 =
if (arch == .x86_64 and std.Target.x86.featureSetHas(builtin.cpu.features, .avx512bw)) 64
else if (arch == .x86_64 and std.Target.x86.featureSetHas(builtin.cpu.features, .avx2)) 32
else 16;
const int32_len: u16 =
if (arch == .x86_64 and std.Target.x86.featureSetHas(builtin.cpu.features, .avx512f)) 16
else if (arch == .x86_64 and std.Target.x86.featureSetHas(builtin.cpu.features, .avx2)) 8
else 4;
const float_len: u16 =
if (arch == .x86_64 and std.Target.x86.featureSetHas(builtin.cpu.features, .avx512f)) 16
else if (arch == .x86_64 and std.Target.x86.featureSetHas(builtin.cpu.features, .avx)) 8
else 4;
// zig fmt: on
return switch (T) {
u8, i8 => byte_len,
u16, i16 => byte_len / 2,
u32, i32 => int32_len,
u64, i64 => int32_len / 2,
f32 => float_len,
f64 => float_len / 2,
else => @compileError("Vectors of " ++ @typeName(T) ++ " not supported"),
};
}
pub fn Type(comptime self: Self) type {
return Vector(self.len, self.ChildType);
}
pub fn minIndex(comptime self: Self, slice_len: usize) usize {
return slice_len % self.len;
}
pub fn maxIndex(comptime self: Self, slice_len: usize) usize {
return slice_len - slice_len % self.len;
}
pub fn splat(comptime self: Self, value: self.ChildType) Vector(self.len, self.ChildType) {
return @splat(self.len, value);
}
pub inline fn load(comptime self: Self, slice: []const self.ChildType) Vector(self.len, self.ChildType) {
const result: Vector(self.len, self.ChildType) = slice[0..self.len].*;
return result;
}
pub fn store(comptime self: Self, slice: []self.ChildType, v: Vector(self.len, self.ChildType)) void {
slice[0..self.len].* = v;
}
pub fn anyTrue(comptime self: Self, cmp: Vector(self.len, bool)) bool {
return @reduce(.Or, cmp);
}
pub fn allTrue(comptime self: Self, cmp: Vector(self.len, bool)) bool {
return @reduce(.And, cmp);
}
fn BitType(comptime len: u16) type {
return std.meta.Int(.unsigned, len);
}
/// Converts a vector of bools to an unsigned integer.
pub fn bitCast(comptime self: Self, cmp: Vector(self.len, bool)) BitType(self.len) {
return @ptrCast(*const BitType(self.len), &cmp).*;
}
pub fn leadingFalseCount(comptime self: Self, cmp: Vector(self.len, bool)) u16 {
return @ctz(BitType(self.len), self.bitCast(cmp));
}
pub fn trailingFalseCount(comptime self: Self, cmp: Vector(self.len, bool)) u16 {
return @clz(BitType(self.len), self.bitCast(cmp));
}
}; | src/native_vector.zig |
const w4 = @import("wasm4.zig");
const statemachine = @import("state-machine.zig");
const mainmenu = @import("screens/main-menu.zig");
const party = @import("screens/party.zig");
const presscon = @import("screens/press-conference.zig");
const startscreen = @import("screens/start-screen.zig");
const houseofcommons = @import("screens/house-of-commons.zig");
const bigben = @import("screens/big-ben.zig");
const suegray = @import("screens/sue-gray-report.zig");
const gamepad = @import("gamepad.zig");
const std = @import("std");
const RndGen = std.rand.DefaultPrng;
var player = gamepad.GamePad{};
// game states
var state: statemachine.StateMachine = undefined;
var partystate: party.PartyState = undefined;
var pressconstate: presscon.PressState = undefined;
var menustate: mainmenu.Menu = undefined;
var parliament: houseofcommons.Parliament = undefined;
var suegrayreport: suegray.SueGrayReport = undefined;
var rnd: std.rand.Random = undefined;
export fn start() void {
w4.PALETTE.* = .{
// XRGBx
0x00DDDDDD,
0x00000000,
0x009E9E9E,
0x00FFFFFF,
};
rnd = RndGen.init(69).random();
// init the allocation buffer
state = statemachine.StateMachine.init();
partystate = party.PartyState.init(&rnd);
pressconstate = presscon.PressState.init(&rnd);
menustate = mainmenu.Menu.init();
parliament = houseofcommons.Parliament.init(&rnd);
suegrayreport = suegray.SueGrayReport.init();
}
var ticker: u32 = 0;
pub fn bigBenTo(next: statemachine.Screens, duration: u32) void {
bigben.update();
ticker += 1;
if (ticker == duration) {
ticker = 0;
state.change(next);
}
}
export fn update() void {
switch (state.screen) {
.IN_MENU => menustate.update(&state, &player),
.AT_PARTY => partystate.update(&state, &player),
.AT_PRESS_CONFERENCE => pressconstate.update(&state, &player, &partystate.choices),
.AT_HOUSE_OF_COMMONS => parliament.update(&state, &player),
.START_SCREEN => startscreen.update(&state, &player),
.FROM_COMMONS_TRANSITION => bigBenTo(.SUE_GRAY, 40),
.TO_COMMONS_TRANSITION => bigBenTo(.AT_HOUSE_OF_COMMONS, 40),
.TO_PRESS_CONFERENCE => bigBenTo(.AT_PRESS_CONFERENCE, 40),
.SUE_GRAY => suegrayreport.update(&state, &player),
.ROUND_DONE => {
// tally score
// reset state and go again
state.change(.AT_PARTY);
},
else => {},
}
state.playMusic();
player.update();
} | src/main.zig |
const std = @import("std");
const FileSource = std.build.FileSource;
const builtin = @import("builtin");
const t_path = "tmp/";
const k_path = "kernel/";
const p_path = k_path ++ "platform/";
const root_path = t_path ++ "root/";
const boot_path = root_path ++ "boot/";
const bin_path = root_path ++ "bin/";
const utils_pkg = std.build.Pkg{
.name = "utils",
.path = .{.path = "libs/utils/utils.zig"},
};
const georgios_pkg = std.build.Pkg{
.name = "georgios",
.path = .{.path = "libs/georgios/georgios.zig"},
.dependencies = &[_]std.build.Pkg {
utils_pkg,
},
};
var b: *std.build.Builder = undefined;
var target: std.zig.CrossTarget = undefined;
var alloc: std.mem.Allocator = undefined;
var kernel: *std.build.LibExeObjStep = undefined;
var test_step: *std.build.Step = undefined;
const program_link_script = FileSource{.path = "programs/linking.ld"};
fn format(comptime fmt: []const u8, args: anytype) []u8 {
return std.fmt.allocPrint(alloc, fmt, args) catch unreachable;
}
fn add_tests(source: []const u8) void {
const tests = b.addTest(source);
tests.addPackage(utils_pkg);
tests.addPackage(georgios_pkg);
test_step.dependOn(&tests.step);
}
pub fn build(builder: *std.build.Builder) void {
b = builder;
var arena_alloc = std.heap.ArenaAllocator.init(std.heap.page_allocator);
alloc = arena_alloc.allocator();
const multiboot_vbe = b.option(bool, "multiboot_vbe",
\\Ask the bootloader to switch to a graphics mode for us.
) orelse false;
const vbe = b.option(bool, "vbe",
\\Use VBE Graphics if possible.
) orelse multiboot_vbe;
const debug_log = b.option(bool, "debug_log",
\\Print debug information by default
) orelse true;
const wait_for_anykey = b.option(bool, "wait_for_anykey",
\\Wait for key press at important events
) orelse false;
target = b.standardTargetOptions(.{
.default_target = std.zig.CrossTarget.parse(.{
.arch_os_abi = "i386-freestanding-gnu",
.cpu_features = "pentiumpro"
// TODO: This is to forbid SSE code. See SSE init code in
// kernel_start_x86_32.zig for details.
}) catch @panic("Failed Making Default Target"),
});
const platform = switch (target.cpu_arch.?) {
.i386 => "x86_32",
else => {
std.debug.print("Unsupported Platform: {s}\n", .{@tagName(target.cpu_arch.?)});
@panic("Unsupported Platform");
},
};
// Set install prefix to root
// TODO: Might break in the future?
b.resolveInstallPrefix(root_path, .{});
// Tests
test_step = b.step("test", "Run Tests");
add_tests("libs/utils/test.zig");
add_tests("libs/georgios/test.zig");
add_tests("kernel/test.zig");
// Kernel
const root_file = format("{s}kernel_start_{s}.zig", .{k_path, platform});
kernel = b.addExecutable("kernel.elf", root_file);
kernel.override_dest_dir = std.build.InstallDir{.custom = "boot"};
kernel.setLinkerScriptPath(std.build.FileSource.relative(p_path ++ "linking.ld"));
kernel.setTarget(target);
const kernel_options = b.addOptions();
kernel_options.addOption(bool, "multiboot_vbe", multiboot_vbe);
kernel_options.addOption(bool, "vbe", vbe);
kernel_options.addOption(bool, "debug_log", debug_log);
kernel_options.addOption(bool, "wait_for_anykey", wait_for_anykey);
kernel_options.addOption(bool, "is_kernel", true);
kernel.addOptions("build_options", kernel_options);
// Packages
kernel.addPackage(utils_pkg);
kernel.addPackage(georgios_pkg);
// System Calls
var generate_system_calls_step = b.addSystemCommand(&[_][]const u8{
"scripts/codegen/generate_system_calls.py"
});
kernel.step.dependOn(&generate_system_calls_step.step);
// bios_int/libx86emu
build_bios_int();
// ACPICA
build_acpica();
kernel.install();
// Programs
build_program("shell");
build_program("hello");
build_program("ls");
build_program("cat");
build_program("snake");
build_program("cksum");
build_program("img");
// build_zig_program("hello-zig");
// build_c_program("hello-c");
}
const disable_ubsan = "-fsanitize-blacklist=misc/clang-sanitize-blacklist.txt";
fn build_bios_int() void {
var bios_int = b.addObject("bios_int", null);
bios_int.setTarget(target);
const bios_int_path = p_path ++ "bios_int/";
const libx86emu_path = bios_int_path ++ "libx86emu/";
const pub_inc = bios_int_path ++ "public_include/";
bios_int.addIncludeDir(libx86emu_path ++ "include/");
bios_int.addIncludeDir(bios_int_path ++ "private_include/");
bios_int.addIncludeDir(pub_inc);
const sources = [_][]const u8 {
libx86emu_path ++ "api.c",
libx86emu_path ++ "decode.c",
libx86emu_path ++ "mem.c",
libx86emu_path ++ "ops2.c",
libx86emu_path ++ "ops.c",
libx86emu_path ++ "prim_ops.c",
bios_int_path ++ "bios_int.c",
};
for (sources) |source| {
bios_int.addCSourceFile(source, &[_][]const u8{disable_ubsan});
}
kernel.addObject(bios_int);
kernel.addIncludeDir(pub_inc);
}
fn build_acpica() void {
var acpica = b.addObject("acpica", null);
acpica.setTarget(target);
const components = [_][]const u8 {
"dispatcher",
"events",
"executer",
"hardware",
"namespace",
"parser",
"resources",
"tables",
"utilities",
};
const acpica_path = p_path ++ "acpica/";
const source_path = acpica_path ++ "acpica/source/";
// Configure Source
var configure_step = b.addSystemCommand(&[_][]const u8{
acpica_path ++ "prepare_source.py", acpica_path});
acpica.step.dependOn(&configure_step.step);
// Includes
for ([_]*std.build.LibExeObjStep{kernel, acpica}) |obj| {
obj.addIncludeDir(acpica_path ++ "include");
obj.addIncludeDir(source_path ++ "include");
obj.addIncludeDir(source_path ++ "include/platform");
}
// Add Sources
for (components) |component| {
const component_path = std.fs.path.join(alloc,
&[_][]const u8{source_path, "components", component}) catch unreachable;
var component_dir =
std.fs.cwd().openDir(component_path, .{.iterate = true}) catch unreachable;
defer component_dir.close();
var walker = component_dir.walk(alloc) catch unreachable;
while (walker.next() catch unreachable) |i| {
const path = i.path;
if (std.mem.endsWith(u8, path, ".c") and
!std.mem.endsWith(u8, path, "dump.c")) {
const full_path = std.fs.path.join(alloc,
&[_][]const u8{component_path, path}) catch unreachable;
// std.debug.print("acpica source: {s}\n", .{full_path});
acpica.addCSourceFile(b.dupe(full_path), &[_][]const u8{disable_ubsan});
}
}
}
kernel.addObject(acpica);
// var crt0 = b.addObject("crt0", "libs/georgios/georgios.zig");
// crt0.addBuildOption(bool, "is_crt", true);
// crt0.override_dest_dir = std.build.InstallDir{.Custom = "lib"};
// crt0.setTarget(target);
// crt0.addPackage(utils_pkg);
// crt0.install();
}
fn build_program(name: []const u8) void {
const elf = format("{s}.elf", .{name});
const zig = format("programs/{s}/{s}.zig", .{name, name});
const prog = b.addExecutable(elf, zig);
prog.setLinkerScriptPath(program_link_script);
prog.setTarget(target);
prog.addPackage(georgios_pkg);
prog.install();
}
fn build_zig_program(name: []const u8) void {
const elf = format("{s}.elf", .{name});
const zig = format("programs/{s}/{s}.zig", .{name, name});
const prog = b.addExecutable(elf, zig);
prog.setLinkerScriptPath(program_link_script);
prog.setTarget(
std.zig.CrossTarget.parse(.{
.arch_os_abi = "i386-georgios-gnu",
.cpu_features = "pentiumpro"
}) catch @panic("Failed Making Default Target")
);
prog.install();
}
// fn add_libc(what: *std.build.LibExeObjStep) void {
// what.addLibPath("/data/development/os/newlib/newlib/i386-pc-georgios/newlib");
// what.addSystemIncludeDir("/data/development/os/newlib/newlib/newlib/libc/include");
// what.linkSystemLibraryName("c");
// }
fn build_c_program(name: []const u8) void {
const elf = format("{s}.elf", .{name});
const c = format("programs/{s}/{s}.c", .{name, name});
const prog = b.addExecutable(elf, null);
prog.addCSourceFile(c, &[_][]const u8{"--libc /data/development/os/georgios/newlib"});
// add_libc(prog);
prog.setLinkerScriptPath(program_link_script);
prog.setTarget(
std.zig.CrossTarget.parse(.{
.arch_os_abi = "i386-georgios-gnu",
.cpu_features = "pentiumpro"
}) catch @panic("Failed Making Default Target")
);
prog.install();
} | build.zig |
const std = @import("std");
const debug = std.debug;
const ArrayList = std.ArrayList;
const Allocator = std.mem.Allocator;
const HashMap = std.HashMap;
/// A TokenId represents a kind of token. It will also hold its associated data if present.
const TokenId = enum {
Ampersand,
Arrow,
AtSign,
Bang,
BinOr,
BinXor,
BitAndEq,
BitOrEq,
BitShiftLeft,
BitShiftLeftEq,
BitShiftRight,
BitShiftRightEq,
BitXorEq,
CharLiteral,
CmpEq,
CmpGreaterOrEq,
CmpGreaterThan,
CmpLessOrEq,
CmpLessThan,
CmpNotEq,
Colon,
Comment,
Comma,
Dash,
DivEq,
DocComment,
Dot,
DoubleQuestion,
Ellipsis2,
Ellipsis3,
Eof,
Eq,
FatArrow,
FloatLiteral,
IntLiteral,
KeywordAlign,
KeywordAnd,
KeywordAsm,
KeywordBreak,
KeywordColdCC,
KeywordCompTime,
KeywordConst,
KeywordContinue,
KeywordDefer,
KeywordElse,
KeywordEnum,
KeywordError,
KeywordExport,
KeywordExtern,
KeywordFalse,
KeywordFn,
KeywordFor,
KeywordGoto,
KeywordIf,
KeywordInline,
KeywordNakedCC,
KeywordNoAlias,
KeywordNull,
KeywordOr,
KeywordPacked,
KeywordPub,
KeywordReturn,
KeywordStdcallCC,
KeywordStruct,
KeywordSwitch,
KeywordTest,
KeywordThis,
KeywordTrue,
KeywordUndefined,
KeywordUnion,
KeywordUnreachable,
KeywordUse,
KeywordVar,
KeywordVolatile,
KeywordWhile,
LBrace,
LBracket,
LParen,
Maybe,
MaybeAssign,
MinusEq,
MinusPercent,
MinusPercentEq,
MultiLineStringLiteral,
ModEq,
ModuleDocComment,
NumberSign,
Percent,
PercentDot,
PercentPercent,
Plus,
PlusEq,
PlusPercent,
PlusPercentEq,
PlusPlus,
RBrace,
RBracket,
RParen,
Semicolon,
Slash,
Star,
StarStar,
StringLiteral,
Symbol,
Tilde,
TimesEq,
TimesPercent,
TimesPercentEq,
};
const Kw = struct {
name: []const u8,
id: TokenId,
pub fn new(name: []const u8, id: TokenId) -> Kw {
Kw {
.name = name,
.id = id,
}
}
};
const keywords = []Kw {
Kw.new("align", TokenId.KeywordAlign),
Kw.new("and", TokenId.KeywordAnd),
Kw.new("asm", TokenId.KeywordAsm),
Kw.new("break", TokenId.KeywordBreak),
Kw.new("coldcc", TokenId.KeywordColdCC),
Kw.new("comptime", TokenId.KeywordCompTime),
Kw.new("const", TokenId.KeywordConst),
Kw.new("continue", TokenId.KeywordContinue),
Kw.new("defer", TokenId.KeywordDefer),
Kw.new("else", TokenId.KeywordElse),
Kw.new("enum", TokenId.KeywordEnum),
Kw.new("error", TokenId.KeywordError),
Kw.new("export", TokenId.KeywordExport),
Kw.new("extern", TokenId.KeywordExtern),
Kw.new("false", TokenId.KeywordFalse),
Kw.new("fn", TokenId.KeywordFn),
Kw.new("for", TokenId.KeywordFor),
Kw.new("goto", TokenId.KeywordGoto),
Kw.new("if", TokenId.KeywordIf),
Kw.new("inline", TokenId.KeywordInline),
Kw.new("nakedcc", TokenId.KeywordNakedCC),
Kw.new("noalias", TokenId.KeywordNoAlias),
Kw.new("null", TokenId.KeywordNull),
Kw.new("or", TokenId.KeywordOr),
Kw.new("packed", TokenId.KeywordPacked),
Kw.new("pub", TokenId.KeywordPub),
Kw.new("return", TokenId.KeywordReturn),
Kw.new("stdcallcc", TokenId.KeywordStdcallCC),
Kw.new("struct", TokenId.KeywordStruct),
Kw.new("switch", TokenId.KeywordSwitch),
Kw.new("test", TokenId.KeywordTest),
Kw.new("this", TokenId.KeywordThis),
Kw.new("true", TokenId.KeywordTrue),
Kw.new("undefined", TokenId.KeywordUndefined),
Kw.new("union", TokenId.KeywordUnion),
Kw.new("unreachable", TokenId.KeywordUnreachable),
Kw.new("use", TokenId.KeywordUse),
Kw.new("var", TokenId.KeywordVar),
Kw.new("volatile", TokenId.KeywordVolatile),
Kw.new("while", TokenId.KeywordWhile),
};
fn getKeywordId(symbol: []const u8) -> ?TokenId {
for (keywords) |kw| {
if (std.mem.eql(u8, kw.name, symbol)) {
return kw.id;
}
}
null
}
error BadValueForRadix;
error ValueOutOfRange;
const IntOrFloat = enum {
Int: u64, // TODO: Convert back to u128 when __floatuntidf implemented.
Float: f64,
};
/// Returns the digit value of the specified character under the specified radix.
///
/// If the value is too large, an error is returned.
fn getDigitValueForRadix(comptime radix: u8, c: u8) -> %u8 {
const value = switch (c) {
'0' ... '9' => |x| { x - '0' },
'a' ... 'z' => |x| { x - 'a' + 10 },
'A' ... 'Z' => |x| { x - 'A' + 10 },
else => return error.ValueOutOfRange,
};
if (value < radix) {
value
} else {
return error.BadValueForRadix;
}
}
/// Extra data associated with a particular token.
pub const TokenData = enum {
InternPoolRef: []const u8,
Integer: u64,
Float: f64, // TODO: Could change to an f128 (or arbitrary-precision) when printing works
Char: u8,
Error: error,
};
fn printCharEscaped(c: u8) -> %void {
const printf = std.io.stdout.printf;
switch (c) {
'\r' => %return printf("\\r"),
'\t' => %return printf("\\t"),
'\n' => %return printf("\\n"),
'\\' => %return printf("\\\\"),
else => %return printf("{c}", c),
}
}
/// A Token consists of a type/id and an associated location/span within the source file.
pub const Token = struct {
id: TokenId,
span: Span,
data: ?TokenData,
pub fn print(self: &const Token) -> %void {
const printf = std.io.stdout.printf;
%return printf("{}:{} {}",
self.span.start_line,
self.span.start_column,
@enumTagName(self.id)
);
if (self.data) |inner| {
%return printf(" (");
switch (inner) {
TokenData.InternPoolRef => |p_ref| {
for (p_ref) |c| {
%return printCharEscaped(c);
}
},
TokenData.Integer => |i| {
%return printf("{}", i);
},
TokenData.Float => |f| {
%return printf("{}", f);
},
TokenData.Char => |c| {
%return printCharEscaped(c);
},
TokenData.Error => |e| {
%return printf("{}", @errorName(e));
},
}
%return printf(")");
}
%return printf("\n");
}
};
/// A Span represents a contiguous sequence (byte-wise) of a source file.
pub const Span = struct {
start_byte: usize,
end_byte: usize,
start_line: usize,
start_column: usize,
};
error UnicodeCharCodeOutOfRange;
error NewlineInStringLiteral;
error InvalidCharacter;
error InvalidCharacterAfterBackslash;
error MissingCharLiteralData;
error ExtraCharLiteralData;
error EofWhileParsingLiteral;
fn u8eql(a: []const u8, b: []const u8) -> bool {
std.mem.eql(u8, a, b)
}
// The second value is heap allocated.
pub const InternPool = HashMap([]const u8, []const u8, std.mem.hash_slice_u8, u8eql);
pub const Tokenizer = struct {
const Self = this;
tokens: ArrayList(Token),
lines: ArrayList(usize),
intern_pool: InternPool,
errors: ArrayList(Token),
consumed: bool,
allocator: &Allocator,
c_token: ?Token,
c_byte: usize,
c_line: usize,
c_column : usize,
c_buf: []const u8,
/// Initialize a new tokenizer to handle the specified input buffer.
pub fn init(allocator: &Allocator) -> Self {
Self {
.tokens = ArrayList(Token).init(allocator),
.lines = ArrayList(usize).init(allocator),
.intern_pool = InternPool.init(allocator),
.errors = ArrayList(Token).init(allocator),
.consumed = false,
.allocator = allocator,
.c_token = null,
.c_byte = 0,
.c_line = 1,
.c_column = 1,
.c_buf = undefined,
}
}
/// Deinitialize the internal tokenizer state.
pub fn deinit(self: &Self) {
self.tokens.deinit();
self.lines.deinit();
self.intern_pool.deinit();
self.errors.deinit();
}
/// Returns the next byte in the buffer and advances our position.
///
/// If we have reached the end of the stream, null is returned.
fn nextByte(self: &Self) -> ?u8 {
if (self.c_byte >= self.c_buf.len) {
null
} else {
const i = self.c_byte;
self.bump(1);
self.c_buf[i]
}
}
/// Mark the current position as the start of a token.
fn beginToken(self: &Self) {
self.c_token = Token {
.id = undefined,
.span = Span {
.start_byte = self.c_byte,
.end_byte = undefined,
.start_line = self.c_line,
.start_column = self.c_column,
},
.data = null,
};
}
/// Set the id of the current token.
fn setToken(self: &Self, id: TokenId) {
(??self.c_token).id = id;
}
/// Mark the current position as the end of the current token.
///
/// A token must have been previously set using beginToken.
fn endToken(self: &Self) -> %void {
var c = ??self.c_token;
c.span.end_byte = self.c_byte + 1;
%return self.tokens.append(c);
self.c_token = null;
}
/// Set the data field for a ArrayList(u8) field using the internal InternPool.
///
/// This takes ownership of the underlying memory.
fn setInternToken(self: &Self, data: &ArrayList(u8)) -> %void {
const ref = if (self.intern_pool.get(data.toSliceConst())) |entry| {
data.deinit();
entry.value
} else {
_ = %return self.intern_pool.put(data.toSliceConst(), data.toSliceConst());
data.toSliceConst()
};
(??self.c_token).data = TokenData.InternPoolRef { ref };
}
/// Mark the current position as the end of a token and set it to a new id.
fn setEndToken(self: &Self, id: TokenId) -> %void {
self.setToken(id);
%return self.endToken();
}
/// Peek at the character n steps ahead in the stream.
///
/// If no token is found, returns the null byte.
// TODO: Return an actual null? Much more verbose during usual parsing though.
fn peek(self: &Self, comptime i: usize) -> u8 {
if (self.c_byte + i >= self.c_buf.len) {
0
} else {
self.c_buf[self.c_byte + i]
}
}
/// Advance the cursor location by n steps.
///
/// Bumping past the end of the buffer has no effect.
fn bump(self: &Self, comptime i: usize) {
var j: usize = 0;
while (j < i) : (j += 1) {
if (self.c_byte >= self.c_buf.len) {
break;
}
if (self.peek(0) == '\n') {
self.c_line += 1;
self.c_column = 1;
} else {
self.c_column += 1;
}
self.c_byte += 1;
}
}
// Actual processing helper routines.
/// Consume an entire integer of the specified radix.
fn consumeInteger(self: &Self, comptime radix: u8, init_value: u64) -> %u64 {
var number = init_value;
var overflowed = false;
while (true) {
const ch = self.peek(0);
const value = if (getDigitValueForRadix(radix, ch)) |ok| {
self.bump(1);
// TODO: Need arbitrary precision to handle this overflow
if (!overflowed) {
{
const previous_number = number;
if (@mulWithOverflow(u64, number, radix, &number)) {
// Revert to previous as this will give partially accurate values for
// floats at least.
number = previous_number;
overflowed = true;
}
}
{
const previous_number = number;
if (@addWithOverflow(u64, number, ok, &number)) {
number = previous_number;
overflowed = true;
}
}
}
} else |_| {
return number;
};
}
}
/// Consumes a decimal exponent for a float.
///
/// This includes an optional leading +, -.
fn consumeFloatExponent(self: &Self, exponent_sign: &bool) -> %u64 {
*exponent_sign = switch (self.peek(0)) {
'-' => {
self.bump(1);
true
},
'+' => {
self.bump(1);
false
},
else => {
false
},
};
self.consumeInteger(10, 0)
}
/// Process a float with the specified radix starting from the decimal part.
///
/// The non-decimal portion should have been processed by `consumeNumber`.
fn consumeFloatFractional(self: &Self, comptime radix: u8, whole_part: u64) -> %f64 {
debug.assert(radix == 10 or radix == 16);
var number = %return self.consumeInteger(radix, 0);
switch (self.peek(0)) {
'e', 'E' => {
self.bump(1);
var is_neg_exp: bool = undefined;
var exp = %return self.consumeFloatExponent(&is_neg_exp);
const whole = if (number != 0) {
const digit_count = usize(1 + std.math.log10(number));
var frac_part = f64(number);
var i: usize = 0;
while (i < digit_count) : (i += 1) {
frac_part /= 10;
}
f64(whole_part) + frac_part
} else {
f64(whole_part)
};
if (is_neg_exp) {
whole / std.math.pow(f64, 10, f64(exp))
} else {
whole * std.math.pow(f64, 10, f64(exp))
}
},
'p', 'P' => {
self.bump(1);
var is_neg_exp: bool = undefined;
var exp = %return self.consumeFloatExponent(&is_neg_exp);
const whole = if (number != 0) {
const digit_count = usize(1 + std.math.log(f64, 16, f64(number)));
var frac_part = f64(number);
var i: usize = 0;
while (i < digit_count) : (i += 1) {
frac_part /= 10;
}
f64(whole_part) + frac_part
} else {
f64(whole_part)
};
if (is_neg_exp) {
whole / std.math.pow(f64, 2, f64(exp))
} else {
whole * std.math.pow(f64, 2, f64(exp))
}
},
else => {
const frac_part = f64(number) / (std.math.pow(f64, f64(10), f64(1 + std.math.log10(number))));
f64(whole_part) + frac_part
},
}
}
/// Processes integer with the specified radix.
///
/// The integer will be represented by an unsigned value.
///
/// This will only modify the current stream position.
//
// TODO: Use big integer generally improve here.
fn consumeNumber(self: &Self, comptime radix: u8, init_value: ?u8) -> %IntOrFloat {
var init_number: u64 = if (init_value) |v| {
%return getDigitValueForRadix(radix, v)
} else {
0
};
const number = %return self.consumeInteger(radix, init_number);
// TODO: Need to be separated by a non-symbol token.
// Raise an error if we find a non-alpha-numeric that doesn't fit. Do at caller?
//
// i.e. 1230174ADAKHJ is invalid.
if (self.peek(0) == '.') {
self.bump(1);
IntOrFloat.Float { %return self.consumeFloatFractional(radix, number) }
} else {
IntOrFloat.Int { number }
}
}
/// Process a character code of the specified length and type.
///
/// Returns the utf8 encoded value of the codepoint.
///
/// This will only modify the current stream position.
fn consumeCharCode(self: &Self,
comptime radix: u8, comptime count: u8, comptime is_unicode: bool) -> %ArrayList(u8)
{
var utf8_code = ArrayList(u8).init(self.allocator);
%defer utf8_code.deinit();
var char_code: u32 = 0;
comptime var i: usize = 0;
inline while (i < count) : (i += 1) {
char_code *= radix;
char_code += %return getDigitValueForRadix(radix, self.peek(0));
self.bump(1);
}
if (is_unicode) {
if (char_code <= 0x7f) {
%return utf8_code.append(u8(char_code));
} else if (char_code <= 0x7ff) {
%return utf8_code.append(0xc0 | u8(char_code >> 6));
%return utf8_code.append(0x80 | u8(char_code & 0x3f));
} else if (char_code <= 0xffff) {
%return utf8_code.append(0xe0 | u8(char_code >> 12));
%return utf8_code.append(0x80 | u8((char_code >> 6) & 0x3f));
%return utf8_code.append(0x80 | u8(char_code & 0x3f));
} else if (char_code <= 0x10ffff) {
%return utf8_code.append(0xf0 | u8(char_code >> 18));
%return utf8_code.append(0x80 | u8((char_code >> 12) & 0x3f));
%return utf8_code.append(0x80 | u8((char_code >> 6) & 0x3f));
%return utf8_code.append(0x80 | u8(char_code & 0x3f));
} else {
return error.UnicodeCharCodeOutOfRange;
}
} else {
%return utf8_code.append(u8(char_code));
}
utf8_code
}
/// Process an escape code.
///
/// Expects the '/' has already been handled by the caller.
///
/// Returns the utf8 encoded value of the codepoint.
fn consumeStringEscape(self: &Self) -> %ArrayList(u8) {
switch (self.peek(0)) {
'x' => {
self.bump(1);
self.consumeCharCode(16, 2, false)
},
'u' => {
self.bump(1);
self.consumeCharCode(16, 4, true)
},
'U' => {
self.bump(1);
self.consumeCharCode(16, 6, true)
},
'n' => {
self.bump(1);
var l = ArrayList(u8).init(self.allocator);
%return l.append('\n');
l
},
'r' => {
self.bump(1);
var l = ArrayList(u8).init(self.allocator);
%return l.append('\r');
l
},
'\\' => {
self.bump(1);
var l = ArrayList(u8).init(self.allocator);
%return l.append('\\');
l
},
't' => {
self.bump(1);
var l = ArrayList(u8).init(self.allocator);
%return l.append('\t');
l
},
'\'' => {
self.bump(1);
var l = ArrayList(u8).init(self.allocator);
%return l.append('\'');
l
},
'"' => {
self.bump(1);
var l = ArrayList(u8).init(self.allocator);
%return l.append('\"');
l
},
else => {
@panic("unexpected character");
}
}
}
/// Process a string, returning the encountered characters.
fn consumeString(self: &Self) -> %ArrayList(u8) {
var literal = ArrayList(u8).init(self.allocator);
%defer literal.deinit();
while (true) {
switch (self.peek(0)) {
'"' => {
self.bump(1);
break;
},
'\n' => {
return error.NewlineInStringLiteral;
},
'\\' => {
self.bump(1);
var value = %return self.consumeStringEscape();
%return literal.appendSlice(value.toSliceConst());
value.deinit();
},
0 => {
return error.EofWhileParsingLiteral;
},
else => |c| {
self.bump(1);
%return literal.append(c);
},
}
}
literal
}
/// Process a line comment, returning the encountered characters
// NOTE: We do not want to strip whitespace from comments since things like diagrams may require
// it to be formatted correctly. We could do trailing but don't bother right now.
fn consumeUntilNewline(self: &Self) -> %ArrayList(u8) {
var comment = ArrayList(u8).init(self.allocator);
%defer comment.deinit();
while (self.nextByte()) |c| {
switch (c) {
'\n' => {
break;
},
else => {
%return comment.append(c);
}
}
}
comment
}
/// Return the next token from the buffer.
pub fn next(t: &Self) -> %?&const Token {
if (t.consumed) {
return null;
}
t.beginToken();
if (t.nextByte()) |ch| {
switch (ch) {
' ', '\r', '\n', '\t' => {},
'(' => %return t.setEndToken(TokenId.LParen),
')' => %return t.setEndToken(TokenId.RParen),
',' => %return t.setEndToken(TokenId.Comma),
'{' => %return t.setEndToken(TokenId.LBrace),
'}' => %return t.setEndToken(TokenId.RBrace),
'[' => %return t.setEndToken(TokenId.LBracket),
']' => %return t.setEndToken(TokenId.RBracket),
';' => %return t.setEndToken(TokenId.Semicolon),
':' => %return t.setEndToken(TokenId.Colon),
'#' => %return t.setEndToken(TokenId.NumberSign),
'~' => %return t.setEndToken(TokenId.Tilde),
'_', 'a' ... 'z', 'A' ... 'Z' => {
var symbol = ArrayList(u8).init(t.allocator);
%return symbol.append(ch);
while (true) {
switch (t.peek(0)) {
'_', 'a' ... 'z', 'A' ... 'Z', '0' ... '9' => |c| {
t.bump(1);
%return symbol.append(c);
},
else => {
break;
},
}
}
if (getKeywordId(symbol.toSliceConst())) |id| {
symbol.deinit();
%return t.setEndToken(id);
} else {
%return t.setInternToken(&symbol);
%return t.setEndToken(TokenId.Symbol);
}
},
'0' => {
const value = switch (t.peek(0)) {
'b' => {
t.bump(1);
%return t.consumeNumber(2, null)
},
'o' => {
t.bump(1);
%return t.consumeNumber(8, null)
},
'x' => {
t.bump(1);
%return t.consumeNumber(16, null)
},
else => {
// TODO: disallow anything after a 0 except a dot.
%return t.consumeNumber(10, null)
},
};
switch (value) {
IntOrFloat.Int => |i| {
(??t.c_token).data = TokenData.Integer { i };
%return t.setEndToken(TokenId.IntLiteral);
},
IntOrFloat.Float => |f| {
(??t.c_token).data = TokenData.Float { f };
%return t.setEndToken(TokenId.FloatLiteral);
},
}
},
'1' ... '9' => {
const value = %return t.consumeNumber(10, ch);
switch (value) {
IntOrFloat.Int => |i| {
(??t.c_token).data = TokenData.Integer { i };
%return t.setEndToken(TokenId.IntLiteral);
},
IntOrFloat.Float => |f| {
(??t.c_token).data = TokenData.Float { f };
%return t.setEndToken(TokenId.FloatLiteral);
},
}
},
'"' => {
var literal = %return t.consumeString();
%return t.setInternToken(&literal);
%return t.setEndToken(TokenId.StringLiteral);
},
'-' => {
switch (t.peek(0)) {
'>' => {
t.bump(1);
%return t.setEndToken(TokenId.Arrow);
},
'=' => {
t.bump(1);
%return t.setEndToken(TokenId.MinusEq);
},
'%' => {
t.bump(1);
switch (t.peek(0)) {
'=' => {
t.bump(1);
%return t.setEndToken(TokenId.MinusPercentEq);
},
else => {
%return t.setEndToken(TokenId.MinusPercent);
},
}
},
else => {
%return t.setEndToken(TokenId.Dash);
}
}
},
'+' => {
switch (t.peek(0)) {
'=' => {
t.bump(1);
%return t.setEndToken(TokenId.PlusEq);
},
'+' => {
t.bump(1);
%return t.setEndToken(TokenId.PlusPlus);
},
'%' => {
t.bump(1);
switch (t.peek(0)) {
'=' => {
t.bump(1);
%return t.setEndToken(TokenId.PlusPercentEq);
},
else => {
%return t.setEndToken(TokenId.PlusPercent);
},
}
},
else => {
%return t.setEndToken(TokenId.Plus);
}
}
},
'*' => {
switch (t.peek(0)) {
'=' => {
t.bump(1);
%return t.setEndToken(TokenId.TimesEq);
},
'*' => {
t.bump(1);
%return t.setEndToken(TokenId.StarStar);
},
'%' => {
t.bump(1);
switch (t.peek(0)) {
'=' => {
t.bump(1);
%return t.setEndToken(TokenId.TimesPercentEq);
},
else => {
%return t.setEndToken(TokenId.TimesPercent);
}
}
},
else => {
%return t.setEndToken(TokenId.Star);
},
}
},
'/' => {
switch (t.peek(0)) {
'/' => {
t.bump(1);
switch (t.peek(0)) {
'!' => {
t.bump(1);
t.setToken(TokenId.ModuleDocComment);
},
'/' => {
t.bump(1);
t.setToken(TokenId.DocComment);
},
else => {
t.setToken(TokenId.Comment);
},
}
var comment_inner = %return t.consumeUntilNewline();
%return t.setInternToken(&comment_inner);
%return t.endToken();
},
'=' => {
t.bump(1);
%return t.setEndToken(TokenId.DivEq);
},
else => {
%return t.setEndToken(TokenId.Slash);
},
}
},
'%' => {
switch (t.peek(0)) {
'=' => {
t.bump(1);
%return t.setEndToken(TokenId.ModEq);
},
'.' => {
t.bump(1);
%return t.setEndToken(TokenId.PercentDot);
},
'%' => {
t.bump(1);
%return t.setEndToken(TokenId.PercentPercent);
},
else => {
%return t.setEndToken(TokenId.Percent);
},
}
},
'@' => {
switch (t.peek(0)) {
'"' => {
t.bump(1);
var literal = %return t.consumeString();
%return t.setInternToken(&literal);
%return t.setEndToken(TokenId.Symbol);
},
else => {
%return t.setEndToken(TokenId.AtSign);
},
}
},
'&' => {
switch (t.peek(0)) {
'=' => {
t.bump(1);
%return t.setEndToken(TokenId.BitAndEq);
},
else => {
%return t.setEndToken(TokenId.Ampersand);
}
}
},
'^' => {
switch (t.peek(0)) {
'=' => {
t.bump(1);
%return t.setEndToken(TokenId.BitXorEq);
},
else => {
%return t.setEndToken(TokenId.BinXor);
}
}
},
'|' => {
switch (t.peek(0)) {
'=' => {
t.bump(1);
%return t.setEndToken(TokenId.BitOrEq);
},
else => {
%return t.setEndToken(TokenId.BinOr);
}
}
},
'=' => {
switch (t.peek(0)) {
'=' => {
t.bump(1);
%return t.setEndToken(TokenId.CmpEq);
},
'>' => {
t.bump(1);
%return t.setEndToken(TokenId.FatArrow);
},
else => {
%return t.setEndToken(TokenId.Eq);
},
}
},
'!' => {
switch (t.peek(0)) {
'=' => {
t.bump(1);
%return t.setEndToken(TokenId.CmpNotEq);
},
else => {
%return t.setEndToken(TokenId.Bang);
},
}
},
'<' => {
switch (t.peek(0)) {
'=' => {
t.bump(1);
%return t.setEndToken(TokenId.CmpLessOrEq);
},
'<' => {
t.bump(1);
switch (t.peek(0)) {
'=' => {
t.bump(1);
%return t.setEndToken(TokenId.BitShiftLeftEq);
},
else => {
%return t.setEndToken(TokenId.BitShiftLeft);
},
}
},
else => {
%return t.setEndToken(TokenId.CmpLessThan);
},
}
},
'>' => {
switch (t.peek(0)) {
'=' => {
t.bump(1);
%return t.setEndToken(TokenId.CmpGreaterOrEq);
},
'>' => {
t.bump(1);
switch (t.peek(0)) {
'=' => {
t.bump(1);
%return t.setEndToken(TokenId.BitShiftRightEq);
},
else => {
%return t.setEndToken(TokenId.BitShiftRight);
},
}
},
else => {
%return t.setEndToken(TokenId.CmpGreaterThan);
},
}
},
'.' => {
switch (t.peek(0)) {
'.' => {
t.bump(1);
switch (t.peek(0)) {
'.' => {
t.bump(1);
%return t.setEndToken(TokenId.Ellipsis3)
},
else => {
%return t.setEndToken(TokenId.Ellipsis2);
},
}
},
else => {
%return t.setEndToken(TokenId.Dot);
},
}
},
'?' => {
switch (t.peek(0)) {
'?' => {
t.bump(1);
%return t.setEndToken(TokenId.DoubleQuestion);
},
'=' => {
t.bump(1);
%return t.setEndToken(TokenId.MaybeAssign);
},
else => {
%return t.setEndToken(TokenId.Maybe);
}
}
},
'\'' => {
switch (t.peek(0)) {
'\'' => {
return error.MissingCharLiteralData;
},
'\\' => {
t.bump(1);
var value = %return t.consumeStringEscape();
if (t.peek(0) != '\'') {
return error.ExtraCharLiteralData;
} else {
t.bump(1);
std.debug.assert(value.len == 1);
(??t.c_token).data = TokenData.Char { value.toSliceConst()[0] };
value.deinit();
%return t.setEndToken(TokenId.CharLiteral);
}
},
0 => {
return error.EofWhileParsingLiteral;
},
else => {
if (t.peek(1) != '\'') {
return error.ExtraCharLiteralData;
} else {
(??t.c_token).data = TokenData.Char { t.peek(0) };
t.bump(2);
%return t.setEndToken(TokenId.CharLiteral);
}
},
}
},
'\\' => {
switch (t.peek(0)) {
'\\' => {
t.bump(1);
var literal = %return t.consumeUntilNewline();
%return t.setInternToken(&literal);
%return t.setEndToken(TokenId.MultiLineStringLiteral);
},
else => {
return error.InvalidCharacterAfterBackslash;
},
}
},
else => {
return error.InvalidCharacter;
}
}
} else {
t.consumed = true;
%return t.setEndToken(TokenId.Eof);
}
&t.tokens.toSliceConst()[t.tokens.len - 1]
}
/// Construct a new tokenization instance and return it in its completed state.
///
// NOTE: If we want to return a stream of tokens, tie this to an underlying tokenization state
// which handles the intern pool.
//
// NOTE: The tokenizer will continue through errors until the complete buffer has been processed.
// The list of errors encountered will be stored in the `errors` field.
pub fn process(self: &Self, buf: []const u8) -> %void {
self.c_buf = buf;
// This iterates over the entire buffer. Tokens are returned as references but are still
// stored in the `tokens` field.
while (true) {
if (self.next()) |ch| {
if (ch == null) {
break;
}
} else |err| switch (err) {
else => return err,
}
}
}
}; | src/tokenizer.zig |
const std = @import("std");
const assert = std.debug.assert;
const c = @cImport({
@cInclude("SDL2/SDL.h");
});
const chip8 = @import("../chip8/chip8.zig");
fn fill_image_buffer(imageOutput: []u8, state: *chip8.CPUState, palette: chip8.Palette, scale: u32) void {
const pixelFormatBGRASizeInBytes: u32 = 4;
const primaryColorBGRA = [4]u8{
@floatToInt(u8, palette.primary.b * 255.0),
@floatToInt(u8, palette.primary.g * 255.0),
@floatToInt(u8, palette.primary.r * 255.0),
255,
};
const secondaryColorBGRA = [4]u8{
@floatToInt(u8, palette.secondary.b * 255.0),
@floatToInt(u8, palette.secondary.g * 255.0),
@floatToInt(u8, palette.secondary.r * 255.0),
255,
};
var j: u32 = 0;
while (j < chip8.ScreenHeight * scale) {
var i: u32 = 0;
while (i < chip8.ScreenWidth * scale) {
const pixelIndexFlatDst = j * chip8.ScreenWidth * scale + i;
const pixelOutputOffsetInBytes = pixelIndexFlatDst * pixelFormatBGRASizeInBytes;
const pixelValue = chip8.read_screen_pixel(state, i / scale, j / scale);
if (pixelValue > 0) {
imageOutput[pixelOutputOffsetInBytes + 0] = primaryColorBGRA[0];
imageOutput[pixelOutputOffsetInBytes + 1] = primaryColorBGRA[1];
imageOutput[pixelOutputOffsetInBytes + 2] = primaryColorBGRA[2];
imageOutput[pixelOutputOffsetInBytes + 3] = primaryColorBGRA[3];
} else {
imageOutput[pixelOutputOffsetInBytes + 0] = secondaryColorBGRA[0];
imageOutput[pixelOutputOffsetInBytes + 1] = secondaryColorBGRA[1];
imageOutput[pixelOutputOffsetInBytes + 2] = secondaryColorBGRA[2];
imageOutput[pixelOutputOffsetInBytes + 3] = secondaryColorBGRA[3];
}
i += 1;
}
j += 1;
}
}
pub fn execute_main_loop(state: *chip8.CPUState, config: chip8.EmuConfig) !void {
const pixelFormatBGRASizeInBytes: u32 = 4;
const scale = config.screenScale;
const width = chip8.ScreenWidth * scale;
const height = chip8.ScreenHeight * scale;
const stride = width * pixelFormatBGRASizeInBytes; // No extra space between lines
const size = stride * height;
const allocator: *std.mem.Allocator = std.heap.page_allocator;
var image = try allocator.alloc(u8, size);
errdefer allocator.free(state.memory);
if (c.SDL_Init(c.SDL_INIT_EVERYTHING) != 0) {
c.SDL_Log("Unable to initialize SDL: %s", c.SDL_GetError());
return error.SDLInitializationFailed;
}
defer c.SDL_Quit();
const window = c.SDL_CreateWindow("CHIP-8 Emulator", c.SDL_WINDOWPOS_UNDEFINED, c.SDL_WINDOWPOS_UNDEFINED, @intCast(c_int, width), @intCast(c_int, height), c.SDL_WINDOW_SHOWN) orelse {
c.SDL_Log("Unable to create window: %s", c.SDL_GetError());
return error.SDLInitializationFailed;
};
defer c.SDL_DestroyWindow(window);
const ren = c.SDL_CreateRenderer(window, -1, c.SDL_RENDERER_ACCELERATED) orelse {
c.SDL_Log("Unable to create renderer: %s", c.SDL_GetError());
return error.SDLInitializationFailed;
};
defer c.SDL_DestroyRenderer(ren);
var rmask: u32 = undefined;
var gmask: u32 = undefined;
var bmask: u32 = undefined;
var amask: u32 = undefined;
if (c.SDL_BYTEORDER == c.SDL_BIG_ENDIAN) {
rmask = 0xff000000;
gmask = 0x00ff0000;
bmask = 0x0000ff00;
amask = 0x000000ff;
} else // little endian, like x86
{
rmask = 0x000000ff;
gmask = 0x0000ff00;
bmask = 0x00ff0000;
amask = 0xff000000;
}
var depth: u32 = 32;
var pitch: u32 = stride;
const surf = c.SDL_CreateRGBSurfaceFrom(@ptrCast(*c_void, &image[0]), @intCast(c_int, width), @intCast(c_int, height), @intCast(c_int, depth), @intCast(c_int, pitch), rmask, gmask, bmask, amask) orelse {
c.SDL_Log("Unable to create surface: %s", c.SDL_GetError());
return error.SDLInitializationFailed;
};
defer c.SDL_FreeSurface(surf);
var previousTimeMs: u32 = c.SDL_GetTicks();
var shouldExit = false;
while (!shouldExit) {
// Poll events
var sdlEvent: c.SDL_Event = undefined;
while (c.SDL_PollEvent(&sdlEvent) > 0) {
switch (sdlEvent.type) {
c.SDL_QUIT => {
shouldExit = true;
},
c.SDL_KEYDOWN => {
if (sdlEvent.key.keysym.sym == c.SDLK_ESCAPE)
shouldExit = true;
},
else => {},
}
}
// Get keyboard state
const sdlKeyStates: [*]const u8 = c.SDL_GetKeyboardState(null);
chip8.set_key_pressed(state, 0x1, sdlKeyStates[c.SDL_SCANCODE_1] > 0);
chip8.set_key_pressed(state, 0x2, sdlKeyStates[c.SDL_SCANCODE_2] > 0);
chip8.set_key_pressed(state, 0x3, sdlKeyStates[c.SDL_SCANCODE_3] > 0);
chip8.set_key_pressed(state, 0xC, sdlKeyStates[c.SDL_SCANCODE_4] > 0);
chip8.set_key_pressed(state, 0x4, sdlKeyStates[c.SDL_SCANCODE_Q] > 0);
chip8.set_key_pressed(state, 0x5, sdlKeyStates[c.SDL_SCANCODE_W] > 0);
chip8.set_key_pressed(state, 0x6, sdlKeyStates[c.SDL_SCANCODE_E] > 0);
chip8.set_key_pressed(state, 0xD, sdlKeyStates[c.SDL_SCANCODE_R] > 0);
chip8.set_key_pressed(state, 0x7, sdlKeyStates[c.SDL_SCANCODE_A] > 0);
chip8.set_key_pressed(state, 0x8, sdlKeyStates[c.SDL_SCANCODE_S] > 0);
chip8.set_key_pressed(state, 0x9, sdlKeyStates[c.SDL_SCANCODE_D] > 0);
chip8.set_key_pressed(state, 0xE, sdlKeyStates[c.SDL_SCANCODE_F] > 0);
chip8.set_key_pressed(state, 0xA, sdlKeyStates[c.SDL_SCANCODE_Z] > 0);
chip8.set_key_pressed(state, 0x0, sdlKeyStates[c.SDL_SCANCODE_X] > 0);
chip8.set_key_pressed(state, 0xB, sdlKeyStates[c.SDL_SCANCODE_C] > 0);
chip8.set_key_pressed(state, 0xF, sdlKeyStates[c.SDL_SCANCODE_V] > 0);
const currentTimeMs: u32 = c.SDL_GetTicks();
const deltaTimeMs: u32 = currentTimeMs - previousTimeMs;
chip8.execute_step(state, deltaTimeMs);
fill_image_buffer(image, state, config.palette, scale);
// Draw
const tex = c.SDL_CreateTextureFromSurface(ren, surf) orelse {
c.SDL_Log("Unable to create texture from surface: %s", c.SDL_GetError());
return error.SDLInitializationFailed;
};
defer c.SDL_DestroyTexture(tex);
_ = c.SDL_RenderClear(ren);
_ = c.SDL_RenderCopy(ren, tex, null, null);
// Present
c.SDL_RenderPresent(ren);
previousTimeMs = currentTimeMs;
}
} | src/sdl2/sdl2_backend.zig |
const std = @import("std");
const Arch = if (@hasField(std.builtin, "Arch")) std.builtin.Arch else std.Target.Cpu.Arch;
pub const Context = enum {
kernel,
userlib,
userspace,
};
pub const TransformFileCommandStep = struct {
step: std.build.Step,
output_path: []const u8,
fn run_command(s: *std.build.Step) !void {}
};
fn make_transform(b: *std.build.Builder, dep: *std.build.Step, command: [][]const u8, output_path: []const u8) !*TransformFileCommandStep {
const transform = try b.allocator.create(TransformFileCommandStep);
transform.output_path = output_path;
transform.step = std.build.Step.init(.custom, "", b.allocator, TransformFileCommandStep.run_command);
const command_step = b.addSystemCommand(command);
command_step.step.dependOn(dep);
transform.step.dependOn(&command_step.step);
return transform;
}
pub fn binaryBlobSection(b: *std.build.Builder, elf: *std.build.LibExeObjStep, section_name: []const u8) !*TransformFileCommandStep {
const elf_path = b.getInstallPath(elf.install_step.?.dest_dir, elf.out_filename);
const dumped_path = b.fmt("{s}.bin", .{elf_path});
const dump_step = try make_transform(
b,
&elf.install_step.?.step,
// zig fmt: off
&[_][]const u8{
"llvm-objcopy",
"-O", "binary",
"--only-section", section_name,
elf_path, dumped_path,
},
// zig fmt: on
dumped_path,
);
return dump_step;
}
fn makeSourceBlobStep(
b: *std.build.Builder,
output: []const u8,
src: []const u8,
) *std.build.RunStep {
return b.addSystemCommand(
&[_][]const u8{
"tar", "--no-xattrs", "-cf", output, "lib", src, "build.zig",
},
);
}
pub fn setTargetFlags(
exec: *std.build.LibExeObjStep,
arch: Arch,
context: Context,
) void {
var disabled_features = std.Target.Cpu.Feature.Set.empty;
var enabled_feautres = std.Target.Cpu.Feature.Set.empty;
switch (arch) {
.x86_64 => {
const features = std.Target.x86.Feature;
if (context == .kernel) {
// Disable SIMD registers
disabled_features.addFeature(@enumToInt(features.mmx));
disabled_features.addFeature(@enumToInt(features.sse));
disabled_features.addFeature(@enumToInt(features.sse2));
disabled_features.addFeature(@enumToInt(features.avx));
disabled_features.addFeature(@enumToInt(features.avx2));
enabled_feautres.addFeature(@enumToInt(features.soft_float));
exec.code_model = .kernel;
} else {
exec.code_model = .small;
}
},
.aarch64 => {
const features = std.Target.aarch64.Feature;
if (context == .kernel) {
// This is equal to -mgeneral-regs-only
disabled_features.addFeature(@enumToInt(features.fp_armv8));
disabled_features.addFeature(@enumToInt(features.crypto));
disabled_features.addFeature(@enumToInt(features.neon));
}
exec.code_model = .small;
},
.riscv64 => {
// idfk
exec.code_model = .small;
},
else => unreachable,
}
exec.disable_stack_probing = switch (context) {
.kernel => true,
.userlib => true,
else => false,
};
exec.setTarget(.{
.cpu_arch = arch,
.os_tag = std.Target.Os.Tag.freestanding,
.abi = std.Target.Abi.none,
.cpu_features_sub = disabled_features,
.cpu_features_add = enabled_feautres,
});
}
pub fn makeExec(params: struct {
builder: *std.build.Builder,
arch: Arch,
ctx: Context,
filename: []const u8,
main: []const u8,
source_blob: ?struct {
global_source_path: []const u8,
source_blob_name: []const u8,
},
mode: ?std.builtin.Mode = null,
strip_symbols: bool = false,
}) *std.build.LibExeObjStep {
const mode = params.mode orelse params.builder.standardReleaseOptions();
const exec = params.builder.addExecutable(params.filename, params.main);
setTargetFlags(exec, params.arch, params.ctx);
exec.setBuildMode(mode);
exec.strip = params.strip_symbols;
if (@hasField(@TypeOf(exec.*), "want_lto"))
exec.want_lto = false;
exec.setMainPkgPath(".");
exec.setOutputDir(params.builder.cache_root);
if (params.source_blob) |blob| {
const cache_root = params.builder.cache_root;
const source_blob_path = params.builder.fmt("{s}/{s}.tar", .{
cache_root,
blob.source_blob_name,
});
exec.addBuildOption(?[]const u8, "source_blob_path", source_blob_path);
exec.step.dependOn(&makeSourceBlobStep(
params.builder,
source_blob_path,
blob.global_source_path,
).step);
} else {
exec.addBuildOption(?[]const u8, "source_blob_path", null);
}
exec.install();
return exec;
} | buildutil/exec.zig |
const std = @import("std");
const builtin = @import("builtin");
const vfs = @import("../vfs.zig");
const uefi = std.os.uefi;
const time = std.time;
const earlyprintf = @import("../platform.zig").earlyprintf;
pub const klibc = @import("../klibc.zig");
pub const debugMalloc = false;
const console = @import("uefi/console.zig");
var exitedBootServices = false;
const Error = error{UefiError};
const timer_interval = 10000000; // Given in nanoseconds
var timer_event: uefi.Event = undefined;
var timer_call: ?fn () void = null;
var in_timer: bool = false;
var timer_ticks: usize = 0;
pub fn timerCallThunk(event: uefi.Event, context: ?*const c_void) callconv(.C) void {
if (@atomicRmw(bool, &in_timer, .Xchg, true, .SeqCst)) return;
if (timer_ticks > 0) _ = @atomicRmw(usize, &timer_ticks, .Sub, 1, .SeqCst);
console.keyboardHandler();
if (timer_call) |func| {
func();
}
_ = @atomicRmw(bool, &in_timer, .Xchg, false, .SeqCst);
}
pub fn init() void {
klibc.notifyInitialization();
const con_out = uefi.system_table.con_out.?;
const con_in = uefi.system_table.con_in.?;
_ = uefi.system_table.boot_services.?.setWatchdogTimer(0, 0, 0, null);
_ = con_out.reset(false);
_ = con_in._reset(con_in, false);
_ = uefi.system_table.boot_services.?.createEvent(uefi.tables.BootServices.event_timer | uefi.tables.BootServices.event_notify_signal, uefi.tables.BootServices.tpl_notify, timerCallThunk, null, &timer_event);
_ = uefi.system_table.boot_services.?.setTimer(timer_event, uefi.tables.TimerDelay.TimerPeriodic, timer_interval / 100); // UEFI spec: has to be in increments of 100ns
console.init();
}
pub fn malloc(size: usize) ?[*]u8 {
if (debugMalloc) earlyprintf("Allocating {} bytes\r\n", .{size});
var buf: [*]align(8) u8 = undefined;
var status = uefi.system_table.boot_services.?.allocatePool(uefi.tables.MemoryType.BootServicesData, size + 8, &buf);
if (status != .Success) return null;
var origSizePtr = @ptrCast([*]align(8) u64, buf);
origSizePtr[0] = @intCast(u64, size);
return @intToPtr([*]u8, @ptrToInt(buf) + 8);
}
pub fn realloc(ptr: ?[*]align(8) u8, newsize: usize) ?[*]u8 {
if (ptr == null) return malloc(newsize);
if (debugMalloc) earlyprintf("Reallocating {} bytes\r\n", .{newsize});
var truePtr = @intToPtr([*]align(8) u8, @ptrToInt(ptr.?) - 8);
var origSizePtr = @ptrCast([*]align(8) u64, truePtr);
if (origSizePtr[0] == @intCast(u64, newsize + 8)) return ptr;
defer free(ptr);
var newPtr = malloc(newsize);
if (newPtr == null) return null;
if (debugMalloc) earlyprintf("Original size: {}\r\n", .{origSizePtr[0]});
@memcpy(newPtr.?, ptr.?, @intCast(usize, origSizePtr[0]));
return newPtr;
}
pub fn free(ptr: ?[*]align(8) u8) void {
if (ptr == null) return;
if (debugMalloc) earlyprintf("Freeing {} ptr\r\n", .{ptr});
var status = uefi.system_table.boot_services.?.freePool(@intToPtr([*]align(8) u8, @ptrToInt(ptr.?) - 8));
if (status != .Success) @panic("free() failed (this shouldn't be possible)");
}
pub fn earlyprintk(str: []const u8) void {
const con_out = uefi.system_table.con_out.?;
for (str) |c| {
if (c == '\n') _ = con_out.outputString(&[_:0]u16{ '\r', 0 });
_ = con_out.outputString(&[_:0]u16{ c, 0 });
}
}
pub fn openConsole() vfs.Node {
return console.ConsoleNode.init();
}
pub fn beforeYield() void {
_ = @atomicRmw(bool, &in_timer, .Xchg, false, .SeqCst);
uefi.system_table.boot_services.?.restoreTpl(uefi.tables.BootServices.tpl_application);
}
pub fn setTimer(cb: @TypeOf(timer_call)) void {
timer_call = cb;
}
pub fn waitTimer(ticks: usize) void {
_ = @atomicRmw(usize, &timer_ticks, .Xchg, ticks, .SeqCst);
// TODO: non-x86
while (timer_ticks > 0) asm volatile ("hlt");
}
pub fn getTimerInterval() i64 {
return timer_interval;
}
pub fn getTimeNano() i64 {
var raw = getTimeNative() catch unreachable;
return uefiToUnixTimeNano(raw);
}
pub fn getTime() i64 {
return @divFloor(getTimeNano(), time.ns_per_s);
}
pub fn getTimeNative() !uefi.Time {
var ret: uefi.Time = undefined;
var status = uefi.system_table.runtime_services.getTime(&ret, null);
if (status != .Success) return Error.UefiError;
return ret;
}
pub fn uefiToUnixTimeNano(raw: uefi.Time) i64 {
const days_in_month = [_]u8{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
var tzOffset = if (raw.timezone != uefi.Time.unspecified_timezone) raw.timezone else 0;
var isLeapYear = false;
if (raw.year % 4 == 0 and (raw.year % 100 != 0 or raw.year % 400 == 0))
isLeapYear = true;
var year = raw.year - 1900;
var yday = raw.day - 1;
for (days_in_month[0..(raw.month - 1)]) |v, i| {
if (i == 1 and isLeapYear) {
yday += 29;
} else {
yday += v;
}
}
var ret: i64 = time.epoch.unix * time.ns_per_s;
ret += @as(i64, raw.nanosecond);
ret += @as(i64, raw.second) * time.ns_per_s;
ret += (@as(i64, raw.minute) - @as(i64, tzOffset)) * time.ns_per_min;
ret += @as(i64, raw.hour) * time.ns_per_hour;
ret += @as(i64, yday) * time.ns_per_day;
ret += @as(i64, year - 70) * 365 * time.ns_per_day;
// Weird stuff. Leap years were a bad idea.
ret += @as(i64, @divFloor(year - 69, 4)) * time.ns_per_day;
ret -= @as(i64, @divFloor(year - 1, 100)) * time.ns_per_day;
ret += @as(i64, @divFloor(year + 299, 400)) * time.ns_per_day;
return ret;
}
pub fn late() void {
// nothing
}
pub fn halt() noreturn {
if (!exitedBootServices) while (true) {
_ = uefi.system_table.boot_services.?.stall(0x7FFFFFFF);
};
while (true) {}
} | kernel/platform/uefi.zig |
const std = @import("std");
const config = @import("config.zig");
const tracer = @import("tracer.zig");
pub const WorkItem = struct {
tracer: *tracer.Tracer,
buffer: *[]u8,
offset: usize,
chunk_size: usize,
};
pub const WorkerThread = struct {
done: std.atomic.Atomic(bool) = std.atomic.Atomic(bool).init(false),
done_count: *std.atomic.Atomic(u32),
job_count: std.atomic.Atomic(u32) = std.atomic.Atomic(u32).init(0),
cur_job_count: u32 = 0,
queue: *std.atomic.Queue(WorkItem),
pub fn wake(self: *@This()) void {
_ = self.job_count.fetchAdd(1, .Release);
std.Thread.Futex.wake(&self.job_count, 1);
}
pub fn pushJobAndWake(self: *@This(), node: *std.atomic.Queue(WorkItem).Node) void {
self.queue.put(node);
self.wake();
}
pub fn waitForJob(self: *@This()) !void {
var global_job_count: u32 = undefined;
while (true) {
global_job_count = self.job_count.load(.Acquire);
if (global_job_count != self.cur_job_count) {
break;
}
std.Thread.Futex.wait(&self.job_count, self.cur_job_count, null) catch unreachable;
}
}
};
pub fn joinThread(thread: std.Thread, data: *WorkerThread) void {
data.done.store(true, .Release);
data.wake();
thread.join();
}
pub fn launchWorkerThread(worker_data: *WorkerThread) !void {
var work_item: WorkItem = undefined;
while (!worker_data.done.load(.Acquire)) {
if (!worker_data.queue.isEmpty()) {
work_item = worker_data.queue.get().?.data;
try tracer.tracePaths(work_item.tracer.*, work_item.buffer.*, work_item.offset, work_item.chunk_size);
_ = worker_data.done_count.fetchAdd(1, .Release);
std.Thread.Futex.wake(worker_data.done_count, 1);
} else {
try worker_data.waitForJob();
}
}
}
pub fn waitUntilDone(done_count: *std.atomic.Atomic(u32), target_count: u32) !void {
var cur_done_count: u32 = undefined;
while (config.IS_MULTI_THREADED) {
cur_done_count = done_count.load(.Acquire);
if (cur_done_count == target_count) {
break;
}
std.Thread.Futex.wait(done_count, cur_done_count, null) catch unreachable;
}
} | src/worker.zig |
const std = @import("std");
// options is a json.Options, but since we're using our hacked json.zig we don't want to
// specifically call this out
pub fn serializeMap(map: anytype, key: []const u8, options: anytype, out_stream: anytype) !bool {
if (map.len == 0) return true;
// TODO: Map might be [][]struct{key, value} rather than []struct{key, value}
var child_options = options;
if (child_options.whitespace) |*child_ws|
child_ws.indent_level += 1;
try out_stream.writeByte('"');
try out_stream.writeAll(key);
_ = try out_stream.write("\":");
if (options.whitespace) |ws| {
if (ws.separator) {
try out_stream.writeByte(' ');
}
}
try out_stream.writeByte('{');
if (options.whitespace) |_|
try out_stream.writeByte('\n');
for (map) |tag, i| {
if (tag.key == null or tag.value == null) continue;
// TODO: Deal with escaping and general "json.stringify" the values...
if (child_options.whitespace) |ws|
try ws.outputIndent(out_stream);
try out_stream.writeByte('"');
try jsonEscape(tag.key.?, child_options, out_stream);
_ = try out_stream.write("\":");
if (child_options.whitespace) |ws| {
if (ws.separator) {
try out_stream.writeByte(' ');
}
}
try out_stream.writeByte('"');
try jsonEscape(tag.value.?, child_options, out_stream);
try out_stream.writeByte('"');
if (i < map.len - 1) {
try out_stream.writeByte(',');
}
if (child_options.whitespace) |_|
try out_stream.writeByte('\n');
}
if (options.whitespace) |ws|
try ws.outputIndent(out_stream);
try out_stream.writeByte('}');
return true;
}
// code within jsonEscape lifted from json.zig in stdlib
fn jsonEscape(value: []const u8, options: anytype, out_stream: anytype) !void {
var i: usize = 0;
while (i < value.len) : (i += 1) {
switch (value[i]) {
// normal ascii character
0x20...0x21, 0x23...0x2E, 0x30...0x5B, 0x5D...0x7F => |c| try out_stream.writeByte(c),
// only 2 characters that *must* be escaped
'\\' => try out_stream.writeAll("\\\\"),
'\"' => try out_stream.writeAll("\\\""),
// solidus is optional to escape
'/' => {
if (options.string.String.escape_solidus) {
try out_stream.writeAll("\\/");
} else {
try out_stream.writeByte('/');
}
},
// control characters with short escapes
// TODO: option to switch between unicode and 'short' forms?
0x8 => try out_stream.writeAll("\\b"),
0xC => try out_stream.writeAll("\\f"),
'\n' => try out_stream.writeAll("\\n"),
'\r' => try out_stream.writeAll("\\r"),
'\t' => try out_stream.writeAll("\\t"),
else => {
const ulen = std.unicode.utf8ByteSequenceLength(value[i]) catch unreachable;
// control characters (only things left with 1 byte length) should always be printed as unicode escapes
if (ulen == 1 or options.string.String.escape_unicode) {
const codepoint = std.unicode.utf8Decode(value[i .. i + ulen]) catch unreachable;
try outputUnicodeEscape(codepoint, out_stream);
} else {
try out_stream.writeAll(value[i .. i + ulen]);
}
i += ulen - 1;
},
}
}
}
// outputUnicodeEscape and assert lifted from json.zig in stdlib
fn outputUnicodeEscape(
codepoint: u21,
out_stream: anytype,
) !void {
if (codepoint <= 0xFFFF) {
// If the character is in the Basic Multilingual Plane (U+0000 through U+FFFF),
// then it may be represented as a six-character sequence: a reverse solidus, followed
// by the lowercase letter u, followed by four hexadecimal digits that encode the character's code point.
try out_stream.writeAll("\\u");
try std.fmt.formatIntValue(codepoint, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream);
} else {
assert(codepoint <= 0x10FFFF);
// To escape an extended character that is not in the Basic Multilingual Plane,
// the character is represented as a 12-character sequence, encoding the UTF-16 surrogate pair.
const high = @intCast(u16, (codepoint - 0x10000) >> 10) + 0xD800;
const low = @intCast(u16, codepoint & 0x3FF) + 0xDC00;
try out_stream.writeAll("\\u");
try std.fmt.formatIntValue(high, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream);
try out_stream.writeAll("\\u");
try std.fmt.formatIntValue(low, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream);
}
}
/// This function invokes undefined behavior when `ok` is `false`.
/// In Debug and ReleaseSafe modes, calls to this function are always
/// generated, and the `unreachable` statement triggers a panic.
/// In ReleaseFast and ReleaseSmall modes, calls to this function are
/// optimized away, and in fact the optimizer is able to use the assertion
/// in its heuristics.
/// Inside a test block, it is best to use the `std.testing` module rather
/// than this function, because this function may not detect a test failure
/// in ReleaseFast and ReleaseSmall mode. Outside of a test block, this assert
/// function is the correct function to use.
pub fn assert(ok: bool) void {
if (!ok) unreachable; // assertion failure
} | codegen/src/json.zig |
const std = @import("std");
const real_input = @embedFile("day-14_real-input");
const test_input = @embedFile("day-14_test-input");
pub fn main() !void {
std.debug.print("--- Day 14 ---\n", .{});
const result = try execute(real_input, 40);
std.debug.print("most common - least common = {}\n", .{ result });
}
test "test-input 40" {
std.debug.print("\n", .{});
const expected: u64 = 2188189693529;
const result = try execute(test_input, 40);
try std.testing.expectEqual(expected, result);
}
test "test-input 10" {
std.debug.print("\n", .{});
const expected: u64 = 1588;
const result = try execute(test_input, 10);
try std.testing.expectEqual(expected, result);
}
fn execute(input: []const u8, iterations: u32) !u64 {
var buffer: [1024 * 1024]u8 = undefined;
var alloc = std.heap.FixedBufferAllocator.init(buffer[0..]);
var line_it = std.mem.tokenize(u8, input, "\r\n");
const template = line_it.next() orelse unreachable;
var rules = std.AutoHashMap(u32, Rule).init(alloc.allocator());
var elements = std.AutoHashMap(u8, u64).init(alloc.allocator());
while (line_it.next()) |line| {
if (line.len == 0) continue;
var rule_it = std.mem.tokenize(u8, line, " ->");
const pair_string = rule_it.next() orelse unreachable;
const insert = rule_it.next() orelse unreachable;
const pair = Pair { .lhs = pair_string[0], .rhs = pair_string[1], };
const lhs_pair = Pair { .lhs = pair.lhs, .rhs = insert[0] };
const rhs_pair = Pair { .lhs = insert[0], .rhs = pair.rhs };
try rules.put(pair.hash(), .{
.lhs_pair_hash = lhs_pair.hash(),
.rhs_pair_hash = rhs_pair.hash(),
.insert_char = insert[0],
});
try elements.put(pair.lhs, 0);
try elements.put(pair.rhs, 0);
}
var pairs = std.AutoHashMap(u32, u64).init(alloc.allocator());
for (template) |char, i| {
var count = elements.getPtr(char) orelse unreachable;
count.* += 1;
if (i < template.len - 1) {
const pair = Pair {
.lhs = template[i],
.rhs = template[i + 1],
};
var pair_count = try pairs.getOrPut(pair.hash());
if (pair_count.found_existing) {
pair_count.value_ptr.* += 1;
}
else {
pair_count.value_ptr.* = 1;
}
}
}
var iteration: u32 = 1;
while (iteration <= iterations):(iteration += 1) {
var new_pairs = std.AutoHashMap(u32, u64).init(alloc.allocator());
defer new_pairs.deinit();
var pair_it = pairs.iterator();
while (pair_it.next()) |pair| {
const rule = rules.get(pair.key_ptr.*) orelse unreachable;
var count = elements.getPtr(rule.insert_char) orelse unreachable;
count.* += pair.value_ptr.*;
var lhs_pair_count = try new_pairs.getOrPut(rule.lhs_pair_hash);
if (lhs_pair_count.found_existing) {
lhs_pair_count.value_ptr.* += pair.value_ptr.*;
}
else {
lhs_pair_count.value_ptr.* = pair.value_ptr.*;
}
var rhs_pair_count = try new_pairs.getOrPut(rule.rhs_pair_hash);
if (rhs_pair_count.found_existing) {
rhs_pair_count.value_ptr.* += pair.value_ptr.*;
}
else {
rhs_pair_count.value_ptr.* = pair.value_ptr.*;
}
}
pairs.clearRetainingCapacity();
var new_pair_it = new_pairs.iterator();
while (new_pair_it.next()) |pair| {
try pairs.put(pair.key_ptr.*, pair.value_ptr.*);
}
}
var least_common: u64 = std.math.maxInt(u64);
var most_common: u64 = 0;
var elements_it = elements.iterator();
while(elements_it.next()) |element| {
const char = element.key_ptr.*;
const count = element.value_ptr.*;
std.debug.print("{c} occurs {} times\n", .{ char, count });
if (count < least_common) least_common = count;
if (count > most_common) most_common = count;
}
return most_common - least_common;
}
const Rule = struct {
insert_char: u8,
lhs_pair_hash: u32,
rhs_pair_hash: u32,
};
const Pair = struct {
lhs: u8,
rhs: u8,
pub fn equals(lhs: Pair, rhs: Pair) bool {
return lhs.lhs == rhs.lhs and lhs.rhs == rhs.rhs;
}
pub fn hash(self: Pair) u32 {
return @intCast(u32, self.lhs) + @intCast(u32, self.rhs) * 100;
}
}; | day-14.zig |
const std = @import("std");
const deps = @import("deps.zig");
pub fn build(b: *std.build.Builder) void {
const target = b.standardTargetOptions(.{});
const mode = b.standardReleaseOptions();
const exe = b.addExecutable("wala", "src/main.zig");
const exe_tests = b.addTest("src/main.zig");
const exe_cases = b.addExecutable("cases", "test/cases.zig");
for (&[_]*std.build.LibExeObjStep{ exe, exe_tests }) |e| {
e.setTarget(target);
e.setBuildMode(mode);
e.single_threaded = true;
deps.addAllTo(e);
}
exe.install();
const fmt = b.addFmt(&[_][]const u8{ "src", "test", "build.zig" });
const fmt_step = b.step("fmt", "Format all code");
fmt_step.dependOn(&fmt.step);
const run_cmd = exe.run();
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 coverage = b.option(bool, "coverage", "Generate coverage with kcov") orelse false;
const kcov_args = &[_][]const u8{ "kcov", "--include-path=src", "--path-strip-level=1", b.getInstallPath(.prefix, "coverage") };
if (coverage) {
b.makePath(kcov_args[kcov_args.len - 1]) catch unreachable;
var args: [kcov_args.len + 1]?[]const u8 = undefined;
for (kcov_args) |arg, i| args[i] = arg;
// to get zig to use the --test-cmd-bin flag
args[kcov_args.len] = null;
exe_tests.setExecCmd(&args);
}
const unit_test_step = b.step("unit-test", "Run unit tests");
unit_test_step.dependOn(&exe_tests.step);
const cases_run = exe_cases.run();
if (coverage) cases_run.addArgs(kcov_args);
cases_run.addArg(b.getInstallPath(.bin, exe.name));
cases_run.step.dependOn(&exe.install_step.?.step);
const cases_step = b.step("cases-test", "Run behavioral tests");
cases_step.dependOn(&cases_run.step);
const test_step = b.step("test", "Run all tests");
test_step.dependOn(unit_test_step);
test_step.dependOn(cases_step);
} | build.zig |
const std = @import("std");
const mem = std.mem;
const fs = std.fs;
const CacheHash = std.cache_hash.CacheHash;
/// Caller must free result
pub fn testZigInstallPrefix(allocator: *mem.Allocator, test_path: []const u8) ![]u8 {
{
const test_zig_dir = try fs.path.join(allocator, &[_][]const u8{ test_path, "lib", "zig" });
errdefer allocator.free(test_zig_dir);
const test_index_file = try fs.path.join(allocator, &[_][]const u8{ test_zig_dir, "std", "std.zig" });
defer allocator.free(test_index_file);
if (fs.cwd().openFile(test_index_file, .{})) |file| {
file.close();
return test_zig_dir;
} else |err| switch (err) {
error.FileNotFound => {
allocator.free(test_zig_dir);
},
else => |e| return e,
}
}
// Also try without "zig"
const test_zig_dir = try fs.path.join(allocator, &[_][]const u8{ test_path, "lib" });
errdefer allocator.free(test_zig_dir);
const test_index_file = try fs.path.join(allocator, &[_][]const u8{ test_zig_dir, "std", "std.zig" });
defer allocator.free(test_index_file);
const file = try fs.cwd().openFile(test_index_file, .{});
file.close();
return test_zig_dir;
}
/// Caller must free result
pub fn findZigLibDir(allocator: *mem.Allocator) ![]u8 {
const self_exe_path = try fs.selfExePathAlloc(allocator);
defer allocator.free(self_exe_path);
var cur_path: []const u8 = self_exe_path;
while (true) {
const test_dir = fs.path.dirname(cur_path) orelse ".";
if (mem.eql(u8, test_dir, cur_path)) {
break;
}
return testZigInstallPrefix(allocator, test_dir) catch |err| {
cur_path = test_dir;
continue;
};
}
return error.FileNotFound;
}
pub fn resolveZigLibDir(allocator: *mem.Allocator) ![]u8 {
return findZigLibDir(allocator) catch |err| {
std.debug.print(
\\Unable to find zig lib directory: {}.
\\Reinstall Zig or use --zig-install-prefix.
\\
, .{@errorName(err)});
return error.ZigLibDirNotFound;
};
}
/// Caller owns returned memory.
pub fn resolveGlobalCacheDir(allocator: *mem.Allocator) ![]u8 {
const appname = "zig";
if (std.Target.current.os.tag != .windows) {
if (std.os.getenv("XDG_CACHE_HOME")) |cache_root| {
return fs.path.join(allocator, &[_][]const u8{ cache_root, appname });
} else if (std.os.getenv("HOME")) |home| {
return fs.path.join(allocator, &[_][]const u8{ home, ".cache", appname });
}
}
return fs.getAppDataDir(allocator, appname);
}
var compiler_id_mutex = std.Mutex{};
var compiler_id: [16]u8 = undefined;
var compiler_id_computed = false;
pub fn resolveCompilerId(gpa: *mem.Allocator) ![16]u8 {
const held = compiler_id_mutex.acquire();
defer held.release();
if (compiler_id_computed)
return compiler_id;
compiler_id_computed = true;
const global_cache_dir = try resolveGlobalCacheDir(gpa);
defer gpa.free(global_cache_dir);
// TODO Introduce openGlobalCacheDir which returns a dir handle rather than a string.
var cache_dir = try fs.cwd().openDir(global_cache_dir, .{});
defer cache_dir.close();
var ch = try CacheHash.init(gpa, cache_dir, "exe");
defer ch.release();
const self_exe_path = try fs.selfExePathAlloc(gpa);
defer gpa.free(self_exe_path);
_ = try ch.addFile(self_exe_path, null);
if (try ch.hit()) |digest| {
compiler_id = digest[0..16].*;
return compiler_id;
}
const libs = try std.process.getSelfExeSharedLibPaths(gpa);
defer {
for (libs) |lib| gpa.free(lib);
gpa.free(libs);
}
for (libs) |lib| {
try ch.addFilePost(lib);
}
const digest = ch.final();
compiler_id = digest[0..16].*;
return compiler_id;
} | src-self-hosted/introspect.zig |
const std = @import("std");
const builtin = @import("builtin");
const log = std.log;
const assert = std.debug.assert;
const fs = @import("src/build/fs.zig");
const Builder = std.build.Builder;
const LibExeObjStep = std.build.LibExeObjStep;
const Step = std.build.Step;
const RunStep = std.build.RunStep;
const FileSource = std.build.FileSource;
const building_os = builtin.target.os.tag;
const building_arch = builtin.target.cpu.arch;
const Arch = std.Target.Cpu.Arch;
const cache_dir = "zig-cache";
const kernel_name = "kernel.elf";
const kernel_path = cache_dir ++ "/" ++ kernel_name;
pub fn build(b: *Builder) void {
const kernel = b.allocator.create(Kernel) catch unreachable;
// zig fmt: off
kernel.* = Kernel {
.builder = b,
.options = .{
.arch = Kernel.Options.x86_64.new(.{ .bootloader = .limine, .protocol = .stivale2 }),
.run = .{
.disk_interface = .nvme,// .nvme,
.filesystem = .custom,
.memory = .{ .amount = 4, .unit = .G, },
.emulator = .{
.qemu = .{
.vga = .std,
.smp = null,
.log = .{ .file = "logfile", .guest_errors = true, .cpu = false, .assembly = false, .interrupts = true, },
.run_for_debug = false,
},
},
},
}
};
// zig fmt: on
kernel.create();
}
const Kernel = struct {
builder: *Builder,
executable: *LibExeObjStep = undefined,
userspace_programs: []*LibExeObjStep = &.{},
options: Options,
boot_image_step: Step = undefined,
disk_step: Step = undefined,
fn create(kernel: *Kernel) void {
kernel.create_executable();
kernel.create_disassembly_step();
kernel.create_userspace_programs();
kernel.create_boot_image();
kernel.create_disk();
kernel.create_run_and_debug_steps();
}
fn create_executable(kernel: *Kernel) void {
kernel.executable = kernel.builder.addExecutable(kernel_name, "src/kernel/root.zig");
var target = get_target_base(kernel.options.arch);
switch (kernel.options.arch) {
.riscv64 => {
target.cpu_features_sub.addFeature(@enumToInt(std.Target.riscv.Feature.d));
kernel.executable.code_model = .medium;
const assembly_files = [_][]const u8{
"start.S",
"interrupt.S",
};
const arch_source_dir = kernel.builder.fmt("src/kernel/arch/{s}/", .{@tagName(kernel.options.arch)});
for (assembly_files) |asm_file| {
const asm_file_path = std.mem.concat(kernel.builder.allocator, u8, &.{ arch_source_dir, asm_file }) catch unreachable;
kernel.executable.addAssemblyFile(asm_file_path);
}
const linker_path = std.mem.concat(kernel.builder.allocator, u8, &.{ arch_source_dir, "linker.ld" }) catch unreachable;
kernel.executable.setLinkerScriptPath(FileSource.relative(linker_path));
},
.x86_64 => {
kernel.executable.code_model = .kernel;
//kernel.executable.pie = true;
kernel.executable.force_pic = true;
kernel.executable.disable_stack_probing = true;
kernel.executable.strip = false;
kernel.executable.code_model = .kernel;
kernel.executable.red_zone = false;
kernel.executable.omit_frame_pointer = false;
const linker_script_path = std.mem.concat(kernel.builder.allocator, u8, &.{ BootImage.x86_64.Limine.base_path, @tagName(kernel.options.arch.x86_64.bootloader.limine.protocol), ".ld" }) catch unreachable;
kernel.executable.setLinkerScriptPath(FileSource.relative(linker_script_path));
},
else => unreachable,
}
kernel.executable.setTarget(target);
kernel.executable.setMainPkgPath("src");
kernel.executable.setBuildMode(kernel.builder.standardReleaseOptions());
kernel.executable.setOutputDir(cache_dir);
kernel.builder.default_step.dependOn(&kernel.executable.step);
}
fn create_disassembly_step(kernel: *Kernel) void {
var arg_list = std.ArrayList([]const u8).init(kernel.builder.allocator);
const main_args = &.{ "llvm-objdump", kernel_path };
const common_flags = &.{ "-d", "-S" };
arg_list.appendSlice(main_args) catch unreachable;
arg_list.appendSlice(common_flags) catch unreachable;
switch (kernel.options.arch) {
.x86_64 => arg_list.append("-Mintel") catch unreachable,
else => {},
}
const disassembly_kernel = kernel.builder.addSystemCommand(arg_list.items);
disassembly_kernel.step.dependOn(&kernel.executable.step);
const disassembly_kernel_step = kernel.builder.step("disasm", "Disassembly the kernel ELF");
disassembly_kernel_step.dependOn(&disassembly_kernel.step);
}
fn create_userspace_programs(kernel: *Kernel) void {
var userspace_programs = std.ArrayList(*LibExeObjStep).init(kernel.builder.allocator);
const userspace_program_descriptors = [_]ZigProgramDescriptor{.{
.out_filename = "minimal.elf",
.main_source_file = "src/user/minimal/main.zig",
}};
for (userspace_program_descriptors) |descriptor| {
const program = kernel.builder.addExecutable(descriptor.out_filename, descriptor.main_source_file);
program.setTarget(get_target_base(kernel.options.arch));
program.setOutputDir(cache_dir);
kernel.builder.default_step.dependOn(&program.step);
userspace_programs.append(program) catch unreachable;
}
kernel.userspace_programs = userspace_programs.items;
}
fn create_boot_image(kernel: *Kernel) void {
kernel.boot_image_step = switch (kernel.options.arch) {
.x86_64 => switch (kernel.options.arch.x86_64.bootloader) {
.limine => BootImage.x86_64.Limine.new(kernel),
},
else => unreachable,
};
}
fn create_disk(kernel: *Kernel) void {
if (kernel.options.run.disk_interface) |_| {
Disk.create(kernel);
}
}
fn create_run_and_debug_steps(kernel: *Kernel) void {
var run_argument_list = std.ArrayList([]const u8).init(kernel.builder.allocator);
var debug_argument_list: std.ArrayList([]const u8) = undefined;
switch (kernel.options.run.emulator) {
.qemu => {
const qemu_name = std.mem.concat(kernel.builder.allocator, u8, &.{ "qemu-system-", @tagName(kernel.options.arch) }) catch unreachable;
run_argument_list.append(qemu_name) catch unreachable;
switch (kernel.options.arch) {
.x86_64 => {
const image_flag = "-cdrom";
const image_path = switch (kernel.options.arch.x86_64.bootloader) {
.limine => Kernel.BootImage.x86_64.Limine.image_path,
};
run_argument_list.append(image_flag) catch unreachable;
run_argument_list.append(image_path) catch unreachable;
},
.riscv64 => {
run_argument_list.append("-bios") catch unreachable;
run_argument_list.append("default") catch unreachable;
run_argument_list.append("-kernel") catch unreachable;
run_argument_list.append(kernel_path) catch unreachable;
},
else => unreachable,
}
{
run_argument_list.append("-no-reboot") catch unreachable;
run_argument_list.append("-no-shutdown") catch unreachable;
}
{
const memory_arg = kernel.builder.fmt("{}{s}", .{ kernel.options.run.memory.amount, @tagName(kernel.options.run.memory.unit) });
run_argument_list.append("-m") catch unreachable;
run_argument_list.append(memory_arg) catch unreachable;
}
if (kernel.options.run.emulator.qemu.smp) |smp_count| {
run_argument_list.append("-smp") catch unreachable;
run_argument_list.append(kernel.builder.fmt("{}", .{smp_count})) catch unreachable;
}
if (kernel.options.run.emulator.qemu.vga) |vga_option| {
run_argument_list.append("-vga") catch unreachable;
run_argument_list.append(@tagName(vga_option)) catch unreachable;
} else {
run_argument_list.append("-nographic") catch unreachable;
}
if (kernel.options.arch == .x86_64) {
run_argument_list.append("-debugcon") catch unreachable;
run_argument_list.append("stdio") catch unreachable;
}
if (kernel.options.run.disk_interface) |disk_interface| {
run_argument_list.append("-drive") catch unreachable;
// TODO: consider other drive options
const disk_id = "primary_disk";
const drive_options = kernel.builder.fmt("file={s},if=none,id={s},format=raw", .{ Disk.path, disk_id });
run_argument_list.append(drive_options) catch unreachable;
switch (disk_interface) {
.nvme => {
run_argument_list.append("-device") catch unreachable;
const device_options = kernel.builder.fmt("nvme,drive={s},serial=1234", .{disk_id});
run_argument_list.append(device_options) catch unreachable;
},
else => unreachable,
}
}
// Here the arch-specific stuff start and that's why the lists are split. For debug builds virtualization is pointless since it gives you no debug information
run_argument_list.append("-machine") catch unreachable;
debug_argument_list = run_argument_list.clone() catch unreachable;
const machine = switch (kernel.options.arch) {
.x86_64 => "q35",
.riscv64 => "virt",
else => unreachable,
};
debug_argument_list.append(machine) catch unreachable;
if (kernel.options.arch == building_arch and !kernel.options.run.emulator.qemu.run_for_debug) {
run_argument_list.append(kernel.builder.fmt("{s},accel=kvm:whpx:tcg", .{machine})) catch unreachable;
} else {
run_argument_list.append(machine) catch unreachable;
if (kernel.options.run.emulator.qemu.log) |log_options| {
const log_flag = "-d";
run_argument_list.append(log_flag) catch unreachable;
debug_argument_list.append(log_flag) catch unreachable;
var log_what = std.ArrayList(u8).init(kernel.builder.allocator);
if (log_options.guest_errors) log_what.appendSlice("guest_errors,") catch unreachable;
if (log_options.cpu) log_what.appendSlice("cpu,") catch unreachable;
if (log_options.interrupts) log_what.appendSlice("int,") catch unreachable;
if (log_options.assembly) log_what.appendSlice("in_asm,") catch unreachable;
// Delete the last comma
_ = log_what.pop();
run_argument_list.append(log_what.items) catch unreachable;
debug_argument_list.append(log_what.items) catch unreachable;
if (log_options.file) |log_file| {
const log_file_flag = "-D";
run_argument_list.append(log_file_flag) catch unreachable;
debug_argument_list.append(log_file_flag) catch unreachable;
run_argument_list.append(log_file) catch unreachable;
debug_argument_list.append(log_file) catch unreachable;
}
}
}
},
}
const run_command = kernel.builder.addSystemCommand(run_argument_list.items);
const run_step = kernel.builder.step("run", "run step");
run_step.dependOn(&run_command.step);
switch (kernel.options.arch) {
.x86_64 => run_command.step.dependOn(&kernel.boot_image_step),
else => unreachable,
}
}
const BootImage = struct {
const x86_64 = struct {
const Limine = struct {
const installer = @import("src/kernel/arch/x86_64/limine/installer.zig");
const base_path = "src/kernel/arch/x86_64/limine/";
const to_install_path = base_path ++ "to_install/";
const image_path = "zig-cache/universal.iso";
fn new(kernel: *Kernel) Step {
var step = Step.init(.custom, "_limine_image_", kernel.builder.allocator, Limine.build);
step.dependOn(&kernel.executable.step);
return step;
}
fn build(step: *Step) !void {
const kernel = @fieldParentPtr(Kernel, "boot_image_step", step);
assert(kernel.options.arch == .x86_64);
const img_dir_path = kernel.builder.fmt("{s}/img_dir", .{kernel.builder.cache_root});
const cwd = std.fs.cwd();
cwd.deleteFile(image_path) catch {};
const img_dir = try cwd.makeOpenPath(img_dir_path, .{});
const img_efi_dir = try img_dir.makeOpenPath("EFI/BOOT", .{});
const limine_dir = try cwd.openDir(to_install_path, .{});
const limine_efi_bin_file = "limine-cd-efi.bin";
const files_to_copy_from_limine_dir = [_][]const u8{
"limine.cfg",
"limine.sys",
"limine-cd.bin",
limine_efi_bin_file,
};
for (files_to_copy_from_limine_dir) |filename| {
log.debug("Trying to copy {s}", .{filename});
try std.fs.Dir.copyFile(limine_dir, filename, img_dir, filename, .{});
}
try std.fs.Dir.copyFile(limine_dir, "BOOTX64.EFI", img_efi_dir, "BOOTX64.EFI", .{});
try std.fs.Dir.copyFile(cwd, kernel_path, img_dir, std.fs.path.basename(kernel_path), .{});
var xorriso_process = std.ChildProcess.init(&.{ "xorriso", "-as", "mkisofs", "-quiet", "-b", "limine-cd.bin", "-no-emul-boot", "-boot-load-size", "4", "-boot-info-table", "--efi-boot", limine_efi_bin_file, "-efi-boot-part", "--efi-boot-image", "--protective-msdos-label", img_dir_path, "-o", image_path }, kernel.builder.allocator);
// Ignore stderr and stdout
xorriso_process.stdin_behavior = std.ChildProcess.StdIo.Ignore;
xorriso_process.stdout_behavior = std.ChildProcess.StdIo.Ignore;
xorriso_process.stderr_behavior = std.ChildProcess.StdIo.Ignore;
_ = try xorriso_process.spawnAndWait();
try Limine.installer.install(image_path, false, null);
}
};
};
};
const Disk = struct {
const block_size = 0x200;
const block_count = 64;
var buffer: [block_size * block_count]u8 align(0x1000) = undefined;
const path = "zig-cache/disk.bin";
fn create(kernel: *Kernel) void {
kernel.disk_step = Step.init(.custom, "disk_create", kernel.builder.allocator, make);
const named_step = kernel.builder.step("disk", "Create a disk blob to use with QEMU");
named_step.dependOn(&kernel.disk_step);
for (kernel.userspace_programs) |program| {
kernel.disk_step.dependOn(&program.step);
}
}
fn make(step: *Step) !void {
const kernel = @fieldParentPtr(Kernel, "disk_step", step);
const font_file = try std.fs.cwd().readFileAlloc(kernel.builder.allocator, "resources/zap-light16.psf", std.math.maxInt(usize));
std.debug.print("Font file size: {} bytes\n", .{font_file.len});
var disk = fs.MemoryDisk{
.bytes = buffer[0..],
};
fs.add_file(disk, "font.psf", font_file);
var debug_file = std.ArrayList(u8).init(kernel.builder.allocator);
for (disk.bytes) |byte, i| {
try debug_file.appendSlice(kernel.builder.fmt("[{}] = 0x{x}]\n", .{ i, byte }));
}
try std.fs.cwd().writeFile("debug_disk", debug_file.items);
try std.fs.cwd().writeFile(Disk.path, &Disk.buffer);
}
};
const Options = struct {
arch: Options.ArchSpecific,
run: RunOptions,
const x86_64 = struct {
bootloader: union(Bootloader) {
limine: Limine,
},
const Bootloader = enum {
limine,
};
fn new(context: anytype) Options.ArchSpecific {
return switch (context.bootloader) {
.limine => .{
.x86_64 = .{
.bootloader = .{
.limine = .{
.protocol = context.protocol,
},
},
},
},
else => unreachable,
};
}
const Limine = struct {
protocol: Protocol,
const Protocol = enum(u32) {
stivale2,
limine,
};
};
};
const ArchSpecific = union(Arch) {
arm,
armeb,
aarch64,
aarch64_be,
aarch64_32,
arc,
avr,
bpfel,
bpfeb,
csky,
hexagon,
m68k,
mips,
mipsel,
mips64,
mips64el,
msp430,
powerpc,
powerpcle,
powerpc64,
powerpc64le,
r600,
amdgcn,
riscv32,
riscv64: void,
sparc,
sparc64,
sparcel,
s390x,
tce,
tcele,
thumb,
thumbeb,
i386,
x86_64: x86_64,
xcore,
nvptx,
nvptx64,
le32,
le64,
amdil,
amdil64,
hsail,
hsail64,
spir,
spir64,
kalimba,
shave,
lanai,
wasm32,
wasm64,
renderscript32,
renderscript64,
ve,
// Stage1 currently assumes that architectures above this comment
// map one-to-one with the ZigLLVM_ArchType enum.
spu_2,
spirv32,
spirv64,
};
const RunOptions = struct {
disk_interface: ?DiskInterface,
filesystem: ?Filesystem,
memory: Memory,
emulator: union(enum) {
qemu: QEMU,
},
const Memory = struct {
amount: u64,
unit: Unit,
const Unit = enum(u3) {
K = 1,
M = 2,
G = 3,
T = 4,
};
};
const QEMU = struct {
vga: ?VGA,
log: ?LogOptions,
smp: ?u64,
run_for_debug: bool,
const VGA = enum {
std,
virtio,
};
};
const LogOptions = struct {
file: ?[]const u8,
guest_errors: bool,
cpu: bool,
interrupts: bool,
assembly: bool,
};
const DiskInterface = enum {
virtio,
ahci,
nvme,
};
const Filesystem = enum { custom };
};
};
};
const CPUFeatures = struct {
enabled: std.Target.Cpu.Feature.Set,
disabled: std.Target.Cpu.Feature.Set,
};
fn get_riscv_base_features() CPUFeatures {
var features = CPUFeatures{
.enabled = std.Target.Cpu.Feature.Set.empty,
.disabled = std.Target.Cpu.Feature.Set.empty,
};
const Feature = std.Target.riscv.Feature;
features.enabled.addFeature(@enumToInt(Feature.a));
return features;
}
fn get_x86_base_features() CPUFeatures {
var features = CPUFeatures{
.enabled = std.Target.Cpu.Feature.Set.empty,
.disabled = std.Target.Cpu.Feature.Set.empty,
};
const Feature = std.Target.x86.Feature;
features.disabled.addFeature(@enumToInt(Feature.mmx));
features.disabled.addFeature(@enumToInt(Feature.sse));
features.disabled.addFeature(@enumToInt(Feature.sse2));
features.disabled.addFeature(@enumToInt(Feature.avx));
features.disabled.addFeature(@enumToInt(Feature.avx2));
features.enabled.addFeature(@enumToInt(Feature.soft_float));
return features;
}
fn get_target_base(arch: Arch) std.zig.CrossTarget {
const cpu_features = switch (arch) {
.riscv64 => get_riscv_base_features(),
.x86_64 => get_x86_base_features(),
else => unreachable,
};
const target = std.zig.CrossTarget{
.cpu_arch = arch,
.os_tag = .freestanding,
.abi = .none,
.cpu_features_add = cpu_features.enabled,
.cpu_features_sub = cpu_features.disabled,
};
return target;
}
const ZigProgramDescriptor = struct {
out_filename: []const u8,
main_source_file: []const u8,
};
//const Debug = struct {
//step: Step,
//b: *Builder,
//arch: Arch,
//fn create(b: *Builder, arch: Arch) *Debug {
//const self = kernel.builder.allocator.create(@This()) catch @panic("out of memory\n");
//self.* = Debug{
//.step = Step.init(.custom, "_debug_", kernel.builder.allocator, make),
//.b = b,
//.arch = arch,
//};
//const named_step = kernel.builder.step("debug", "Debug the program with QEMU and GDB");
//named_step.dependOn(&self.step);
//return self;
//}
//fn make(step: *Step) !void {
//const self = @fieldParentPtr(Debug, "step", step);
//const b = self.b;
//const qemu = get_qemu_command(self.arch) ++ [_][]const u8{ "-S", "-s" };
//if (building_os == .windows) {
//unreachable;
//} else {
//const terminal_thread = try std.Thread.spawn(.{}, terminal_and_gdb_thread, .{b});
//var process = std.ChildProcess.init(qemu, kernel.builder.allocator);
//_ = try process.spawnAndWait();
//terminal_thread.join();
//_ = try process.kill();
//}
//}
//fn terminal_and_gdb_thread(b: *Builder) void {
//_ = b;
////zig fmt: off
////var kernel_elf = std.fs.realpathAlloc(kernel.builder.allocator, "zig-cache/kernel.elf") catch unreachable;
////if (builtin.os.tag == .windows) {
////const buffer = kernel.builder.allocator.create([512]u8) catch unreachable;
////var counter: u64 = 0;
////for (kernel_elf) |ch| {
////const is_separator = ch == '\\';
////buffer[counter] = ch;
////buffer[counter + @boolToInt(is_separator)] = ch;
////counter += @as(u64, 1) + @boolToInt(is_separator);
////}
////kernel_elf = buffer[0..counter];
////}
////const symbol_file = kernel.builder.fmt("symbol-file {s}", .{kernel_elf});
////const process_name = [_][]const u8{
////"wezterm", "start", "--",
////get_gdb_name(arch),
////"-tui",
////"-ex", symbol_file,
////"-ex", "target remote :1234",
////"-ex", "b start",
////"-ex", "c",
////};
////for (process_name) |arg, arg_i| {
////log.debug("Process[{}]: {s}", .{arg_i, arg});
////}
////var process = std.ChildProcess.init(&process_name, kernel.builder.allocator);
//// zig fmt: on
////_ = process.spawnAndWait() catch unreachable;
//}
//}; | build.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const assert = std.debug.assert;
//;
// TODO maybe make it so ptrs hold offsets rather than pointers, and cant be invalidated by pool resizes
// maybe make it so this thing can be easier resized?
// could further increase cache locality by doing a binary search to kill objects
// or something
// some way of using the lowest offsets first so theyre all usually in one spot
pub fn Pool(comptime T: type) type {
return struct {
const Self = @This();
pub const Iter = struct {
pool: *const Self,
idx: usize,
pub fn next(self: *Iter) ?*const T {
if (self.idx >= self.pool.alive_ct) {
return null;
} else {
const get = &self.pool.data.items[self.pool.offsets.items[self.idx]];
self.idx += 1;
return get;
}
}
};
pub const IterMut = struct {
pool: *Self,
idx: usize,
pub fn next(self: *IterMut) ?*T {
if (self.idx >= self.pool.alive_ct) {
return null;
} else {
const get = &self.pool.data.items[self.pool.offsets.items[self.idx]];
self.idx += 1;
return get;
}
}
};
pub const Ptr = struct {
pool: *Self,
obj: *T,
pub fn kill(self: *Ptr) void {
self.pool.kill(self.obj);
}
// TODO
pub fn killStable(self: *Ptr) void {}
};
data: ArrayList(T),
offsets: ArrayList(usize),
alive_ct: usize,
pub fn init(allocator: *Allocator, initial_size: usize) !Self {
var data = try ArrayList(T).initCapacity(allocator, initial_size);
data.appendNTimesAssumeCapacity(undefined, initial_size);
var offsets = try ArrayList(usize).initCapacity(allocator, initial_size);
var i: usize = 0;
while (i < initial_size) : (i += 1) {
offsets.append(i) catch unreachable;
}
return Self{
.data = data,
.offsets = offsets,
.alive_ct = 0,
};
}
pub fn deinit(self: *Self) void {
self.offsets.deinit();
self.data.deinit();
}
//;
// asserts pool isnt empty
pub fn spawn(self: *Self) *T {
assert(!self.isEmpty());
const at = self.alive_ct;
self.alive_ct += 1;
return &self.data.items[self.offsets.items[at]];
}
// TODO maybe return an error here instead
// if not, rename to maybeSpawn
pub fn trySpawn(self: *Self) ?*T {
if (self.isEmpty()) return null;
return self.spawn();
}
// TODO killStable
// asserts this object is from this pool, and is alive
pub fn kill(self: *Self, obj: *T) void {
// assert ptr is from this pool
assert(blk: {
const t = @ptrToInt(obj);
const d = @ptrToInt(self.data.items.ptr);
break :blk t >= d and t < (d + self.data.items.len * @sizeOf(T));
});
// assert ptr is alive
assert(blk: {
const t = @ptrToInt(obj);
const d = @ptrToInt(self.data.items.ptr);
const o = (t - d) / @sizeOf(T);
var i: usize = 0;
while (i < self.alive_ct) : (i += 1) {
if (self.offsets.items[i] == o) {
break :blk true;
}
}
break :blk false;
});
const obj_ptr = @ptrToInt(obj);
const data_ptr = @ptrToInt(self.data.items.ptr);
const offset = (obj_ptr - data_ptr) / @sizeOf(T);
self.alive_ct -= 1;
var i: usize = 0;
while (i < self.alive_ct) : (i += 1) {
if (self.offsets.items[i] == offset) {
std.mem.swap(
usize,
&self.offsets.items[self.alive_ct],
&self.offsets.items[i],
);
}
}
}
pub fn spawnPtr(self: *Self) Ptr {
return .{
.pool = self,
.obj = self.spawn(),
};
}
//;
// this function may invalidate pointers to objects in the pool
// if you plan to use this function it's recommended let the pool manage the memory for you,
// using iterators and reclaim
pub fn pleaseSpawn(self: *Self) !*T {
if (self.isEmpty()) {
try self.offsets.append(self.data.items.len);
_ = try self.data.addOne();
}
return self.spawn();
}
pub fn iter(self: *const Self) Iter {
return .{
.pool = self,
.idx = 0,
};
}
pub fn iterMut(self: *Self) IterMut {
return .{
.pool = self,
.idx = 0,
};
}
pub fn reclaim(self: *Self, killFn: fn (*T) bool) void {
var len = self.alive_ct;
var i: usize = 0;
while (i < len) {
if (killFn(&self.data.items[self.offsets.items[i]])) {
len -= 1;
std.mem.swap(
usize,
&self.offsets.items[i],
&self.offsets.items[len],
);
}
i += 1;
}
self.alive_ct = len;
}
pub fn reclaimStable(self: *Self, killFn: fn (*T) bool) void {
const len = self.alive_ct;
var del: usize = 0;
var i: usize = 0;
while (i < len) : (i += 1) {
if (killFn(&self.data.items[self.offsets.items[i]])) {
del += 1;
} else if (del > 0) {
std.mem.swap(
usize,
&self.offsets.items[i],
&self.offsets.items[i - del],
);
}
}
self.alive_ct -= del;
}
//;
// TODO
// attach
// detach
// sort the dead
//;
pub fn isEmpty(self: Self) bool {
return self.deadCount() == 0;
}
pub fn aliveCount(self: Self) usize {
return self.alive_ct;
}
pub fn deadCount(self: Self) usize {
return self.offsets.items.len - self.alive_ct;
}
pub fn capacity(self: Self) usize {
return self.offsets.items.len;
}
};
}
// tests ===
const testing = std.testing;
const expect = testing.expect;
fn killEven(value: *u8) bool {
return value.* % 2 == 0;
}
fn kill3(value: *u8) bool {
return value.* == 3;
}
test "Pool" {
var pool = try Pool(u8).init(testing.allocator, 10);
defer pool.deinit();
pool.trySpawn().?.* = 1;
pool.trySpawn().?.* = 2;
pool.trySpawn().?.* = 3;
pool.trySpawn().?.* = 4;
pool.trySpawn().?.* = 5;
expect(pool.aliveCount() == 5);
var iter = pool.iter();
// order is guaranteed in the order you spawned them
expect(iter.next().?.* == 1);
expect(iter.next().?.* == 2);
expect(iter.next().?.* == 3);
expect(iter.next().?.* == 4);
expect(iter.next().?.* == 5);
expect(iter.next() == null);
// won't mess with order
pool.reclaimStable(killEven);
expect(pool.aliveCount() == 3);
iter = pool.iter();
expect(iter.next().?.* == 1);
expect(iter.next().?.* == 3);
expect(iter.next().?.* == 5);
expect(iter.next() == null);
// may mess with the order
pool.reclaim(kill3);
expect(pool.aliveCount() == 2);
var found_one: bool = false;
var found_five: bool = false;
iter = pool.iter();
while (iter.next()) |val| {
if (val.* == 1) {
expect(!found_one);
found_one = true;
} else if (val.* == 5) {
expect(!found_five);
found_five = true;
}
}
expect(found_one);
expect(found_five);
var i: usize = 0;
while (i < 8) : (i += 1) {
pool.trySpawn().?.* = 0;
}
expect(pool.trySpawn() == null);
_ = try pool.pleaseSpawn();
expect(pool.capacity() == 11);
expect(pool.aliveCount() == 11);
expect(pool.isEmpty());
}
test "Pool kill" {
var pool = try Pool(u8).init(testing.allocator, 10);
defer pool.deinit();
const obj = pool.spawn();
expect(pool.aliveCount() == 1);
pool.kill(obj);
expect(pool.aliveCount() == 0);
} | src/pool.zig |
const std = @import("std");
const os = std.os;
const testing = std.testing;
const assert = std.debug.assert;
const Time = @import("../time.zig").Time;
const IO = @import("../io.zig").IO;
test "write/fsync/read/close" {
try struct {
const Context = @This();
io: IO,
done: bool = false,
fd: os.fd_t,
write_buf: [20]u8 = [_]u8{97} ** 20,
read_buf: [20]u8 = [_]u8{98} ** 20,
written: usize = 0,
fsynced: bool = false,
read: usize = 0,
fn run_test() !void {
const path = "test_io_write_fsync_read";
const file = try std.fs.cwd().createFile(path, .{ .read = true, .truncate = true });
defer std.fs.cwd().deleteFile(path) catch {};
var self: Context = .{
.io = try IO.init(32, 0),
.fd = file.handle,
};
defer self.io.deinit();
var completion: IO.Completion = undefined;
self.io.write(
*Context,
&self,
write_callback,
&completion,
self.fd,
&self.write_buf,
10,
);
while (!self.done) try self.io.tick();
try testing.expectEqual(self.write_buf.len, self.written);
try testing.expect(self.fsynced);
try testing.expectEqual(self.read_buf.len, self.read);
try testing.expectEqualSlices(u8, &self.write_buf, &self.read_buf);
}
fn write_callback(
self: *Context,
completion: *IO.Completion,
result: IO.WriteError!usize,
) void {
self.written = result catch @panic("write error");
self.io.fsync(*Context, self, fsync_callback, completion, self.fd);
}
fn fsync_callback(
self: *Context,
completion: *IO.Completion,
result: IO.FsyncError!void,
) void {
result catch @panic("fsync error");
self.fsynced = true;
self.io.read(*Context, self, read_callback, completion, self.fd, &self.read_buf, 10);
}
fn read_callback(
self: *Context,
completion: *IO.Completion,
result: IO.ReadError!usize,
) void {
self.read = result catch @panic("read error");
self.io.close(*Context, self, close_callback, completion, self.fd);
}
fn close_callback(
self: *Context,
completion: *IO.Completion,
result: IO.CloseError!void,
) void {
_ = result catch @panic("close error");
self.done = true;
}
}.run_test();
}
test "accept/connect/send/receive" {
try struct {
const Context = @This();
io: IO,
done: bool = false,
server: os.socket_t,
client: os.socket_t,
accepted_sock: os.socket_t = undefined,
send_buf: [10]u8 = [_]u8{ 1, 0, 1, 0, 1, 0, 1, 0, 1, 0 },
recv_buf: [5]u8 = [_]u8{ 0, 1, 0, 1, 0 },
sent: usize = 0,
received: usize = 0,
fn run_test() !void {
const address = try std.net.Address.parseIp4("127.0.0.1", 3131);
const kernel_backlog = 1;
const server = try IO.openSocket(address.any.family, os.SOCK_STREAM, os.IPPROTO_TCP);
defer os.closeSocket(server);
const client = try IO.openSocket(address.any.family, os.SOCK_STREAM, os.IPPROTO_TCP);
defer os.closeSocket(client);
try os.setsockopt(
server,
os.SOL_SOCKET,
os.SO_REUSEADDR,
&std.mem.toBytes(@as(c_int, 1)),
);
try os.bind(server, &address.any, address.getOsSockLen());
try os.listen(server, kernel_backlog);
var self: Context = .{
.io = try IO.init(32, 0),
.server = server,
.client = client,
};
defer self.io.deinit();
var client_completion: IO.Completion = undefined;
self.io.connect(
*Context,
&self,
connect_callback,
&client_completion,
client,
address,
);
var server_completion: IO.Completion = undefined;
self.io.accept(*Context, &self, accept_callback, &server_completion, server);
while (!self.done) try self.io.tick();
try testing.expectEqual(self.send_buf.len, self.sent);
try testing.expectEqual(self.recv_buf.len, self.received);
try testing.expectEqualSlices(u8, self.send_buf[0..self.received], &self.recv_buf);
}
fn connect_callback(
self: *Context,
completion: *IO.Completion,
result: IO.ConnectError!void,
) void {
result catch @panic("connect error");
self.io.send(
*Context,
self,
send_callback,
completion,
self.client,
&self.send_buf,
);
}
fn send_callback(
self: *Context,
completion: *IO.Completion,
result: IO.SendError!usize,
) void {
self.sent = result catch @panic("send error");
}
fn accept_callback(
self: *Context,
completion: *IO.Completion,
result: IO.AcceptError!os.socket_t,
) void {
self.accepted_sock = result catch @panic("accept error");
self.io.recv(
*Context,
self,
recv_callback,
completion,
self.accepted_sock,
&self.recv_buf,
);
}
fn recv_callback(
self: *Context,
completion: *IO.Completion,
result: IO.RecvError!usize,
) void {
self.received = result catch @panic("recv error");
self.done = true;
}
}.run_test();
}
test "timeout" {
const ms = 20;
const margin = 5;
const count = 10;
try struct {
const Context = @This();
io: IO,
timer: *Time,
count: u32 = 0,
stop_time: u64 = 0,
fn run_test() !void {
var timer = Time{};
const start_time = timer.monotonic();
var self: Context = .{
.timer = &timer,
.io = try IO.init(32, 0),
};
defer self.io.deinit();
var completions: [count]IO.Completion = undefined;
for (completions) |*completion| {
self.io.timeout(
*Context,
&self,
timeout_callback,
completion,
ms * std.time.ns_per_ms,
);
}
while (self.count < count) try self.io.tick();
try self.io.tick();
try testing.expectEqual(@as(u32, count), self.count);
try testing.expectApproxEqAbs(
@as(f64, ms),
@intToFloat(f64, (self.stop_time - start_time) / std.time.ns_per_ms),
margin,
);
}
fn timeout_callback(
self: *Context,
completion: *IO.Completion,
result: IO.TimeoutError!void,
) void {
result catch @panic("timeout error");
if (self.stop_time == 0) self.stop_time = self.timer.monotonic();
self.count += 1;
}
}.run_test();
}
test "submission queue full" {
const ms = 20;
const count = 10;
try struct {
const Context = @This();
io: IO,
count: u32 = 0,
fn run_test() !void {
var self: Context = .{ .io = try IO.init(1, 0) };
defer self.io.deinit();
var completions: [count]IO.Completion = undefined;
for (completions) |*completion| {
self.io.timeout(
*Context,
&self,
timeout_callback,
completion,
ms * std.time.ns_per_ms,
);
}
while (self.count < count) try self.io.tick();
try self.io.tick();
try testing.expectEqual(@as(u32, count), self.count);
}
fn timeout_callback(
self: *Context,
completion: *IO.Completion,
result: IO.TimeoutError!void,
) void {
result catch @panic("timeout error");
self.count += 1;
}
}.run_test();
}
test "tick to wait" {
// Use only IO.tick() to see if pending IO is actually processsed
try struct {
const Context = @This();
io: IO,
accepted: os.socket_t = -1,
connected: bool = false,
received: bool = false,
fn run_test() !void {
var self: Context = .{ .io = try IO.init(1, 0) };
defer self.io.deinit();
const address = try std.net.Address.parseIp4("127.0.0.1", 3131);
const kernel_backlog = 1;
const server = try IO.openSocket(address.any.family, os.SOCK_STREAM, os.IPPROTO_TCP);
defer os.closeSocket(server);
try os.setsockopt(
server,
os.SOL_SOCKET,
os.SO_REUSEADDR,
&std.mem.toBytes(@as(c_int, 1)),
);
try os.bind(server, &address.any, address.getOsSockLen());
try os.listen(server, kernel_backlog);
const client = try IO.openSocket(address.any.family, os.SOCK_STREAM, os.IPPROTO_TCP);
defer os.closeSocket(client);
// Start the accept
var server_completion: IO.Completion = undefined;
self.io.accept(*Context, &self, accept_callback, &server_completion, server);
// Start the connect
var client_completion: IO.Completion = undefined;
self.io.connect(
*Context,
&self,
connect_callback,
&client_completion,
client,
address,
);
// Tick the IO to drain the accept & connect completions
assert(!self.connected);
assert(self.accepted == -1);
while (self.accepted == -1 or !self.connected)
try self.io.tick();
assert(self.connected);
assert(self.accepted != -1);
defer os.closeSocket(self.accepted);
// Start receiving on the client
var recv_completion: IO.Completion = undefined;
var recv_buffer: [64]u8 = undefined;
std.mem.set(u8, &recv_buffer, 0xaa);
self.io.recv(
*Context,
&self,
recv_callback,
&recv_completion,
client,
&recv_buffer,
);
// Drain out the recv completion from any internal IO queues
try self.io.tick();
try self.io.tick();
try self.io.tick();
// Complete the recv() *outside* of the IO instance.
// Other tests already check .tick() with IO based completions.
// This simulates IO being completed by an external system
var send_buf = std.mem.zeroes([64]u8);
const wrote = try os.write(self.accepted, &send_buf);
try testing.expectEqual(wrote, send_buf.len);
// Wait for the recv() to complete using only IO.tick().
// If tick is broken, then this will deadlock
assert(!self.received);
while (!self.received) {
try self.io.tick();
}
// Make sure the receive actually happened
assert(self.received);
try testing.expect(std.mem.eql(u8, &recv_buffer, &send_buf));
}
fn accept_callback(
self: *Context,
completion: *IO.Completion,
result: IO.AcceptError!os.socket_t,
) void {
assert(self.accepted == -1);
self.accepted = result catch @panic("accept error");
}
fn connect_callback(
self: *Context,
completion: *IO.Completion,
result: IO.ConnectError!void,
) void {
result catch @panic("connect error");
assert(!self.connected);
self.connected = true;
}
fn recv_callback(
self: *Context,
completion: *IO.Completion,
result: IO.RecvError!usize,
) void {
_ = result catch |err| std.debug.panic("recv error: {}", .{err});
assert(!self.received);
self.received = true;
}
}.run_test();
}
test "pipe data over socket" {
try struct {
io: IO,
tx: Pipe,
rx: Pipe,
server: Socket = .{},
const buffer_size = 1 * 1024 * 1024;
const Context = @This();
const Socket = struct {
fd: os.socket_t = -1,
completion: IO.Completion = undefined,
};
const Pipe = struct {
socket: Socket = .{},
buffer: []u8,
transferred: usize = 0,
};
fn run() !void {
const tx_buf = try testing.allocator.alloc(u8, buffer_size);
defer testing.allocator.free(tx_buf);
const rx_buf = try testing.allocator.alloc(u8, buffer_size);
defer testing.allocator.free(rx_buf);
std.mem.set(u8, tx_buf, 1);
std.mem.set(u8, rx_buf, 0);
var self = Context{
.io = try IO.init(32, 0),
.tx = .{ .buffer = tx_buf },
.rx = .{ .buffer = rx_buf },
};
defer self.io.deinit();
self.server.fd = try IO.openSocket(os.AF_INET, os.SOCK_STREAM, os.IPPROTO_TCP);
defer os.closeSocket(self.server.fd);
const address = try std.net.Address.parseIp4("127.0.0.1", 3131);
try os.setsockopt(
self.server.fd,
os.SOL_SOCKET,
os.SO_REUSEADDR,
&std.mem.toBytes(@as(c_int, 1)),
);
try os.bind(self.server.fd, &address.any, address.getOsSockLen());
try os.listen(self.server.fd, 1);
self.io.accept(
*Context,
&self,
on_accept,
&self.server.completion,
self.server.fd,
);
self.tx.socket.fd = try IO.openSocket(os.AF_INET, os.SOCK_STREAM, os.IPPROTO_TCP);
defer os.closeSocket(self.tx.socket.fd);
self.io.connect(
*Context,
&self,
on_connect,
&self.tx.socket.completion,
self.tx.socket.fd,
address,
);
var tick: usize = 0xdeadbeef;
while (self.rx.transferred != self.rx.buffer.len) : (tick +%= 1) {
if (tick % 61 == 0) {
const timeout_ns = tick % (10 * std.time.ns_per_ms);
try self.io.run_for_ns(@intCast(u63, timeout_ns));
} else {
try self.io.tick();
}
}
try testing.expect(self.server.fd != -1);
try testing.expect(self.tx.socket.fd != -1);
try testing.expect(self.rx.socket.fd != -1);
os.closeSocket(self.rx.socket.fd);
try testing.expectEqual(self.tx.transferred, buffer_size);
try testing.expectEqual(self.rx.transferred, buffer_size);
try testing.expect(std.mem.eql(u8, self.tx.buffer, self.rx.buffer));
}
fn on_accept(
self: *Context,
completion: *IO.Completion,
result: IO.AcceptError!os.socket_t,
) void {
assert(self.rx.socket.fd == -1);
assert(&self.server.completion == completion);
self.rx.socket.fd = result catch |err| std.debug.panic("accept error {}", .{err});
assert(self.rx.transferred == 0);
self.do_receiver(0);
}
fn on_connect(
self: *Context,
completion: *IO.Completion,
result: IO.ConnectError!void,
) void {
assert(self.tx.socket.fd != -1);
assert(&self.tx.socket.completion == completion);
assert(self.tx.transferred == 0);
self.do_sender(0);
}
fn do_sender(self: *Context, bytes: usize) void {
self.tx.transferred += bytes;
assert(self.tx.transferred <= self.tx.buffer.len);
if (self.tx.transferred < self.tx.buffer.len) {
self.io.send(
*Context,
self,
on_send,
&self.tx.socket.completion,
self.tx.socket.fd,
self.tx.buffer[self.tx.transferred..],
);
}
}
fn on_send(
self: *Context,
completion: *IO.Completion,
result: IO.SendError!usize,
) void {
const bytes = result catch |err| std.debug.panic("send error: {}", .{err});
assert(&self.tx.socket.completion == completion);
self.do_sender(bytes);
}
fn do_receiver(self: *Context, bytes: usize) void {
self.rx.transferred += bytes;
assert(self.rx.transferred <= self.rx.buffer.len);
if (self.rx.transferred < self.rx.buffer.len) {
self.io.recv(
*Context,
self,
on_recv,
&self.rx.socket.completion,
self.rx.socket.fd,
self.rx.buffer[self.rx.transferred..],
);
}
}
fn on_recv(
self: *Context,
completion: *IO.Completion,
result: IO.RecvError!usize,
) void {
const bytes = result catch |err| std.debug.panic("recv error: {}", .{err});
assert(&self.rx.socket.completion == completion);
self.do_receiver(bytes);
}
}.run();
} | src/io/test.zig |
const std = @import("std");
const assert = std.debug.assert;
const print = std.debug.print;
const tools = @import("tools");
const VM = struct {
const Word = u16;
const OpCode = enum(Word) { halt, set, push, pop, eq, gt, jmp, jt, jf, add, mult, mod, band, bor, not, rmem, wmem, call, ret, out, in, noop };
const Insn = union(OpCode) {
halt: struct {}, // stop execution and terminate the program
set: struct { a: Word, b: Word }, // set register <a> to the value of <b>
push: struct { a: Word }, // push <a> onto the stack
pop: struct { a: Word }, // remove the top element from the stack and write it into <a>; empty stack = error
eq: struct { a: Word, b: Word, c: Word }, // set <a> to 1 if <b> is equal to <c>; set it to 0 otherwise
gt: struct { a: Word, b: Word, c: Word }, // set <a> to 1 if <b> is greater than <c>; set it to 0 otherwise
jmp: struct { a: Word }, // jump to <a>
jt: struct { a: Word, b: Word }, // if <a> is nonzero, jump to <b>
jf: struct { a: Word, b: Word }, // if <a> is zero, jump to <b>
add: struct { a: Word, b: Word, c: Word }, // assign into <a> the sum of <b> and <c> (modulo 32768)
mult: struct { a: Word, b: Word, c: Word }, // store into <a> the product of <b> and <c> (modulo 32768)
mod: struct { a: Word, b: Word, c: Word }, // store into <a> the remainder of <b> divided by <c>
band: struct { a: Word, b: Word, c: Word }, // stores into <a> the bitwise and of <b> and <c>
bor: struct { a: Word, b: Word, c: Word }, // stores into <a> the bitwise or of <b> and <c>
not: struct { a: Word, b: Word }, // stores 15-bit bitwise inverse of <b> in <a>
rmem: struct { a: Word, b: Word }, // read memory at address <b> and write it to <a>
wmem: struct { a: Word, b: Word }, // write the value from <b> into memory at address <a>
call: struct { a: Word }, // write the address of the next instruction to the stack and jump to <a>
ret: struct {}, // remove the top element from the stack and jump to it; empty stack = halt
out: struct { a: Word }, // write the character represented by ascii code <a> to the terminal
in: struct { a: Word }, // read a character from the terminal and write its ascii code to <a>; it can be assumed that once input starts, it will continue until a newline is encountered; this means that you can safely read whole lines from the keyboard and trust that they will be fully read
noop: struct {}, // no operation
};
const Debug = struct {
breakpoints: []const u15,
watchpoints: []const u15,
};
const State = struct {
ip: ?u15,
sp: u6,
regs: [8]u15,
stack: [64]u15, // doc: "unbounded"
mem: [32768]u16,
};
fn asRegister(a: Word) ?u3 {
if (a <= 32767) return null;
if (a >= 32776) return null;
return @intCast(u3, a - 32768);
}
fn asImmediate(a: Word) ?u15 {
if (a <= 32767) return @intCast(u15, a);
return null;
}
fn getVal(s: *const State, a: Word) u15 {
if (asImmediate(a)) |v| return v;
return s.regs[asRegister(a).?];
}
fn dumpArg(a: Word, buf: []u8) ![]const u8 {
if (a >= 32776) return error.InvalidVal;
if (a >= 32768) return std.fmt.bufPrint(buf, "R{}", .{a - 32768});
if (a >= 0x20 and a < 0x7F) return std.fmt.bufPrint(buf, "#{} '{c}'", .{ a, @intCast(u7, a) });
return std.fmt.bufPrint(buf, "#{}", .{a});
}
fn dumpInsn(insn: Insn, buf: []u8) ![]u8 {
var bufA: [16]u8 = undefined;
var bufB: [16]u8 = undefined;
var bufC: [16]u8 = undefined;
switch (insn) {
.halt, .ret, .noop => return std.fmt.bufPrint(buf, "{s}", .{@tagName(insn)}),
.set => |arg| return std.fmt.bufPrint(buf, "{s}\t{s}", .{ @tagName(insn), dumpArg(arg.a, &bufA) }),
.push => |arg| return std.fmt.bufPrint(buf, "{s}\t{s}", .{ @tagName(insn), dumpArg(arg.a, &bufA) }),
.pop => |arg| return std.fmt.bufPrint(buf, "{s}\t{s}", .{ @tagName(insn), dumpArg(arg.a, &bufA) }),
.jmp => |arg| return std.fmt.bufPrint(buf, "{s}\t{s}", .{ @tagName(insn), dumpArg(arg.a, &bufA) }),
.call => |arg| return std.fmt.bufPrint(buf, "{s}\t{s}", .{ @tagName(insn), dumpArg(arg.a, &bufA) }),
.out => |arg| return std.fmt.bufPrint(buf, "{s}\t{s}", .{ @tagName(insn), dumpArg(arg.a, &bufA) }),
.in => |arg| return std.fmt.bufPrint(buf, "{s}\t{s}", .{ @tagName(insn), dumpArg(arg.a, &bufA) }),
.eq => |arg| return std.fmt.bufPrint(buf, "{s}\t{s}, {s}, {s}", .{ @tagName(insn), dumpArg(arg.a, &bufA), dumpArg(arg.b, &bufB), dumpArg(arg.c, &bufC) }),
.gt => |arg| return std.fmt.bufPrint(buf, "{s}\t{s}, {s}, {s}", .{ @tagName(insn), dumpArg(arg.a, &bufA), dumpArg(arg.b, &bufB), dumpArg(arg.c, &bufC) }),
.jt => |arg| return std.fmt.bufPrint(buf, "{s}\t{s}, {s}", .{ @tagName(insn), dumpArg(arg.a, &bufA), dumpArg(arg.b, &bufB) }),
.jf => |arg| return std.fmt.bufPrint(buf, "{s}\t{s}, {s}", .{ @tagName(insn), dumpArg(arg.a, &bufA), dumpArg(arg.b, &bufB) }),
.not => |arg| return std.fmt.bufPrint(buf, "{s}\t{s}, {s}", .{ @tagName(insn), dumpArg(arg.a, &bufA), dumpArg(arg.b, &bufB) }),
.wmem => |arg| return std.fmt.bufPrint(buf, "{s}\t{s}, {s}", .{ @tagName(insn), dumpArg(arg.a, &bufA), dumpArg(arg.b, &bufB) }),
.rmem => |arg| return std.fmt.bufPrint(buf, "{s}\t{s}, {s}", .{ @tagName(insn), dumpArg(arg.a, &bufA), dumpArg(arg.b, &bufB) }),
.add => |arg| return std.fmt.bufPrint(buf, "{s}\t{s}, {s}, {s}", .{ @tagName(insn), dumpArg(arg.a, &bufA), dumpArg(arg.b, &bufB), dumpArg(arg.c, &bufC) }),
.mult => |arg| return std.fmt.bufPrint(buf, "{s}\t{s}, {s}, {s}", .{ @tagName(insn), dumpArg(arg.a, &bufA), dumpArg(arg.b, &bufB), dumpArg(arg.c, &bufC) }),
.mod => |arg| return std.fmt.bufPrint(buf, "{s}\t{s}, {s}, {s}", .{ @tagName(insn), dumpArg(arg.a, &bufA), dumpArg(arg.b, &bufB), dumpArg(arg.c, &bufC) }),
.band => |arg| return std.fmt.bufPrint(buf, "{s}\t{s}, {s}, {s}", .{ @tagName(insn), dumpArg(arg.a, &bufA), dumpArg(arg.b, &bufB), dumpArg(arg.c, &bufC) }),
.bor => |arg| return std.fmt.bufPrint(buf, "{s}\t{s}, {s}, {s}", .{ @tagName(insn), dumpArg(arg.a, &bufA), dumpArg(arg.b, &bufB), dumpArg(arg.c, &bufC) }),
}
}
fn execInsn(s: *State, insn: Insn, out: *[]u8, in: *[]const u8) !void {
switch (insn) {
.halt => |_| s.ip = null,
.set => |arg| s.regs[asRegister(arg.a).?] = getVal(s, arg.b),
.push => |arg| {
s.stack[s.sp] = getVal(s, arg.a);
s.sp += 1;
},
.pop => |arg| {
s.sp -= 1;
s.regs[asRegister(arg.a).?] = s.stack[s.sp];
},
.eq => |arg| s.regs[asRegister(arg.a).?] = @boolToInt(getVal(s, arg.b) == getVal(s, arg.c)),
.gt => |arg| s.regs[asRegister(arg.a).?] = @boolToInt(getVal(s, arg.b) > getVal(s, arg.c)),
.jmp => |arg| s.ip = getVal(s, arg.a),
.jt => |arg| if (getVal(s, arg.a) != 0) {
s.ip = getVal(s, arg.b);
},
.jf => |arg| if (getVal(s, arg.a) == 0) {
s.ip = getVal(s, arg.b);
},
.add => |arg| s.regs[asRegister(arg.a).?] = (getVal(s, arg.b) +% getVal(s, arg.c)),
.mult => |arg| s.regs[asRegister(arg.a).?] = (getVal(s, arg.b) *% getVal(s, arg.c)),
.mod => |arg| s.regs[asRegister(arg.a).?] = (getVal(s, arg.b) % getVal(s, arg.c)),
.band => |arg| s.regs[asRegister(arg.a).?] = (getVal(s, arg.b) & getVal(s, arg.c)),
.bor => |arg| s.regs[asRegister(arg.a).?] = (getVal(s, arg.b) | getVal(s, arg.c)),
.not => |arg| s.regs[asRegister(arg.a).?] = ~getVal(s, arg.b),
.rmem => |arg| s.regs[asRegister(arg.a).?] = @intCast(u15, s.mem[getVal(s, arg.b)]),
.wmem => |arg| s.mem[getVal(s, arg.a)] = getVal(s, arg.b),
.call => |arg| {
s.stack[s.sp] = s.ip.?;
s.sp += 1;
s.ip = getVal(s, arg.a);
},
.ret => |_| if (s.sp > 0) {
s.sp -= 1;
s.ip = s.stack[s.sp];
} else {
s.ip = null;
},
.out => |arg| {
if (out.len == 0) return error.NeedOuput;
out.*[0] = @intCast(u8, getVal(s, arg.a));
out.* = out.*[1..];
},
.in => |arg| {
if (in.len == 0) return error.NeedInput;
s.regs[asRegister(arg.a).?] = in.*[0];
in.* = in.*[1..];
},
.noop => |_| {},
}
if (s.sp >= s.stack.len) return error.StackOverflow;
}
fn fetchInsn(ip: u15, mem: []const Word) struct { insn: Insn, sz: u2 } {
const opcode = @ptrCast(*const OpCode, &mem[ip]).*;
switch (opcode) {
.halt => return .{ .sz = 0, .insn = Insn{ .halt = .{} } },
.set => return .{ .sz = 2, .insn = Insn{ .set = .{ .a = mem[ip + 1], .b = mem[ip + 2] } } },
.push => return .{ .sz = 1, .insn = Insn{ .push = .{ .a = mem[ip + 1] } } },
.pop => return .{ .sz = 1, .insn = Insn{ .pop = .{ .a = mem[ip + 1] } } },
.eq => return .{ .sz = 3, .insn = Insn{ .eq = .{ .a = mem[ip + 1], .b = mem[ip + 2], .c = mem[ip + 3] } } },
.gt => return .{ .sz = 3, .insn = Insn{ .gt = .{ .a = mem[ip + 1], .b = mem[ip + 2], .c = mem[ip + 3] } } },
.jmp => return .{ .sz = 1, .insn = Insn{ .jmp = .{ .a = mem[ip + 1] } } },
.jt => return .{ .sz = 2, .insn = Insn{ .jt = .{ .a = mem[ip + 1], .b = mem[ip + 2] } } },
.jf => return .{ .sz = 2, .insn = Insn{ .jf = .{ .a = mem[ip + 1], .b = mem[ip + 2] } } },
.add => return .{ .sz = 3, .insn = Insn{ .add = .{ .a = mem[ip + 1], .b = mem[ip + 2], .c = mem[ip + 3] } } },
.mult => return .{ .sz = 3, .insn = Insn{ .mult = .{ .a = mem[ip + 1], .b = mem[ip + 2], .c = mem[ip + 3] } } },
.mod => return .{ .sz = 3, .insn = Insn{ .mod = .{ .a = mem[ip + 1], .b = mem[ip + 2], .c = mem[ip + 3] } } },
.band => return .{ .sz = 3, .insn = Insn{ .band = .{ .a = mem[ip + 1], .b = mem[ip + 2], .c = mem[ip + 3] } } },
.bor => return .{ .sz = 3, .insn = Insn{ .bor = .{ .a = mem[ip + 1], .b = mem[ip + 2], .c = mem[ip + 3] } } },
.not => return .{ .sz = 2, .insn = Insn{ .not = .{ .a = mem[ip + 1], .b = mem[ip + 2] } } },
.rmem => return .{ .sz = 2, .insn = Insn{ .rmem = .{ .a = mem[ip + 1], .b = mem[ip + 2] } } },
.wmem => return .{ .sz = 2, .insn = Insn{ .wmem = .{ .a = mem[ip + 1], .b = mem[ip + 2] } } },
.call => return .{ .sz = 1, .insn = Insn{ .call = .{ .a = mem[ip + 1] } } },
.ret => return .{ .sz = 0, .insn = Insn{ .ret = .{} } },
.out => return .{ .sz = 1, .insn = Insn{ .out = .{ .a = mem[ip + 1] } } },
.in => return .{ .sz = 1, .insn = Insn{ .in = .{ .a = mem[ip + 1] } } },
.noop => return .{ .sz = 0, .insn = Insn{ .noop = .{} } },
}
}
fn run(state: *State, input: []const u8, outbuf: []u8, debug: ?Debug) []u8 {
var out = outbuf;
var in = input;
runloop: while (state.ip) |ip| {
const insn = VM.fetchInsn(ip, &state.mem);
if (debug) |dbg| {
if (std.mem.indexOfScalar(u15, dbg.breakpoints, ip) != null) {
print("[DEBUG] break at ip={}\n", .{ip});
break :runloop;
}
assert(dbg.watchpoints.len == 0); // TODO
}
state.ip = ip + 1 + insn.sz;
VM.execInsn(state, insn.insn, &out, &in) catch |err| switch (err) {
error.NeedInput => {
state.ip = ip;
break :runloop;
},
error.StackOverflow => unreachable,
error.NeedOuput => unreachable,
};
}
return outbuf[0 .. outbuf.len - out.len];
}
};
const IFPlayer = struct {
const Object = enum(u8) { tablet, @"empty lantern", can, lantern, @"lit lantern", @"red coin", @"blue coin", @"concave coin", @"shiny coin", @"corroded coin", teleporter, @"business card", @"strange book" };
const Exit = enum(u8) { north, west, east, south, down, up, @"continue", back, doorway, bridge, passage, cavern, ladder, darkness, forward, run, investigate, wait, hide, outside, inside };
const RoomId = struct { desc_hash: u64, pos: [3]i8 };
const RoomDesc = struct {
id: RoomId,
name: []const u8,
desc: []const u8 = "",
objects: []const Object = &[0]Object{},
exits: []const Exit = &[0]Exit{},
inventory: []const Object = &[0]Object{},
};
fn applyDir(p: [3]i8, d: Exit, reverse: bool) [3]i8 {
if (reverse) {
return switch (d) {
.north => applyDir(p, .south, false),
.south => applyDir(p, .north, false),
.east => applyDir(p, .west, false),
.west => applyDir(p, .east, false),
.up => applyDir(p, .down, false),
.down => applyDir(p, .up, false),
else => unreachable,
};
}
return switch (d) {
.north => .{ p[0], p[1] + 1, p[2] },
.south => .{ p[0], p[1] - 1, p[2] },
.east => .{ p[0] + 1, p[1], p[2] },
.west => .{ p[0] - 1, p[1], p[2] },
.up => .{ p[0], p[1], p[2] + 1 },
.down => .{ p[0], p[1], p[2] - 1 },
else => unreachable,
};
}
fn computeRoomId(prev: RoomId, e: Exit, curdir: Exit, new_room_rawtext: []const u8) RoomId {
// mmm pas trop reflechit comment trouver un id unique sachant que ya des racourcis et des bouclages dans tous les sens, mais qu'il y a aussi des pieces repetées (je pense?) ou c'est aumoins sévéremetn non-euclidien.
// donc j'essaye d'utiliser:
// - hash de la desc complete + inventaire pour distinguer deux passages dans la meme piece avec des objets différents.
// - plus un accu de position pour les repèt.
// - plus un forçage des possitions dans certaines salles pour resnapper
const hash = std.hash.Wyhash.hash(0, new_room_rawtext);
const pos: [3]i8 = blk: {
if (std.mem.indexOf(u8, new_room_rawtext, "It must have broken your fall!") != null)
break :blk .{ 0, 0, -1 };
break :blk switch (e) {
.north, .south, .east, .west, .up, .down => applyDir(prev.pos, e, false),
.@"continue", .forward, .run => applyDir(prev.pos, curdir, false),
.back => applyDir(prev.pos, curdir, true),
.doorway, .bridge => applyDir(prev.pos, .north, false),
.passage, .cavern, .ladder, .darkness, .outside, .inside => prev.pos,
.investigate, .wait, .hide => prev.pos,
};
};
return RoomId{ .desc_hash = hash, .pos = pos };
}
fn parseRoom(id: RoomId, text: []const u8, arena: std.mem.Allocator) !RoomDesc {
var it = std.mem.tokenize(u8, text, "\n");
const name = while (it.next()) |line| {
if (tools.match_pattern("== {} ==", line)) |fields| {
break try arena.dupe(u8, fields[0].lit);
} else {
print("ignoring line: {s}\n", .{line});
}
} else return RoomDesc{ .id = id, .name = "null" };
const desc = try arena.dupe(u8, it.next() orelse unreachable);
var objs = std.ArrayList(Object).init(arena);
var inv = std.ArrayList(Object).init(arena);
var exits = std.ArrayList(Exit).init(arena);
section: while (it.next()) |line| {
if (tools.match_pattern("There {} exit", line)) |_| {
var it2 = it;
while (it2.next()) |line2| {
if (tools.match_pattern("- {}", line2)) |fields2| {
const e = tools.nameToEnum(Exit, fields2[0].lit) catch |err| {
print("unknown Exit: '{s}\n", .{fields2[0].lit});
return err;
};
try exits.append(e);
} else {
continue :section;
}
it = it2;
}
} else if (tools.match_pattern("Things of interest here:", line)) |_| {
var it2 = it;
while (it2.next()) |line2| {
if (tools.match_pattern("- {}", line2)) |fields2| {
const o = tools.nameToEnum(Object, fields2[0].lit) catch |err| {
print("unknown Object: '{s}\n", .{fields2[0].lit});
return err;
};
try objs.append(o);
} else {
continue :section;
}
it = it2;
}
} else if (tools.match_pattern("Your inventory:", line)) |_| {
var it2 = it;
while (it2.next()) |line2| {
if (tools.match_pattern("- {}", line2)) |fields2| {
const o = tools.nameToEnum(Object, fields2[0].lit) catch |err| {
print("unknown Object: '{s}\n", .{fields2[0].lit});
return err;
};
try inv.append(o);
} else {
continue :section;
}
it = it2;
}
} else if (tools.match_pattern("What do you do?", line)) |_| {
continue;
} else if (tools.match_pattern("{} a Grue.", line)) |_| {
continue;
} else {
print("ignoring line: {s}\n", .{line});
}
}
return RoomDesc{ .id = id, .name = name, .desc = desc, .objects = objs.items, .exits = exits.items, .inventory = inv.items };
}
};
const SearchState = struct {
room: IFPlayer.RoomId,
dir: IFPlayer.Exit,
vm: VM.State,
};
const TraceStep = union(enum) { go: IFPlayer.Exit, take: IFPlayer.Object, use: IFPlayer.Object, drop: IFPlayer.Object };
const BFS = tools.BestFirstSearch(SearchState, []const TraceStep);
fn abs(x: anytype) usize {
return if (x > 0) @intCast(usize, x) else @intCast(usize, -x);
}
fn maybeQueueNewRoomToExplore(vms: *VM.State, node: BFS.Node, t: TraceStep, rooms: anytype, agenda: *BFS, arena: std.mem.Allocator) !void {
var buf_out: [1024]u8 = undefined;
const out = VM.run(vms, "look\ninv\n", &buf_out);
const dir = blk: {
if (t == .go) {
switch (t.go) {
.north, .south, .east, .west, .up, .down => break :blk t.go,
else => {},
}
}
break :blk node.state.dir; // continue on same dir
};
const id = IFPlayer.computeRoomId(node.state.room, if (t == .go) t.go else .wait, dir, out);
if (abs(id.pos[0]) + abs(id.pos[1]) + abs(id.pos[2]) > 7)
return; // n'explore pas trop loin avec les repet etc..
const entry = try rooms.getOrPut(id);
if (entry.found_existing) return;
//print("nesw room: {s}\n", .{out});
const room = try IFPlayer.parseRoom(id, out, arena);
entry.entry.value = room;
const trace = try arena.alloc(TraceStep, node.trace.len + 1);
std.mem.copy(TraceStep, trace[0..node.trace.len], node.trace);
trace[node.trace.len] = t;
try agenda.insert(BFS.Node{
.cost = node.cost + 1,
.rating = node.rating + switch (t) {
.go => @as(i8, 1),
.use => @as(i8, 1),
.take => @as(i8, 0),
.drop => @as(i8, 10),
},
.trace = trace,
.state = .{ .vm = vms.*, .room = id, .dir = dir },
});
}
fn grepCode(text: []const u8, stdout: std.fs.File.Writer, visited_codes: anytype) !void {
var it = std.mem.tokenize(u8, text, " .,-;:!?\"'\t\n");
// de la forme: "fFHcqYpjxGoi"
next_word: while (it.next()) |word| {
if (word.len < 12) continue :next_word;
for ([_][]const u8{ "bioluminescent", "Headquarters", "dramatically", "unfortunately", "Introduction", "interdimensional", "Interdimensional", "fundamentals", "mathematical", "interactions", "teleportation", "hypothetical", "destinations", "preconfigured", "confirmation", "computationally" }) |notcode| {
if (std.mem.eql(u8, word, notcode)) continue :next_word;
}
if ((try visited_codes.getOrPut(word)).found_existing) continue :next_word;
//print("{s}\n", .{text});
try stdout.print("maybe code: '{s}'\n", .{word});
}
}
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
const stdin = std.io.getStdIn().reader();
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var vm_state = VM.State{
.ip = 0,
.sp = 0,
.regs = undefined,
.mem = undefined,
.stack = undefined,
};
_ = try std.fs.cwd().readFile("synacor/challenge.bin", @ptrCast([*]u8, &vm_state.mem)[0 .. vm_state.mem.len * @sizeOf(VM.Word)]);
var buf_out: [10000]u8 = undefined;
var buf_in: [1024]u8 = undefined;
var visitedcodes = std.StringHashMap(void).init(allocator);
defer visitedcodes.deinit();
if (true) {
print("going to the ruins...\n", .{});
const in = "take tablet\nuse tablet\ndoorway\nnorth\nnorth\nbridge\ncontinue\ndown\neast\ntake empty lantern\nwest\nwest\npassage\nladder\nwest\nsouth\nnorth\ntake can\nwest\nladder\ndarkness\nuse can\nuse lantern\ncontinue\nwest\nwest\nwest\nwest\n";
try grepCode(VM.run(&vm_state, in, &buf_out, null), stdout, &visitedcodes);
}
if (true) {
print("going to the headquarters...\n", .{});
const in = "north\ntake red coin\nnorth\neast\ntake concave coin\ndown\ntake corroded coin\nup\nwest\nwest\nup\ntake shiny coin\ndown\ntake blue coin\neast\nuse blue coin\nuse red coin\nuse shiny coin\nuse concave coin\nuse corroded coin\nnorth\ntake teleporter\nuse teleporter\n";
try grepCode(VM.run(&vm_state, in, &buf_out, null), stdout, &visitedcodes);
}
if (true) {
print("going to the teleport hack...\n", .{});
const in = "take business card\ntake strange book\noutside\n";
try grepCode(VM.run(&vm_state, in, &buf_out, null), stdout, &visitedcodes);
}
const interractive = true;
const bruteforce_teleporter = false; // laisse béton. il faut vraiment decompiler et debugguer
if (interractive) {
var in: []const u8 = "";
var breakpoints = std.ArrayList(u15).init(allocator);
defer breakpoints.deinit();
while (vm_state.ip != null) {
const out = VM.run(&vm_state, in, &buf_out, VM.Debug{ .breakpoints = breakpoints.items, .watchpoints = &[0]u15{} });
try stdout.writeAll(out);
while (true) {
print("[DEBUG] ip={}, sp={} regs={d}\n", .{ vm_state.ip, vm_state.sp, vm_state.regs });
in = (try stdin.readUntilDelimiterOrEof(&buf_in, '\n')) orelse break;
buf_in[in.len] = '\n';
in.len += 1;
if (!std.mem.startsWith(u8, in, "dbg "))
break;
in = in[4..];
if (tools.match_pattern("r{}={}", in)) |fields| {
vm_state.regs[@intCast(u3, fields[0].imm)] = @intCast(u15, fields[1].imm);
} else if (tools.match_pattern("m{}={}", in)) |fields| {
const adr = @intCast(u15, fields[0].imm);
vm_state.mem[adr] = @intCast(u15, fields[1].imm);
} else if (tools.match_pattern("m{}", in)) |fields| {
const adr = @intCast(u15, fields[0].imm);
print("[DEBUG] @{} = {s}\n", .{ adr, VM.dumpArg(vm_state.mem[adr], &buf_out) });
} else if (tools.match_pattern("set bp {}", in)) |fields| {
const adr = @intCast(u15, fields[0].imm);
try breakpoints.append(adr);
} else if (tools.match_pattern("clr bp {}", in)) |fields| {
const adr = @intCast(u15, fields[0].imm);
while (std.mem.indexOfScalar(u15, breakpoints.items, adr)) |idx| {
_ = breakpoints.swapRemove(idx);
}
} else if (tools.match_pattern("stack", in)) |_| {
for (vm_state.stack[0..vm_state.sp]) |v| {
print("[DEBUG] stack = {s}\n", .{VM.dumpArg(v, &buf_out)});
}
} else if (tools.match_pattern("asm {}", in)) |fields| {
var ip = if (fields[0] == .imm) @intCast(u15, fields[0].imm) else vm_state.ip.?;
var nb: u32 = 0;
while (nb < 30) : (nb += 1) {
const insn = VM.fetchInsn(ip, &vm_state.mem);
try stdout.print("[{}]\t{s}\n", .{ ip, VM.dumpInsn(insn.insn, &buf_out) });
ip += @as(u15, 1) + insn.sz;
}
}
in = "";
}
}
} else if (bruteforce_teleporter) {
const all_states = try allocator.alloc(struct { out: [1024]u8, out_len: u16, vms: VM.State }, 32767);
defer allocator.free(all_states);
for (all_states) |*s, i| {
s.vms = vm_state;
s.vms.regs[7] = @intCast(u15, i + 1);
s.out_len = 0;
_ = VM.run(&s.vms, "use teleporter", &buf_out);
}
var yolo: u32 = 10;
var nb_still_running: usize = all_states.len;
while (nb_still_running > 0) {
nb_still_running = 0;
for (all_states) |*s, i| {
const ip = s.vms.ip orelse continue;
nb_still_running += 1;
var in: []const u8 = "\n";
var out: []u8 = s.out[s.out_len..];
const insn = VM.fetchInsn(ip, &s.vms.mem);
s.vms.ip = ip + 1 + insn.sz;
const err = VM.execInsn(&s.vms, insn.insn, &out, &in);
s.out_len = @intCast(u16, s.out.len - out.len);
err catch |e| switch (e) {
error.NeedInput => unreachable,
error.StackOverflow => {
print("OVERFLOW {}...\n", .{i + 1});
print("... {s}\n", .{s.out[0..s.out_len]});
s.vms.ip = null;
yolo -= 1;
},
error.NeedOuput => {
print("interresting {}...\n", .{i + 1});
const msg = VM.run(&s.vms, "", &buf_out);
print("... {s}\n", .{msg});
s.vms.ip = null;
//return;
},
};
}
}
} else {
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();
var rooms = std.AutoHashMap(IFPlayer.RoomId, IFPlayer.RoomDesc).init(allocator);
defer rooms.deinit();
const init_room_id = blk: {
const id = IFPlayer.RoomId{ .desc_hash = 0, .pos = .{ 0, 0, 0 } };
const out = VM.run(&vm_state, "look\ninv\n", &buf_out, null);
//print("init room: {s}\n", .{out});
const room = try IFPlayer.parseRoom(id, out, arena.allocator());
try rooms.put(id, room);
break :blk id;
};
var agenda = BFS.init(allocator);
defer agenda.deinit();
try agenda.insert(BFS.Node{
.cost = 0,
.rating = 0,
.state = .{ .vm = vm_state, .room = init_room_id, .dir = .north },
.trace = &[0]TraceStep{},
});
var longest_trace: []const TraceStep = &[0]TraceStep{};
while (agenda.pop()) |node| {
const room = rooms.get(node.state.room) orelse unreachable;
//if (std.mem.eql(u8, room.name, "Synacor Headquarters")) {
if (false and node.trace.len > longest_trace.len) {
longest_trace = node.trace;
print("longuest trace = ", .{});
for (longest_trace) |t| switch (t) {
.go => print("{s}\\n", .{@tagName(t.go)}),
.use => print("use {s}\\n", .{@tagName(t.use)}),
.take => print("take {s}\\n", .{@tagName(t.take)}),
.drop => print("drop {s}\\n", .{@tagName(t.drop)}),
};
print("\n", .{});
print(" -> leads to == {s} == {s}\n", .{ room.name, room.desc });
print(" -> pos == {d}\n", .{room.id.pos});
print(" -> with {} items in inventory\n", .{room.inventory.len});
break;
}
// print("\n----------------\nexploring '{s}', trace={D}...\n", .{ room.name, node.trace });
for (room.exits) |e| {
if (e == .east and std.mem.eql(u8, room.name, "Ruins") and std.mem.indexOf(u8, room.desc, "A crevice in the rock to the east leads to an alarmingly dark passageway.") != null)
continue; // don't go back in the caves.
// print("trying: go {s}...\n", .{e});
var vms = node.state.vm;
const in = try std.fmt.bufPrint(&buf_in, "go {s}\n", .{@tagName(e)});
const out = VM.run(&vms, in, &buf_out);
try grepCode(out, stdout, &visitedcodes);
//print("out: {s}\n", .{out});
try maybeQueueNewRoomToExplore(&vms, node, .{ .go = e }, &rooms, &agenda, arena.allocator());
}
for (room.objects) |o| {
var vms = node.state.vm;
const in = try std.fmt.bufPrint(&buf_in, "take {s}\nlook {s}\n", .{ @tagName(o), @tagName(o) });
const out = VM.run(&vms, in, &buf_out);
try grepCode(out, stdout, &visitedcodes);
//print("out: {s}\n", .{out});
assert(std.mem.indexOf(u8, out, "You see no such item here.") == null);
try maybeQueueNewRoomToExplore(&vms, node, .{ .take = o }, &rooms, &agenda, arena.allocator());
}
for (room.inventory) |o| {
// if (o == .lantern) continue; // don't use lanter -> don't exit cave
// print("trying: use {s}...\n", .{o});
var vms = node.state.vm;
const in = try std.fmt.bufPrint(&buf_in, "use {s}\nlook {s}\n", .{ @tagName(o), @tagName(o) });
const out = VM.run(&vms, in, &buf_out);
try grepCode(out, stdout, &visitedcodes);
//print("out: {s}\n", .{out});
assert(std.mem.indexOf(u8, out, "You can't find that in your pack.") == null);
try maybeQueueNewRoomToExplore(&vms, node, .{ .use = o }, &rooms, &agenda, arena.allocator());
}
for (room.inventory) |o| {
var vms = node.state.vm;
const in = try std.fmt.bufPrint(&buf_in, "drop {s}\nlook {s}\n", .{ @tagName(o), @tagName(o) });
const out = VM.run(&vms, in, &buf_out);
try grepCode(out, stdout, &visitedcodes);
//print("out: {s}\n", .{out});
assert(std.mem.indexOf(u8, out, "You can't find that in your pack.") == null);
try maybeQueueNewRoomToExplore(&vms, node, .{ .drop = o }, &rooms, &agenda, arena.allocator());
}
}
print("explored {} unique rooms\n", .{rooms.count()});
}
try stdout.print("fin.\n", .{});
} | synacor/main.zig |
const std = @import("std");
const assert = std.debug.assert;
const cpu = @import("cpu.zig");
const memory = @import("memory.zig");
const keyboard = @import("keyboard.zig");
const display = @import("display.zig");
// Clear the display.
pub fn execute_cls(state: *cpu.CPUState) void {
for (state.screen) |*row| {
for (row) |*byte| {
byte.* = 0x0;
}
}
}
// Return from a subroutine.
// The interpreter sets the program counter to the address at the top of the stack,
// then subtracts 1 from the stack pointer.
pub fn execute_ret(state: *cpu.CPUState) void {
assert(state.sp > 0); // Stack Underflow
const nextPC = state.stack[state.sp] + 2;
assert(memory.is_valid_range(nextPC, 2, memory.Usage.Execute));
state.pc = nextPC;
state.sp = if (state.sp > 0) (state.sp - 1) else state.sp;
}
// Jump to a machine code routine at nnn.
// This instruction is only used on the old computers on which Chip-8 was originally implemented.
// NOTE: We choose to ignore it since we don't load any code into system memory.
pub fn execute_sys(state: *cpu.CPUState, address: u16) void {
// noop
}
// Jump to location nnn.
// The interpreter sets the program counter to nnn.
pub fn execute_jp(state: *cpu.CPUState, address: u16) void {
assert((address & 0x0001) == 0); // Unaligned address
assert(memory.is_valid_range(address, 2, memory.Usage.Execute));
state.pc = address;
}
// Call subroutine at nnn.
// The interpreter increments the stack pointer, then puts the current PC on the top of the stack.
// The PC is then set to nnn.
pub fn execute_call(state: *cpu.CPUState, address: u16) void {
assert((address & 0x0001) == 0); // Unaligned address
assert(memory.is_valid_range(address, 2, memory.Usage.Execute));
assert(state.sp < cpu.StackSize); // Stack overflow
state.sp = if (state.sp < cpu.StackSize) (state.sp + 1) else state.sp; // Increment sp
state.stack[state.sp] = state.pc; // Put PC on top of the stack
state.pc = address; // Set PC to new address
}
// Skip next instruction if Vx = kk.
// The interpreter compares register Vx to kk, and if they are equal,
// increments the program counter by 2.
pub fn execute_se(state: *cpu.CPUState, registerName: u8, value: u8) void {
assert((registerName & 0xF0) == 0); // Invalid register
assert(memory.is_valid_range(state.pc, 6, memory.Usage.Execute));
const registerValue = state.vRegisters[registerName];
if (registerValue == value)
state.pc += 4;
}
// Skip next instruction if Vx != kk.
// The interpreter compares register Vx to kk, and if they are not equal,
// increments the program counter by 2.
pub fn execute_sne(state: *cpu.CPUState, registerName: u8, value: u8) void {
const registerValue = state.vRegisters[registerName];
assert((registerName & 0xF0) == 0); // Invalid register
assert(memory.is_valid_range(state.pc, 6, memory.Usage.Execute));
if (registerValue != value)
state.pc += 4;
}
// Skip next instruction if Vx = Vy.
// The interpreter compares register Vx to register Vy, and if they are equal,
// increments the program counter by 2.
pub fn execute_se2(state: *cpu.CPUState, registerLHS: u8, registerRHS: u8) void {
assert((registerLHS & 0xF0) == 0); // Invalid register
assert((registerRHS & 0xF0) == 0); // Invalid register
assert(memory.is_valid_range(state.pc, 6, memory.Usage.Execute));
const registerValueLHS = state.vRegisters[registerLHS];
const registerValueRHS = state.vRegisters[registerRHS];
if (registerValueLHS == registerValueRHS)
state.pc += 4;
}
// Set Vx = kk.
// The interpreter puts the value kk into register Vx.
pub fn execute_ld(state: *cpu.CPUState, registerName: u8, value: u8) void {
assert((registerName & 0xF0) == 0); // Invalid register
state.vRegisters[registerName] = value;
}
// Set Vx = Vx + kk.
// Adds the value kk to the value of register Vx, then stores the result in Vx.
// NOTE: Carry in NOT set.
// NOTE: Overflows will just wrap the value around.
pub fn execute_add(state: *cpu.CPUState, registerName: u8, value: u8) void {
assert((registerName & 0xF0) == 0); // Invalid register
const registerValue = state.vRegisters[registerName];
const sum = registerValue +% value;
state.vRegisters[registerName] = sum;
}
// Set Vx = Vy.
// Stores the value of register Vy in register Vx.
pub fn execute_ld2(state: *cpu.CPUState, registerLHS: u8, registerRHS: u8) void {
assert((registerLHS & 0xF0) == 0); // Invalid register
assert((registerRHS & 0xF0) == 0); // Invalid register
state.vRegisters[registerLHS] = state.vRegisters[registerRHS];
}
// Set Vx = Vx OR Vy.
// Performs a bitwise OR on the values of Vx and Vy, then stores the result in Vx.
// A bitwise OR compares the corrseponding bits from two values, and if either bit is 1,
// then the same bit in the result is also 1. Otherwise, it is 0.
pub fn execute_or(state: *cpu.CPUState, registerLHS: u8, registerRHS: u8) void {
assert((registerLHS & 0xF0) == 0); // Invalid register
assert((registerRHS & 0xF0) == 0); // Invalid register
state.vRegisters[registerLHS] |= state.vRegisters[registerRHS];
}
// Set Vx = Vx AND Vy.
// Performs a bitwise AND on the values of Vx and Vy, then stores the result in Vx.
// A bitwise AND compares the corrseponding bits from two values, and if both bits are 1,
// then the same bit in the result is also 1. Otherwise, it is 0.
pub fn execute_and(state: *cpu.CPUState, registerLHS: u8, registerRHS: u8) void {
assert((registerLHS & 0xF0) == 0); // Invalid register
assert((registerRHS & 0xF0) == 0); // Invalid register
state.vRegisters[registerLHS] &= state.vRegisters[registerRHS];
}
// Set Vx = Vx XOR Vy.
// Performs a bitwise exclusive OR on the values of Vx and Vy, then stores the result in Vx.
// An exclusive OR compares the corrseponding bits from two values, and if the bits are not both the same,
// then the corresponding bit in the result is set to 1. Otherwise, it is 0.
pub fn execute_xor(state: *cpu.CPUState, registerLHS: u8, registerRHS: u8) void {
assert((registerLHS & 0xF0) == 0); // Invalid register
assert((registerRHS & 0xF0) == 0); // Invalid register
state.vRegisters[registerLHS] = state.vRegisters[registerLHS] ^ state.vRegisters[registerRHS];
}
// Set Vx = Vx + Vy, set VF = carry.
// The values of Vx and Vy are added together.
// If the result is greater than 8 bits (i.e., > 255,) VF is set to 1, otherwise 0.
// Only the lowest 8 bits of the result are kept, and stored in Vx.
pub fn execute_add2(state: *cpu.CPUState, registerLHS: u8, registerRHS: u8) void {
assert((registerLHS & 0xF0) == 0); // Invalid register
assert((registerRHS & 0xF0) == 0); // Invalid register
const valueLHS = state.vRegisters[registerLHS];
const valueRHS = state.vRegisters[registerRHS];
const result = valueLHS +% valueRHS;
state.vRegisters[registerLHS] = result;
state.vRegisters[@enumToInt(cpu.Register.VF)] = if (result > valueLHS) 0 else 1; // Set carry
}
// Set Vx = Vx - Vy, set VF = NOT borrow.
// If Vx > Vy, then VF is set to 1, otherwise 0.
// Then Vy is subtracted from Vx, and the results stored in Vx.
pub fn execute_sub(state: *cpu.CPUState, registerLHS: u8, registerRHS: u8) void {
assert((registerLHS & 0xF0) == 0); // Invalid register
assert((registerRHS & 0xF0) == 0); // Invalid register
const valueLHS = state.vRegisters[registerLHS];
const valueRHS = state.vRegisters[registerRHS];
const result = valueLHS -% valueRHS;
state.vRegisters[registerLHS] = result;
state.vRegisters[@enumToInt(cpu.Register.VF)] = if (valueLHS > valueRHS) 1 else 0; // Set carry
}
// Set Vx = Vx SHR 1.
// If the least-significant bit of Vx is 1, then VF is set to 1, otherwise 0.
// Then Vx is divided by 2.
// NOTE: registerRHS is just ignored apparently.
pub fn execute_shr1(state: *cpu.CPUState, registerLHS: u8, registerRHS: u8) void {
assert((registerLHS & 0xF0) == 0); // Invalid register
assert((registerRHS & 0xF0) == 0); // Invalid register
const valueLHS = state.vRegisters[registerLHS];
state.vRegisters[registerLHS] = valueLHS >> 1;
state.vRegisters[@enumToInt(cpu.Register.VF)] = valueLHS & 0x01; // Set carry
}
// Set Vx = Vy - Vx, set VF = NOT borrow.
// If Vy > Vx, then VF is set to 1, otherwise 0.
// Then Vx is subtracted from Vy, and the results stored in Vx.
pub fn execute_subn(state: *cpu.CPUState, registerLHS: u8, registerRHS: u8) void {
assert((registerLHS & 0xF0) == 0); // Invalid register
assert((registerRHS & 0xF0) == 0); // Invalid register
const valueLHS = state.vRegisters[registerLHS];
const valueRHS = state.vRegisters[registerRHS];
const result = valueRHS -% valueLHS;
state.vRegisters[registerLHS] = result;
state.vRegisters[@enumToInt(cpu.Register.VF)] = if (valueRHS > valueLHS) 1 else 0; // Set carry
}
// Set Vx = Vx SHL 1.
// If the most-significant bit of Vx is 1, then VF is set to 1, otherwise to 0. Then Vx is multiplied by 2.
// NOTE: registerRHS is just ignored apparently.
pub fn execute_shl1(state: *cpu.CPUState, registerLHS: u8, registerRHS: u8) void {
assert((registerLHS & 0xF0) == 0); // Invalid register
assert((registerRHS & 0xF0) == 0); // Invalid register
const valueLHS = state.vRegisters[registerLHS];
state.vRegisters[registerLHS] = valueLHS << 1;
state.vRegisters[@enumToInt(cpu.Register.VF)] = if ((valueLHS & 0x80) > 0) 1 else 0; // Set carry
}
// Skip next instruction if Vx != Vy.
// The values of Vx and Vy are compared, and if they are not equal, the program counter is increased by 2.
pub fn execute_sne2(state: *cpu.CPUState, registerLHS: u8, registerRHS: u8) void {
assert((registerLHS & 0xF0) == 0); // Invalid register
assert((registerRHS & 0xF0) == 0); // Invalid register
assert(memory.is_valid_range(state.pc, 6, memory.Usage.Execute));
const valueLHS = state.vRegisters[registerLHS];
const valueRHS = state.vRegisters[registerRHS];
if (valueLHS != valueRHS)
state.pc += 4;
}
// Set I = nnn.
// The value of register I is set to nnn.
pub fn execute_ldi(state: *cpu.CPUState, address: u16) void {
state.i = address;
}
// Jump to location nnn + V0.
// The program counter is set to nnn plus the value of V0.
pub fn execute_jp2(state: *cpu.CPUState, baseAddress: u16) void {
const offset: u16 = state.vRegisters[@enumToInt(cpu.Register.V0)];
const targetAddress = baseAddress + offset;
assert((targetAddress & 0x0001) == 0); // Unaligned address
assert(memory.is_valid_range(targetAddress, 2, memory.Usage.Execute));
state.pc = targetAddress;
}
// Set Vx = random byte AND kk.
// The interpreter generates a random number from 0 to 255, which is then ANDed with the value kk.
// The results are stored in Vx. See instruction 8xy2 for more information on AND.
pub fn execute_rnd(state: *cpu.CPUState, registerName: u8, value: u8) void {
assert((registerName & 0xF0) == 0); // Invalid register
const seed: u64 = 0x42;
var rng = std.rand.DefaultPrng.init(seed);
const randomValue = rng.random.int(u8);
state.vRegisters[registerName] = randomValue & value;
}
// Display n-byte sprite starting at memory location I at (Vx, Vy), set VF = collision.
// The interpreter reads n bytes from memory, starting at the address stored in I.
// These bytes are then displayed as sprites on screen at coordinates (Vx, Vy).
// Sprites are XORed onto the existing screen. If this causes any pixels to be erased, VF is set to 1,
// otherwise it is set to 0.
// If the sprite is positioned so part of it is outside the coordinates of the display,
// it wraps around to the opposite side of the screen. See instruction 8xy3 for more information on XOR,
// and section 2.4, Display, for more information on the Chip-8 screen and sprites.
pub fn execute_drw(state: *cpu.CPUState, registerLHS: u8, registerRHS: u8, size: u8) void {
assert((registerLHS & 0xF0) == 0); // Invalid register
assert((registerRHS & 0xF0) == 0); // Invalid register
assert(memory.is_valid_range(state.i, size, memory.Usage.Read));
const spriteStartX: u32 = state.vRegisters[registerLHS];
const spriteStartY: u32 = state.vRegisters[registerRHS];
var collision = false;
// Sprites are made of rows of 1 byte each.
for (state.memory[state.i .. state.i + size]) |spriteRow, rowIndex| {
const screenY: u32 = (spriteStartY + @intCast(u32, rowIndex)) % cpu.ScreenHeight;
var pixelIndex: u32 = 0;
while (pixelIndex < 8) {
const spritePixelValue = (spriteRow >> (7 - @intCast(u3, pixelIndex))) & 0x1;
const screenX = (spriteStartX + pixelIndex) % cpu.ScreenWidth;
const screenPixelValue = display.read_screen_pixel(state, screenX, screenY);
const result = screenPixelValue ^ spritePixelValue;
// A pixel was erased
if (screenPixelValue > 0 and result != 0)
collision = true;
display.write_screen_pixel(state, screenX, screenY, result);
pixelIndex += 1;
}
}
state.vRegisters[@enumToInt(cpu.Register.VF)] = if (collision) 1 else 0;
}
// Skip next instruction if key with the value of Vx is pressed.
// Checks the keyboard, and if the key corresponding to the value of Vx is currently in the down position,
// PC is increased by 2.
pub fn execute_skp(state: *cpu.CPUState, registerName: u8) void {
assert((registerName & 0xF0) == 0); // Invalid register
assert(memory.is_valid_range(state.pc, 6, memory.Usage.Execute));
const keyID = state.vRegisters[registerName];
if (keyboard.is_key_pressed(state, keyID))
state.pc += 4;
}
// Skip next instruction if key with the value of Vx is not pressed.
// Checks the keyboard, and if the key corresponding to the value of Vx is currently in the up position,
// PC is increased by 2.
pub fn execute_sknp(state: *cpu.CPUState, registerName: u8) void {
assert((registerName & 0xF0) == 0); // Invalid register
assert(memory.is_valid_range(state.pc, 6, memory.Usage.Execute));
const key = state.vRegisters[registerName];
if (!keyboard.is_key_pressed(state, key))
state.pc += 4;
}
// Set Vx = delay timer value.
// The value of DT is placed into Vx.
pub fn execute_ldt(state: *cpu.CPUState, registerName: u8) void {
assert((registerName & 0xF0) == 0); // Invalid register
state.vRegisters[registerName] = state.delayTimer;
}
// Wait for a key press, store the value of the key in Vx.
// All execution stops until a key is pressed, then the value of that key is stored in Vx.
pub fn execute_ldk(state: *cpu.CPUState, registerName: u8) void {
assert((registerName & 0xF0) == 0); // Invalid register
// If we enter for the first time, set the waiting flag.
if (!state.isWaitingForKey) {
state.isWaitingForKey = true;
} else {
const keyStatePressMask = ~state.keyStatePrev & state.keyState;
// When waiting, check the key states.
if (keyStatePressMask > 0) {
state.vRegisters[registerName] = keyboard.get_key_pressed(keyStatePressMask);
state.isWaitingForKey = false;
}
}
}
// Set delay timer = Vx.
// DT is set equal to the value of Vx.
pub fn execute_lddt(state: *cpu.CPUState, registerName: u8) void {
assert((registerName & 0xF0) == 0); // Invalid register
state.delayTimer = state.vRegisters[registerName];
}
// Set sound timer = Vx.
// ST is set equal to the value of Vx.
pub fn execute_ldst(state: *cpu.CPUState, registerName: u8) void {
assert((registerName & 0xF0) == 0); // Invalid register
state.soundTimer = state.vRegisters[registerName];
}
// Set I = I + Vx.
// The values of I and Vx are added, and the results are stored in I.
// NOTE: Carry in NOT set.
// NOTE: Overflows will just wrap the value around.
pub fn execute_addi(state: *cpu.CPUState, registerName: u8) void {
assert((registerName & 0xF0) == 0); // Invalid register
const registerValue: u16 = state.vRegisters[registerName];
const sum = state.i +% registerValue;
assert(sum >= state.i); // Overflow
state.i = sum;
}
// Set I = location of sprite for digit Vx.
// The value of I is set to the location for the hexadecimal sprite corresponding to the value of Vx.
// See section 2.4, Display, for more information on the Chip-8 hexadecimal font.
pub fn execute_ldf(state: *cpu.CPUState, registerName: u8) void {
assert((registerName & 0xF0) == 0); // Invalid register
const glyphIndex = state.vRegisters[registerName];
assert((glyphIndex & 0xF0) == 0); // Invalid index
state.i = state.fontTableOffsets[glyphIndex];
}
// Store BCD representation of Vx in memory locations I, I+1, and I+2.
// The interpreter takes the decimal value of Vx, and places the hundreds digit in memory at location in I,
// the tens digit at location I+1, and the ones digit at location I+2.
pub fn execute_ldb(state: *cpu.CPUState, registerName: u8) void {
assert((registerName & 0xF0) == 0); // Invalid register
assert(memory.is_valid_range(state.i, 3, memory.Usage.Write));
const registerValue = state.vRegisters[registerName];
state.memory[state.i + 0] = (registerValue / 100) % 10;
state.memory[state.i + 1] = (registerValue / 10) % 10;
state.memory[state.i + 2] = (registerValue) % 10;
}
// Store registers V0 through Vx in memory starting at location I.
// The interpreter copies the values of registers V0 through Vx into memory,
// starting at the address in I.
pub fn execute_ldai(state: *cpu.CPUState, registerName: u8) void {
const registerIndexMax = registerName;
assert((registerIndexMax & 0xF0) == 0); // Invalid register
assert(memory.is_valid_range(state.i, registerIndexMax + 1, memory.Usage.Write));
for (state.vRegisters[0 .. registerIndexMax + 1]) |reg, index| {
state.memory[state.i + index] = reg;
}
}
// Read registers V0 through Vx from memory starting at location I.
// The interpreter reads values from memory starting at location I into registers V0 through Vx.
pub fn execute_ldm(state: *cpu.CPUState, registerName: u8) void {
const registerIndexMax = registerName;
assert((registerIndexMax & 0xF0) == 0); // Invalid register
assert(memory.is_valid_range(state.i, registerIndexMax + 1, memory.Usage.Read));
for (state.memory[state.i .. state.i + registerIndexMax + 1]) |byte, index| {
state.vRegisters[index] = byte;
}
} | src/chip8/instruction.zig |
const std = @import("std");
const c = @import("c.zig");
const pem = @import("pem.zig");
pub const RsaPublicKey = struct {
allocator: std.mem.Allocator,
key: c.br_rsa_public_key,
const Self = @This();
pub fn init(key: *const c.br_rsa_public_key, allocator: std.mem.Allocator) !Self
{
var self = Self {
.allocator = allocator,
.key = undefined,
};
try copyRsaPublicKey(&self.key, key, allocator);
return self;
}
pub fn deinit(self: Self) void
{
freeRsaPublicKey(self.key, self.allocator);
}
};
pub const EcPublicKey = struct {
allocator: std.mem.Allocator,
key: c.br_ec_public_key,
const Self = @This();
pub fn init(key: *const c.br_ec_public_key, allocator: std.mem.Allocator) !Self
{
var self = Self {
.allocator = allocator,
.key = undefined,
};
try copyEcPublicKey(&self.key, key, allocator);
return self;
}
pub fn deinit(self: Self) void
{
freeEcPublicKey(self.key, self.allocator);
}
};
pub fn copyRsaPublicKey(
dst: *c.br_rsa_public_key,
src: *const c.br_rsa_public_key,
allocator: std.mem.Allocator) !void
{
try copyBytes(&dst.n, src.n, src.nlen, allocator);
dst.nlen = src.nlen;
try copyBytes(&dst.e, src.e, src.elen, allocator);
dst.elen = src.elen;
}
pub fn freeRsaPublicKey(key: c.br_rsa_public_key, allocator: std.mem.Allocator) void
{
allocator.free(key.n[0..key.nlen]);
allocator.free(key.e[0..key.elen]);
}
pub fn copyEcPublicKey(
dst: *c.br_ec_public_key,
src: *const c.br_ec_public_key,
allocator: std.mem.Allocator) !void
{
dst.curve = src.curve;
try copyBytes(&dst.q, src.q, src.qlen, allocator);
dst.qlen = src.qlen;
}
pub fn freeEcPublicKey(key: c.br_ec_public_key, allocator: std.mem.Allocator) void
{
allocator.free(key.q[0..key.qlen]);
}
pub fn copyPublicKey(
dst: *c.br_x509_pkey,
src: *const c.br_x509_pkey,
allocator: std.mem.Allocator) !void
{
dst.key_type = src.key_type;
switch (dst.key_type) {
c.BR_KEYTYPE_RSA => {
try copyRsaPublicKey(&dst.key.rsa, &src.key.rsa, allocator);
},
c.BR_KEYTYPE_EC => {
try copyEcPublicKey(&dst.key.ec, &src.key.ec, allocator);
},
else => return error.BadKeyType,
}
}
pub fn freePublicKey(key: c.br_x509_pkey, allocator: std.mem.Allocator) void
{
switch (key.key_type) {
c.BR_KEYTYPE_RSA => {
freeRsaPublicKey(key.key.rsa, allocator);
},
c.BR_KEYTYPE_EC => {
freeEcPublicKey(key.key.ec, allocator);
},
else => {},
}
}
fn copyBytes(dst: *[*c]u8, src: [*]const u8, len: usize, allocator: std.mem.Allocator) !void
{
const srcSlice = src[0..len];
const copy = try allocator.dupe(u8, srcSlice);
dst.* = ©[0];
}
fn freeBytes(ptr: [*]const u8, len: usize, allocator: std.mem.Allocator) void
{
const slice = ptr[0..len];
allocator.free(slice);
}
/// Only supports RSA for now
pub const PrivateKey = struct {
rsaKey: c.br_rsa_private_key,
const Self = @This();
pub fn initFromPem(pemData: []const u8, allocator: std.mem.Allocator) !Self
{
var self = Self {
.rsaKey = undefined,
};
var context: c.br_skey_decoder_context = undefined;
c.br_skey_decoder_init(&context);
var pemState = PemState {
.context = &context,
.pushed = false,
};
try pem.decode(pemData, *PemState, &pemState, pemCallback, allocator);
const err = c.br_skey_decoder_last_error(&context);
if (err != 0) {
return error.DecoderError;
}
const keyType = c.br_skey_decoder_key_type(&context);
switch (keyType) {
c.BR_KEYTYPE_RSA => {
const rsaKey = c.br_skey_decoder_get_rsa(&context);
try copyRsaPrivateKey(&self.rsaKey, rsaKey, allocator);
},
c.BR_KEYTYPE_EC => return error.UnsupportedEcKeyType,
else => return error.BadKeyType,
}
return self;
}
pub fn deinit(self: Self, allocator: std.mem.Allocator) void
{
freeRsaPrivateKey(self.rsaKey, allocator);
}
};
pub fn copyRsaPrivateKey(
dst: *c.br_rsa_private_key,
src: *const c.br_rsa_private_key,
allocator: std.mem.Allocator) !void
{
dst.n_bitlen = src.n_bitlen;
try copyBytes(&dst.p, src.p, src.plen, allocator);
dst.plen = src.plen;
try copyBytes(&dst.q, src.q, src.qlen, allocator);
dst.qlen = src.qlen;
try copyBytes(&dst.dp, src.dp, src.dplen, allocator);
dst.dplen = src.dplen;
try copyBytes(&dst.dq, src.dq, src.dqlen, allocator);
dst.dqlen = src.dqlen;
try copyBytes(&dst.iq, src.iq, src.iqlen, allocator);
dst.iqlen = src.iqlen;
}
pub fn freeRsaPrivateKey(key: c.br_rsa_private_key, allocator: std.mem.Allocator) void
{
allocator.free(key.p[0..key.plen]);
allocator.free(key.q[0..key.qlen]);
allocator.free(key.dp[0..key.dplen]);
allocator.free(key.dq[0..key.dqlen]);
allocator.free(key.iq[0..key.iqlen]);
}
const PemState = struct {
context: *c.br_skey_decoder_context,
pushed: bool,
};
fn pemCallback(state: *PemState, data: []const u8) !void
{
c.br_skey_decoder_push(state.context, &data[0], data.len);
} | src/key.zig |
const std = @import("std");
const assert = std.debug.assert;
const os = @import("windows/windows.zig");
const dxgi = @import("windows/dxgi.zig");
const d3d12 = @import("windows/d3d12.zig");
const d2d1 = @import("windows/d2d1.zig");
const dwrite = @import("windows/dwrite.zig");
const dcommon = @import("windows/dcommon.zig");
const gr = @import("graphics.zig");
usingnamespace @import("math.zig");
const window_num_samples = 8;
const Vertex = struct {
position: [3]f32,
normal: [3]f32,
texcoord: [2]f32,
};
const Triangle = struct {
index0: u32,
index1: u32,
index2: u32,
};
comptime {
assert(@sizeOf(Vertex) == 32 and @alignOf(Vertex) == 4);
assert(@sizeOf(Triangle) == 12 and @alignOf(Triangle) == 4);
}
const Mesh = struct {
start_index_location: u32,
base_vertex_location: u32,
num_indices: u32,
};
const Entity = struct {
mesh: Mesh,
id: u32,
position: Vec3,
color: u32,
};
const DemoState = struct {
dx: gr.DxContext,
frame_stats: FrameStats,
srgb_texture: gr.ResourceHandle,
depth_texture: gr.ResourceHandle,
lightmap_texture: gr.ResourceHandle,
vertex_buffer: gr.ResourceHandle,
index_buffer: gr.ResourceHandle,
entity_buffer: gr.ResourceHandle,
srgb_texture_rtv: d3d12.CPU_DESCRIPTOR_HANDLE,
depth_texture_dsv: d3d12.CPU_DESCRIPTOR_HANDLE,
lightmap_texture_srv: d3d12.CPU_DESCRIPTOR_HANDLE,
vertex_buffer_srv: d3d12.CPU_DESCRIPTOR_HANDLE,
index_buffer_srv: d3d12.CPU_DESCRIPTOR_HANDLE,
entity_buffer_srv: d3d12.CPU_DESCRIPTOR_HANDLE,
pipelines: std.ArrayList(gr.PipelineHandle),
entities: std.ArrayList(Entity),
brush: *d2d1.ISolidColorBrush,
text_format: *dwrite.ITextFormat,
camera: struct {
position: Vec3,
pitch: Scalar,
yaw: Scalar,
forward: Vec3 = vec3.init(0.0, 0.0, 0.0),
},
mouse: struct {
cursor_prev_x: i32 = 0,
cursor_prev_y: i32 = 0,
} = .{},
fn init(allocator: *std.mem.Allocator, window: os.HWND) DemoState {
var dx = gr.DxContext.init(allocator, window);
var srgb_texture: gr.ResourceHandle = undefined;
var depth_texture: gr.ResourceHandle = undefined;
var srgb_texture_rtv: d3d12.CPU_DESCRIPTOR_HANDLE = undefined;
var depth_texture_dsv: d3d12.CPU_DESCRIPTOR_HANDLE = undefined;
initRenderTarget(&dx, &srgb_texture, &depth_texture, &srgb_texture_rtv, &depth_texture_dsv);
var pipelines = std.ArrayList(gr.PipelineHandle).init(allocator);
initDx12Pipelines(&dx, &pipelines);
var brush: *d2d1.ISolidColorBrush = undefined;
var text_format: *dwrite.ITextFormat = undefined;
init2dResources(dx, &brush, &text_format);
dx.beginFrame();
var meshes = std.ArrayList(Mesh).init(allocator);
defer meshes.deinit();
var vertex_buffer: gr.ResourceHandle = undefined;
var index_buffer: gr.ResourceHandle = undefined;
var vertex_buffer_srv: d3d12.CPU_DESCRIPTOR_HANDLE = undefined;
var index_buffer_srv: d3d12.CPU_DESCRIPTOR_HANDLE = undefined;
initMeshes(
&dx,
&meshes,
&vertex_buffer,
&index_buffer,
&vertex_buffer_srv,
&index_buffer_srv,
);
var entities = std.ArrayList(Entity).init(allocator);
var entity_buffer: gr.ResourceHandle = undefined;
var entity_buffer_srv: d3d12.CPU_DESCRIPTOR_HANDLE = undefined;
initEntities(&dx, meshes.items, &entities, &entity_buffer, &entity_buffer_srv);
var lightmap_texture: gr.ResourceHandle = undefined;
var lightmap_texture_srv: d3d12.CPU_DESCRIPTOR_HANDLE = undefined;
dx.createTextureFromFile("data/level1_ao.png", 1, &lightmap_texture, &lightmap_texture_srv);
dx.addTransitionBarrier(lightmap_texture, .{ .PIXEL_SHADER_RESOURCE = true });
dx.addTransitionBarrier(vertex_buffer, .{ .NON_PIXEL_SHADER_RESOURCE = true });
dx.addTransitionBarrier(index_buffer, .{ .NON_PIXEL_SHADER_RESOURCE = true });
dx.flushResourceBarriers();
dx.closeAndExecuteCommandList();
dx.waitForGpu();
return DemoState{
.dx = dx,
.srgb_texture = srgb_texture,
.srgb_texture_rtv = srgb_texture_rtv,
.depth_texture = depth_texture,
.depth_texture_dsv = depth_texture_dsv,
.lightmap_texture = lightmap_texture,
.lightmap_texture_srv = lightmap_texture_srv,
.vertex_buffer = vertex_buffer,
.index_buffer = index_buffer,
.entity_buffer = entity_buffer,
.vertex_buffer_srv = vertex_buffer_srv,
.index_buffer_srv = index_buffer_srv,
.entity_buffer_srv = entity_buffer_srv,
.pipelines = pipelines,
.entities = entities,
.brush = brush,
.text_format = text_format,
.frame_stats = FrameStats.init(),
.camera = .{
.position = vec3.init(0.0, 8.0, -8.0),
.pitch = math.pi / 4.0,
.yaw = 0.0,
},
};
}
fn deinit(self: *DemoState) void {
self.dx.waitForGpu();
self.entities.deinit();
for (self.pipelines.items) |pso| {
_ = self.dx.releasePipeline(pso);
}
self.pipelines.deinit();
os.releaseCom(&self.brush);
os.releaseCom(&self.text_format);
_ = self.dx.releaseResource(self.vertex_buffer);
_ = self.dx.releaseResource(self.index_buffer);
_ = self.dx.releaseResource(self.entity_buffer);
_ = self.dx.releaseResource(self.srgb_texture);
_ = self.dx.releaseResource(self.depth_texture);
_ = self.dx.releaseResource(self.lightmap_texture);
self.dx.deinit();
self.* = undefined;
}
fn update(self: *DemoState) void {
self.frame_stats.update();
// Handle camera rotation with mouse.
{
var pos: os.POINT = undefined;
_ = os.GetCursorPos(&pos);
const delta_x = @intToFloat(Scalar, pos.x - self.mouse.cursor_prev_x);
const delta_y = @intToFloat(Scalar, pos.y - self.mouse.cursor_prev_y);
self.mouse.cursor_prev_x = pos.x;
self.mouse.cursor_prev_y = pos.y;
if (os.GetAsyncKeyState(os.VK_RBUTTON) < 0) {
self.camera.pitch += 0.0025 * delta_y;
self.camera.yaw += 0.0025 * delta_x;
self.camera.pitch = math.clamp(self.camera.pitch, -math.pi * 0.48, math.pi * 0.48);
self.camera.yaw = scalar.modAngle(self.camera.yaw);
}
}
// Handle camera movement with 'WASD' keys.
{
const transform = mat4.mul(
mat4.initRotationX(self.camera.pitch),
mat4.initRotationY(self.camera.yaw),
);
const forward = vec3.normalize(vec3.transform(vec3.init(0.0, 0.0, 1.0), transform));
const right = vec3.normalize(vec3.cross(vec3.init(0.0, 1.0, 0.0), forward));
self.camera.forward = forward;
const delta_forward = vec3.scale(forward, 10.0 * self.frame_stats.delta_time);
const delta_right = vec3.scale(right, 10.0 * self.frame_stats.delta_time);
if (os.GetAsyncKeyState('W') < 0) {
self.camera.position = vec3.add(self.camera.position, delta_forward);
} else if (os.GetAsyncKeyState('S') < 0) {
self.camera.position = vec3.sub(self.camera.position, delta_forward);
}
if (os.GetAsyncKeyState('D') < 0) {
self.camera.position = vec3.add(self.camera.position, delta_right);
} else if (os.GetAsyncKeyState('A') < 0) {
self.camera.position = vec3.sub(self.camera.position, delta_right);
}
}
self.draw();
}
fn draw(self: *DemoState) void {
var dx = &self.dx;
dx.beginFrame();
// Upload camera transform.
{
const upload = dx.allocateUploadBufferRegion(Mat4, 1);
upload.cpu_slice[0] = mat4.transpose(
mat4.mul(
mat4.initLookAt(
self.camera.position,
vec3.add(self.camera.position, self.camera.forward),
vec3.init(0.0, 1.0, 0.0),
),
mat4.initPerspective(
math.pi / 3.0,
@intToFloat(Scalar, dx.viewport_width) / @intToFloat(Scalar, dx.viewport_height),
0.1,
100.0,
),
),
);
dx.cmdlist.CopyBufferRegion(
dx.getResource(self.entity_buffer),
0,
upload.buffer,
upload.buffer_offset,
upload.cpu_slice.len * @sizeOf(Mat4),
);
}
dx.addTransitionBarrier(self.srgb_texture, .{ .RENDER_TARGET = true });
dx.addTransitionBarrier(self.entity_buffer, .{ .NON_PIXEL_SHADER_RESOURCE = true });
dx.flushResourceBarriers();
dx.cmdlist.OMSetRenderTargets(
1,
&[_]d3d12.CPU_DESCRIPTOR_HANDLE{self.srgb_texture_rtv},
os.TRUE,
&self.depth_texture_dsv,
);
dx.cmdlist.ClearRenderTargetView(
self.srgb_texture_rtv,
&[4]f32{ 0.2, 0.4, 0.8, 1.0 },
0,
null,
);
dx.cmdlist.ClearDepthStencilView(self.depth_texture_dsv, .{ .DEPTH = true }, 1.0, 0.0, 0, null);
dx.cmdlist.IASetPrimitiveTopology(.TRIANGLELIST);
dx.setPipelineState(self.pipelines.items[0]);
dx.cmdlist.SetGraphicsRootDescriptorTable(1, blk: {
const base = dx.copyDescriptorsToGpuHeap(1, self.vertex_buffer_srv);
_ = dx.copyDescriptorsToGpuHeap(1, self.index_buffer_srv);
_ = dx.copyDescriptorsToGpuHeap(1, self.entity_buffer_srv);
break :blk base;
});
dx.cmdlist.SetGraphicsRootDescriptorTable(2, blk: {
const base = dx.copyDescriptorsToGpuHeap(1, self.lightmap_texture_srv);
break :blk base;
});
for (self.entities.items) |entity| {
dx.cmdlist.SetGraphicsRoot32BitConstants(0, 3, &[_]u32{
entity.mesh.start_index_location,
entity.mesh.base_vertex_location,
entity.id,
}, 0);
dx.cmdlist.DrawInstanced(entity.mesh.num_indices, 1, 0, 0);
}
const back_buffer = dx.getBackBuffer();
dx.addTransitionBarrier(back_buffer.resource_handle, .{ .RESOLVE_DEST = true });
dx.addTransitionBarrier(self.srgb_texture, .{ .RESOLVE_SOURCE = true });
dx.addTransitionBarrier(self.entity_buffer, .{ .COPY_DEST = true });
dx.flushResourceBarriers();
dx.cmdlist.ResolveSubresource(
dx.getResource(back_buffer.resource_handle),
0,
dx.getResource(self.srgb_texture),
0,
.R8G8B8A8_UNORM,
);
dx.addTransitionBarrier(back_buffer.resource_handle, .{ .RENDER_TARGET = true });
dx.flushResourceBarriers();
dx.closeAndExecuteCommandList();
dx.beginDraw2d();
dx.d2d.context.SetTransform(&dcommon.MATRIX_3X2_F.identity());
{
var buffer: [128]u8 = undefined;
const text = std.fmt.bufPrint(
buffer[0..],
"FPS: {d:.1}\nCPU time: {d:.3} ms",
.{ self.frame_stats.fps, self.frame_stats.average_cpu_time },
) catch unreachable;
self.brush.SetColor(&d2d1.COLOR_F.Black);
dx.d2d.context.DrawTextSimple(
text,
self.text_format,
&dcommon.RECT_F{
.left = 0.0,
.top = 0.0,
.right = @intToFloat(f32, dx.viewport_width),
.bottom = @intToFloat(f32, dx.viewport_height),
},
@ptrCast(*d2d1.IBrush, self.brush),
);
}
dx.endDraw2d();
dx.endFrame();
}
fn initMeshes(
dx: *gr.DxContext,
meshes: *std.ArrayList(Mesh),
vertex_buffer: *gr.ResourceHandle,
index_buffer: *gr.ResourceHandle,
vertex_buffer_srv: *d3d12.CPU_DESCRIPTOR_HANDLE,
index_buffer_srv: *d3d12.CPU_DESCRIPTOR_HANDLE,
) void {
const max_num_vertices = 10_000;
const max_num_triangles = 10_000;
vertex_buffer.* = dx.createCommittedResource(
.DEFAULT,
.{},
&d3d12.RESOURCE_DESC.buffer(max_num_vertices * @sizeOf(Vertex)),
.{ .COPY_DEST = true },
null,
);
index_buffer.* = dx.createCommittedResource(
.DEFAULT,
.{},
&d3d12.RESOURCE_DESC.buffer(max_num_triangles * @sizeOf(Triangle)),
.{ .COPY_DEST = true },
null,
);
vertex_buffer_srv.* = dx.allocateCpuDescriptors(.CBV_SRV_UAV, 1);
dx.device.CreateShaderResourceView(
dx.getResource(vertex_buffer.*),
&d3d12.SHADER_RESOURCE_VIEW_DESC.structuredBuffer(0, max_num_vertices, @sizeOf(Vertex)),
vertex_buffer_srv.*,
);
index_buffer_srv.* = dx.allocateCpuDescriptors(.CBV_SRV_UAV, 1);
dx.device.CreateShaderResourceView(
dx.getResource(index_buffer.*),
&d3d12.SHADER_RESOURCE_VIEW_DESC.typedBuffer(.R32_UINT, 0, 3 * max_num_triangles),
index_buffer_srv.*,
);
//const mesh_names = [_][]const u8{ "cube", "sphere" };
const mesh_names = [_][]const u8{"level1_map"};
var start_index_location: u32 = 0;
var base_vertex_location: u32 = 0;
for (mesh_names) |mesh_name, mesh_idx| {
var buf: [256]u8 = undefined;
const path = std.fmt.bufPrint(
buf[0..],
"{}/data/{}.ply",
.{ std.fs.selfExeDirPath(buf[0..]), mesh_name },
) catch unreachable;
var ply = MeshLoader.init(path);
defer ply.deinit();
const upload_verts = dx.allocateUploadBufferRegion(Vertex, ply.num_vertices);
const upload_tris = dx.allocateUploadBufferRegion(Triangle, ply.num_triangles);
ply.load(upload_verts.cpu_slice, upload_tris.cpu_slice);
dx.cmdlist.CopyBufferRegion(
dx.getResource(vertex_buffer.*),
base_vertex_location * @sizeOf(Vertex),
upload_verts.buffer,
upload_verts.buffer_offset,
upload_verts.cpu_slice.len * @sizeOf(Vertex),
);
dx.cmdlist.CopyBufferRegion(
dx.getResource(index_buffer.*),
start_index_location * @sizeOf(u32),
upload_tris.buffer,
upload_tris.buffer_offset,
upload_tris.cpu_slice.len * @sizeOf(Triangle),
);
meshes.append(Mesh{
.num_indices = ply.num_triangles * 3,
.start_index_location = start_index_location,
.base_vertex_location = base_vertex_location,
}) catch unreachable;
start_index_location += ply.num_triangles * 3;
base_vertex_location += ply.num_vertices;
}
}
fn initEntities(
dx: *gr.DxContext,
meshes: []Mesh,
entities: *std.ArrayList(Entity),
entity_buffer: *gr.ResourceHandle,
entity_buffer_srv: *d3d12.CPU_DESCRIPTOR_HANDLE,
) void {
if (false) {
var buf: [256]u8 = undefined;
const path = std.fmt.bufPrint(
buf[0..],
"{}/data/map.ppm",
.{std.fs.selfExeDirPath(buf[0..])},
) catch unreachable;
const file = std.fs.openFileAbsolute(path, .{ .read = true }) catch unreachable;
defer file.close();
// Line 1.
const reader = file.reader();
if (reader.readUntilDelimiterOrEof(buf[0..], '\n') catch unreachable) |line| {
assert(std.mem.eql(u8, "P6", line));
}
// Line 2.
var map_width: u32 = 0;
var map_height: u32 = 0;
if (reader.readUntilDelimiterOrEof(buf[0..], '\n') catch unreachable) |line| {
var it = std.mem.split(line, " ");
map_width = std.fmt.parseInt(u32, it.next().?, 10) catch unreachable;
map_height = std.fmt.parseInt(u32, it.next().?, 10) catch unreachable;
}
// Line 3.
if (reader.readUntilDelimiterOrEof(buf[0..], '\n') catch unreachable) |line| {
assert(std.mem.eql(u8, "255", line));
}
var y: u32 = 0;
var current_id: u32 = 1;
while (y < map_height) : (y += 1) {
var x: u32 = 0;
while (x < map_width) : (x += 1) {
const desc = reader.readBytesNoEof(3) catch unreachable;
if (desc[0] == 0 and desc[1] == 0 and desc[2] == 0) {
entities.append(
Entity{
.mesh = meshes[0],
.id = current_id,
.position = vec3.init(@intToFloat(f32, x), 0.0, @intToFloat(f32, y)),
.color = 0x000000ff,
},
) catch unreachable;
current_id += 1;
}
// Floor.
entities.append(
Entity{
.mesh = meshes[0],
.id = current_id,
.position = vec3.init(@intToFloat(f32, x), -1.0, @intToFloat(f32, y)),
.color = 0x0000ffff,
},
) catch unreachable;
current_id += 1;
}
}
}
entities.append(Entity{
.mesh = meshes[0],
.id = 1,
.position = vec3.init(0.0, 0.0, 0.0),
.color = 0x00ffffff,
}) catch unreachable;
const EntityInfo = extern struct {
m4x4: Mat4,
color: u32,
};
const num_slots: u32 = @intCast(u32, entities.items.len + 1);
entity_buffer.* = dx.createCommittedResource(
.DEFAULT,
.{},
&d3d12.RESOURCE_DESC.buffer(num_slots * @sizeOf(EntityInfo)),
.{ .COPY_DEST = true },
null,
);
entity_buffer_srv.* = dx.allocateCpuDescriptors(.CBV_SRV_UAV, 1);
dx.device.CreateShaderResourceView(
dx.getResource(entity_buffer.*),
&d3d12.SHADER_RESOURCE_VIEW_DESC.structuredBuffer(0, num_slots, @sizeOf(EntityInfo)),
entity_buffer_srv.*,
);
// Upload entity info to a GPU buffer.
{
const upload = dx.allocateUploadBufferRegion(EntityInfo, num_slots);
for (entities.items) |entity, entity_idx| {
upload.cpu_slice[entity_idx + 1].m4x4 = mat4.transpose(
mat4.initTranslation(entity.position),
);
upload.cpu_slice[entity_idx + 1].color = entity.color;
}
dx.cmdlist.CopyBufferRegion(
dx.getResource(entity_buffer.*),
0,
upload.buffer,
upload.buffer_offset,
upload.cpu_slice.len * @sizeOf(EntityInfo),
);
}
}
fn initRenderTarget(
dx: *gr.DxContext,
srgb_texture: *gr.ResourceHandle,
depth_texture: *gr.ResourceHandle,
srgb_texture_rtv: *d3d12.CPU_DESCRIPTOR_HANDLE,
depth_texture_dsv: *d3d12.CPU_DESCRIPTOR_HANDLE,
) void {
srgb_texture.* = dx.createCommittedResource(
.DEFAULT,
.{},
&blk: {
var desc = d3d12.RESOURCE_DESC.tex2d(
.R8G8B8A8_UNORM_SRGB,
dx.viewport_width,
dx.viewport_height,
);
desc.Flags = .{ .ALLOW_RENDER_TARGET = true };
desc.SampleDesc.Count = window_num_samples;
break :blk desc;
},
.{ .RENDER_TARGET = true },
&d3d12.CLEAR_VALUE.color(.R8G8B8A8_UNORM_SRGB, [4]f32{ 0.2, 0.4, 0.8, 1.0 }),
);
srgb_texture_rtv.* = dx.allocateCpuDescriptors(.RTV, 1);
dx.device.CreateRenderTargetView(dx.getResource(srgb_texture.*), null, srgb_texture_rtv.*);
depth_texture.* = dx.createCommittedResource(
.DEFAULT,
.{},
&blk: {
var desc = d3d12.RESOURCE_DESC.tex2d(.D32_FLOAT, dx.viewport_width, dx.viewport_height);
desc.Flags = .{ .ALLOW_DEPTH_STENCIL = true, .DENY_SHADER_RESOURCE = true };
desc.SampleDesc.Count = window_num_samples;
break :blk desc;
},
.{ .DEPTH_WRITE = true },
&d3d12.CLEAR_VALUE.depthStencil(.D32_FLOAT, 1.0, 0),
);
depth_texture_dsv.* = dx.allocateCpuDescriptors(.DSV, 1);
dx.device.CreateDepthStencilView(dx.getResource(depth_texture.*), null, depth_texture_dsv.*);
}
fn initDx12Pipelines(dx: *gr.DxContext, pipelines: *std.ArrayList(gr.PipelineHandle)) void {
pipelines.append(dx.createGraphicsPipeline(d3d12.GRAPHICS_PIPELINE_STATE_DESC{
.PrimitiveTopologyType = .TRIANGLE,
.NumRenderTargets = 1,
.RTVFormats = [_]dxgi.FORMAT{.R8G8B8A8_UNORM_SRGB} ++ [_]dxgi.FORMAT{.UNKNOWN} ** 7,
.DSVFormat = .D32_FLOAT,
.VS = blk: {
const file = @embedFile("../shaders/test.vs.cso");
break :blk .{ .pShaderBytecode = file, .BytecodeLength = file.len };
},
.PS = blk: {
const file = @embedFile("../shaders/test.ps.cso");
break :blk .{ .pShaderBytecode = file, .BytecodeLength = file.len };
},
.SampleDesc = .{ .Count = window_num_samples, .Quality = 0 },
})) catch unreachable;
}
fn init2dResources(
dx: gr.DxContext,
brush: **d2d1.ISolidColorBrush,
text_format: **dwrite.ITextFormat,
) void {
os.vhr(dx.d2d.context.CreateSolidColorBrush(
&d2d1.COLOR_F{ .r = 1.0, .g = 0.0, .b = 0.0, .a = 0.5 },
null,
&brush.*,
));
os.vhr(dx.d2d.dwrite_factory.CreateTextFormat(
std.unicode.utf8ToUtf16LeStringLiteral("Verdana")[0..],
null,
.NORMAL,
.NORMAL,
.NORMAL,
32.0,
std.unicode.utf8ToUtf16LeStringLiteral("en-us")[0..],
&text_format.*,
));
os.vhr(text_format.*.SetTextAlignment(.LEADING));
os.vhr(text_format.*.SetParagraphAlignment(.NEAR));
}
};
const MeshLoader = struct {
num_vertices: u32,
num_triangles: u32,
file: std.fs.File,
fn init(path: []const u8) MeshLoader {
const file = std.fs.openFileAbsolute(path, .{ .read = true }) catch unreachable;
var num_vertices: u32 = 0;
var num_triangles: u32 = 0;
var buf: [128]u8 = undefined;
const reader = file.reader();
line_loop: while (reader.readUntilDelimiterOrEof(buf[0..], '\n') catch null) |line| {
var it = std.mem.split(line, " ");
while (it.next()) |item| {
if (std.mem.eql(u8, item, "end_header")) {
break :line_loop;
} else if (std.mem.eql(u8, item, "vertex")) {
num_vertices = std.fmt.parseInt(u32, it.next().?, 10) catch unreachable;
} else if (std.mem.eql(u8, item, "face")) {
num_triangles = std.fmt.parseInt(u32, it.next().?, 10) catch unreachable;
}
}
}
assert(num_vertices > 0 and num_triangles > 0);
return MeshLoader{
.num_vertices = num_vertices,
.num_triangles = num_triangles,
.file = file,
};
}
fn deinit(self: *MeshLoader) void {
self.file.close();
self.* = undefined;
}
fn load(self: MeshLoader, vertices: []Vertex, triangles: []Triangle) void {
var buf: [256]u8 = undefined;
const reader = self.file.reader();
for (vertices) |*vertex| {
const line = reader.readUntilDelimiterOrEof(buf[0..], '\n') catch unreachable;
var it = std.mem.split(line.?, " ");
const x = std.fmt.parseFloat(f32, it.next().?) catch unreachable;
const y = std.fmt.parseFloat(f32, it.next().?) catch unreachable;
const z = std.fmt.parseFloat(f32, it.next().?) catch unreachable;
vertex.* = Vertex{
// NOTE: We mirror on x-axis to convert from Blender to our coordinate system.
.position = [3]f32{ -x, y, z },
.normal = [3]f32{
std.fmt.parseFloat(f32, it.next().?) catch unreachable,
std.fmt.parseFloat(f32, it.next().?) catch unreachable,
std.fmt.parseFloat(f32, it.next().?) catch unreachable,
},
.texcoord = [2]f32{
std.fmt.parseFloat(f32, it.next().?) catch unreachable,
1.0 - (std.fmt.parseFloat(f32, it.next().?) catch unreachable),
},
};
}
for (triangles) |*tri| {
const line = reader.readUntilDelimiterOrEof(buf[0..], '\n') catch unreachable;
var it = std.mem.split(line.?, " ");
const num_verts = std.fmt.parseInt(u32, it.next().?, 10) catch unreachable;
assert(num_verts == 3);
tri.* = Triangle{
// NOTE: We change indices order to end up with 'clockwise is front winding'.
.index0 = std.fmt.parseInt(u32, it.next().?, 10) catch unreachable,
.index2 = std.fmt.parseInt(u32, it.next().?, 10) catch unreachable,
.index1 = std.fmt.parseInt(u32, it.next().?, 10) catch unreachable,
};
}
}
};
const FrameStats = struct {
time: f64,
delta_time: f32,
fps: f32,
average_cpu_time: f32,
timer: std.time.Timer,
previous_time_ns: u64,
fps_refresh_time_ns: u64,
frame_counter: u64,
fn init() FrameStats {
return .{
.time = 0.0,
.delta_time = 0.0,
.fps = 0.0,
.average_cpu_time = 0.0,
.timer = std.time.Timer.start() catch unreachable,
.previous_time_ns = 0,
.fps_refresh_time_ns = 0,
.frame_counter = 0,
};
}
fn update(self: *FrameStats) void {
const now_ns = self.timer.read();
self.time = @intToFloat(f64, now_ns) / std.time.ns_per_s;
self.delta_time = @intToFloat(f32, now_ns - self.previous_time_ns) / std.time.ns_per_s;
self.previous_time_ns = now_ns;
if ((now_ns - self.fps_refresh_time_ns) >= std.time.ns_per_s) {
const t = @intToFloat(f64, now_ns - self.fps_refresh_time_ns) / std.time.ns_per_s;
const fps = @intToFloat(f64, self.frame_counter) / t;
const ms = (1.0 / fps) * 1000.0;
self.fps = @floatCast(f32, fps);
self.average_cpu_time = @floatCast(f32, ms);
self.fps_refresh_time_ns = now_ns;
self.frame_counter = 0;
}
self.frame_counter += 1;
}
};
fn processWindowMessage(
window: os.HWND,
message: os.UINT,
wparam: os.WPARAM,
lparam: os.LPARAM,
) callconv(.C) os.LRESULT {
const processed = switch (message) {
os.user32.WM_DESTROY => blk: {
os.user32.PostQuitMessage(0);
break :blk true;
},
os.user32.WM_KEYDOWN => blk: {
if (wparam == os.VK_ESCAPE) {
os.user32.PostQuitMessage(0);
break :blk true;
}
break :blk false;
},
else => false,
};
return if (processed) null else os.user32.DefWindowProcA(window, message, wparam, lparam);
}
pub fn main() !void {
_ = os.SetProcessDPIAware();
const window_name = "zig d3d12 test";
const window_width = 1920;
const window_height = 1080;
const winclass = os.user32.WNDCLASSEXA{
.style = 0,
.lpfnWndProc = processWindowMessage,
.cbClsExtra = 0,
.cbWndExtra = 0,
.hInstance = @ptrCast(os.HINSTANCE, os.kernel32.GetModuleHandleW(null)),
.hIcon = null,
.hCursor = os.LoadCursorA(null, @intToPtr(os.LPCSTR, 32512)),
.hbrBackground = null,
.lpszMenuName = null,
.lpszClassName = window_name,
.hIconSm = null,
};
_ = os.user32.RegisterClassExA(&winclass);
const style = os.user32.WS_OVERLAPPED +
os.user32.WS_SYSMENU +
os.user32.WS_CAPTION +
os.user32.WS_MINIMIZEBOX;
var rect = os.RECT{ .left = 0, .top = 0, .right = window_width, .bottom = window_height };
_ = os.AdjustWindowRect(&rect, style, os.FALSE);
const window = os.user32.CreateWindowExA(
0,
window_name,
window_name,
style + os.WS_VISIBLE,
-1,
-1,
rect.right - rect.left,
rect.bottom - rect.top,
null,
null,
winclass.hInstance,
null,
);
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer {
const leaked = gpa.deinit();
assert(leaked == false);
}
var demo_state = DemoState.init(&gpa.allocator, window.?);
defer demo_state.deinit();
while (true) {
var message = std.mem.zeroes(os.user32.MSG);
if (os.user32.PeekMessageA(&message, null, 0, 0, os.user32.PM_REMOVE)) {
_ = os.user32.DispatchMessageA(&message);
if (message.message == os.user32.WM_QUIT)
break;
} else {
demo_state.update();
}
}
} | src/main.zig |
const std = @import("std");
const util = @import("util.zig");
const data = @embedFile("../data/day15.txt");
const Input = struct {
risks: [100][100]i64 = undefined,
dim: usize = undefined,
pub fn init(input_text: []const u8, allocator: std.mem.Allocator) !@This() {
_ = allocator;
var input = Input{};
errdefer input.deinit();
var lines = std.mem.tokenize(u8, input_text, "\r\n");
var y: usize = 0;
while (lines.next()) |line| : (y += 1) {
for (line) |c, x| {
input.risks[y][x] = c - '0';
}
}
input.dim = y;
return input;
}
pub fn deinit(self: @This()) void {
_ = self;
}
};
const Coord2 = struct {
x: usize,
y: usize,
};
const UNVISITED: i64 = std.math.maxInt(i64);
fn updateCandidate(input: Input, lowest: *[100][100]i64, candidates: *std.ArrayList(Coord2), x: usize, y: usize, val: i64) void {
if (x >= input.dim or y >= input.dim) {
return; // out of bounds
}
if (lowest.*[y][x] == UNVISITED) {
candidates.appendAssumeCapacity(Coord2{ .x = x, .y = y });
}
lowest.*[y][x] = std.math.min(lowest.*[y][x], val + input.risks[y][x]);
}
fn part1(input: Input) i64 {
var lowest: [100][100]i64 = undefined;
for (lowest) |*row| {
for (row) |*v| {
v.* = UNVISITED;
}
}
var candidates = std.ArrayList(Coord2).initCapacity(std.testing.allocator, 100 * 100) catch unreachable;
defer candidates.deinit();
candidates.appendAssumeCapacity(Coord2{ .x = input.dim - 1, .y = input.dim - 1 });
lowest[input.dim - 1][input.dim - 1] = input.risks[input.dim - 1][input.dim - 1];
var visit_count: usize = 0;
while (candidates.items.len > 0) {
visit_count += 1;
var min_risk: i64 = UNVISITED;
var min_risk_index: usize = 0;
// when picking the next candidate to explore:
// for Dijkstra, just pick the one with the lowest total cost.
// For A*, add a conservative heuristic of the remaining cost (e.g. Manhattan distance).
for (candidates.items) |c, i| {
const h: i64 = @intCast(i64, c.y + c.x);
_ = h;
const r = lowest[c.y][c.x] + h;
if (r < min_risk) {
min_risk = r;
min_risk_index = i;
}
}
const c = candidates.swapRemove(min_risk_index);
if (c.x == 0 and c.y == 0) {
print("visited {d} nodes out of {d}\n", .{ visit_count, input.dim * input.dim });
return lowest[0][0] - input.risks[0][0]; // starting location not counted
}
const r = lowest[c.y][c.x];
updateCandidate(input, &lowest, &candidates, c.x -% 1, c.y, r);
updateCandidate(input, &lowest, &candidates, c.x + 1, c.y, r);
updateCandidate(input, &lowest, &candidates, c.x, c.y -% 1, r);
updateCandidate(input, &lowest, &candidates, c.x, c.y + 1, r);
}
unreachable;
}
fn tiledRisk(input: Input, x: usize, y: usize) i64 {
const tile_x = @divFloor(x, input.dim);
const tile_y = @divFloor(y, input.dim);
const cell_x = x % input.dim;
const cell_y = y % input.dim;
const risk_offset = tile_x + tile_y;
const r = input.risks[cell_y][cell_x] + @intCast(i64, risk_offset);
return if (r <= 9) r else @mod(r + 1, 10);
}
fn updateCandidate2(input: Input, lowest: *[500][500]i64, candidates: *std.ArrayList(Coord2), x: usize, y: usize, val: i64) void {
const scale_dim = 5 * input.dim;
if (x >= scale_dim or y >= scale_dim) {
return; // out of bounds
}
if (lowest.*[y][x] == UNVISITED) {
candidates.appendAssumeCapacity(Coord2{ .x = x, .y = y });
}
lowest.*[y][x] = std.math.min(lowest.*[y][x], val + tiledRisk(input, x, y));
}
fn part2(input: Input) i64 {
var lowest: [500][500]i64 = undefined;
for (lowest) |*row| {
for (row) |*v| {
v.* = UNVISITED;
}
}
var candidates = std.ArrayList(Coord2).initCapacity(std.testing.allocator, 500 * 500) catch unreachable;
defer candidates.deinit();
const scale_dim = 5 * input.dim;
candidates.appendAssumeCapacity(Coord2{ .x = scale_dim - 1, .y = scale_dim - 1 });
lowest[scale_dim - 1][scale_dim - 1] = tiledRisk(input, scale_dim - 1, scale_dim - 1);
var visit_count: usize = 0;
while (candidates.items.len > 0) {
visit_count += 1;
var min_risk: i64 = UNVISITED;
var min_risk_index: usize = 0;
// when picking the next candidate to explore:
// for Dijkstra, just pick the one with the lowest total cost.
// For A*, add a conservative heuristic of the remaining cost (e.g. Manhattan distance).
// In this case it doesn't really make a huge difference in the visit count, and adding
// the heuristic doubles the running time (???), so I've left it commented out.
for (candidates.items) |c, i| {
const r = lowest[c.y][c.x]; // + @intCast(i64, c.y + c.x);
if (r < min_risk) {
min_risk = r;
min_risk_index = i;
}
}
const c = candidates.swapRemove(min_risk_index);
if (c.x == 0 and c.y == 0) {
print("visited {d} nodes out of {d}\n", .{ visit_count, scale_dim * scale_dim });
return lowest[0][0] - input.risks[0][0]; // starting location not counted
}
const r = lowest[c.y][c.x];
updateCandidate2(input, &lowest, &candidates, c.x -% 1, c.y, r);
updateCandidate2(input, &lowest, &candidates, c.x + 1, c.y, r);
updateCandidate2(input, &lowest, &candidates, c.x, c.y -% 1, r);
updateCandidate2(input, &lowest, &candidates, c.x, c.y + 1, r);
}
unreachable;
}
const test_data =
\\1163751742
\\1381373672
\\2136511328
\\3694931569
\\7463417111
\\1319128137
\\1359912421
\\3125421639
\\1293138521
\\2311944581
;
const part1_test_solution: ?i64 = 40;
const part1_solution: ?i64 = 741;
const part2_test_solution: ?i64 = 315;
const part2_solution: ?i64 = 2976;
// Just boilerplate below here, nothing to see
fn testPart1() !void {
var test_input = try Input.init(test_data, std.testing.allocator);
defer test_input.deinit();
if (part1_test_solution) |solution| {
try std.testing.expectEqual(solution, part1(test_input));
}
var timer = try std.time.Timer.start();
var input = try Input.init(data, std.testing.allocator);
defer input.deinit();
if (part1_solution) |solution| {
try std.testing.expectEqual(solution, part1(input));
print("part1 took {d:9.3}ms\n", .{@intToFloat(f64, timer.lap()) / 1000000.0});
}
}
fn testPart2() !void {
var test_input = try Input.init(test_data, std.testing.allocator);
defer test_input.deinit();
if (part2_test_solution) |solution| {
try std.testing.expectEqual(solution, part2(test_input));
}
var timer = try std.time.Timer.start();
var input = try Input.init(data, std.testing.allocator);
defer input.deinit();
if (part2_solution) |solution| {
try std.testing.expectEqual(solution, part2(input));
print("part2 took {d:9.3}ms\n", .{@intToFloat(f64, timer.lap()) / 1000000.0});
}
}
pub fn main() !void {
try testPart1();
try testPart2();
}
test "part1" {
try testPart1();
}
test "part2" {
try testPart2();
}
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const parseInt = std.fmt.parseInt;
const min = std.math.min;
const max = std.math.max;
const print = std.debug.print;
const expect = std.testing.expect;
const assert = std.debug.assert; | src/day15.zig |
const std = @import("std");
const Arena = std.heap.ArenaAllocator;
const expectEqual = std.testing.expectEqual;
const expectEqualStrings = std.testing.expectEqualStrings;
const yeti = @import("yeti");
const initCodebase = yeti.initCodebase;
const tokenize = yeti.tokenize;
const parse = yeti.parse;
const analyzeSemantics = yeti.analyzeSemantics;
const codegen = yeti.codegen;
const printWasm = yeti.printWasm;
const components = yeti.components;
const literalOf = yeti.query.literalOf;
const typeOf = yeti.query.typeOf;
const MockFileSystem = yeti.FileSystem;
test "tokenize struct" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
const module = try codebase.createEntity(.{});
const code = "struct";
var tokens = try tokenize(module, code);
{
const token = tokens.next().?;
try expectEqual(token.get(components.TokenKind), .struct_);
try expectEqual(token.get(components.Span), .{
.begin = .{ .column = 0, .row = 0 },
.end = .{ .column = 6, .row = 0 },
});
}
try expectEqual(tokens.next(), null);
}
test "parse struct" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
const module = try codebase.createEntity(.{});
const code =
\\struct Rectangle {
\\ width: f64
\\ height: f64
\\}
;
var tokens = try tokenize(module, code);
try parse(module, &tokens);
const top_level = module.get(components.TopLevel);
const rectangle = top_level.findString("Rectangle");
const overloads = rectangle.get(components.Overloads).slice();
try expectEqual(overloads.len, 1);
const overload = overloads[0];
try expectEqual(overload.get(components.AstKind), .struct_);
const fields = overload.get(components.Fields).slice();
try expectEqual(fields.len, 2);
const width = fields[0];
try expectEqualStrings(literalOf(width), "width");
try expectEqualStrings(literalOf(width.get(components.TypeAst).entity), "f64");
const height = fields[1];
try expectEqualStrings(literalOf(height), "height");
try expectEqualStrings(literalOf(height.get(components.TypeAst).entity), "f64");
}
test "analyze semantics of struct" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
var fs = try MockFileSystem.init(&arena);
_ = try fs.newFile("foo.yeti",
\\struct Rectangle {
\\ width: f64
\\ height: f64
\\}
\\
\\start() Rectangle {
\\ Rectangle(10, 30)
\\}
);
_ = try analyzeSemantics(codebase, fs, "foo.yeti");
const module = try analyzeSemantics(codebase, fs, "foo.yeti");
const top_level = module.get(components.TopLevel);
const start = top_level.findString("start").get(components.Overloads).slice()[0];
try expectEqualStrings(literalOf(start.get(components.Module).entity), "foo");
try expectEqualStrings(literalOf(start.get(components.Name).entity), "start");
try expectEqual(start.get(components.Parameters).len(), 0);
const rectangle = start.get(components.ReturnType).entity;
try expectEqualStrings(literalOf(rectangle.get(components.Name).entity), "Rectangle");
const body = start.get(components.Body).slice();
try expectEqual(body.len, 1);
const construct = body[0];
try expectEqual(construct.get(components.AstKind), .construct);
try expectEqual(typeOf(construct), rectangle);
const arguments = construct.get(components.Arguments).slice();
try expectEqual(arguments.len, 2);
try expectEqualStrings(literalOf(arguments[0]), "10");
try expectEqualStrings(literalOf(arguments[1]), "30");
}
test "analyze semantics of struct field access" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
var fs = try MockFileSystem.init(&arena);
const builtins = codebase.get(components.Builtins);
_ = try fs.newFile("foo.yeti",
\\struct Rectangle {
\\ width: f64
\\ height: f64
\\}
\\
\\start() f64 {
\\ r = Rectangle(10, 30)
\\ r.width
\\}
);
_ = try analyzeSemantics(codebase, fs, "foo.yeti");
const module = try analyzeSemantics(codebase, fs, "foo.yeti");
const top_level = module.get(components.TopLevel);
const start = top_level.findString("start").get(components.Overloads).slice()[0];
try expectEqualStrings(literalOf(start.get(components.Module).entity), "foo");
try expectEqualStrings(literalOf(start.get(components.Name).entity), "start");
try expectEqual(start.get(components.Parameters).len(), 0);
try expectEqual(start.get(components.ReturnType).entity, builtins.F64);
const body = start.get(components.Body).slice();
try expectEqual(body.len, 2);
const r = blk: {
const define = body[0];
try expectEqual(define.get(components.AstKind), .define);
try expectEqual(typeOf(define), builtins.Void);
const local = define.get(components.Local).entity;
try expectEqual(local.get(components.AstKind), .local);
try expectEqualStrings(literalOf(local.get(components.Name).entity), "r");
const construct = define.get(components.Value).entity;
const rectangle = typeOf(construct);
try expectEqual(typeOf(local), rectangle);
try expectEqualStrings(literalOf(rectangle.get(components.Name).entity), "Rectangle");
try expectEqualStrings(literalOf(local.get(components.Name).entity), "r");
try expectEqual(construct.get(components.AstKind), .construct);
try expectEqual(typeOf(construct), rectangle);
const arguments = construct.get(components.Arguments).slice();
try expectEqual(arguments.len, 2);
try expectEqualStrings(literalOf(arguments[0]), "10");
try expectEqualStrings(literalOf(arguments[1]), "30");
break :blk local;
};
const field = body[1];
try expectEqual(field.get(components.AstKind), .field);
try expectEqual(typeOf(field), builtins.F64);
try expectEqual(field.get(components.Local).entity, r);
try expectEqualStrings(literalOf(field.get(components.Field).entity), "width");
}
test "analyze semantics of struct field write" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
var fs = try MockFileSystem.init(&arena);
const builtins = codebase.get(components.Builtins);
_ = try fs.newFile("foo.yeti",
\\struct Rectangle {
\\ width: f64
\\ height: f64
\\}
\\
\\start() Rectangle {
\\ r = Rectangle(10, 30)
\\ r.width = 45
\\ r
\\}
);
_ = try analyzeSemantics(codebase, fs, "foo.yeti");
const module = try analyzeSemantics(codebase, fs, "foo.yeti");
const top_level = module.get(components.TopLevel);
const start = top_level.findString("start").get(components.Overloads).slice()[0];
try expectEqualStrings(literalOf(start.get(components.Module).entity), "foo");
try expectEqualStrings(literalOf(start.get(components.Name).entity), "start");
try expectEqual(start.get(components.Parameters).len(), 0);
const rectangle = start.get(components.ReturnType).entity;
try expectEqualStrings(literalOf(rectangle.get(components.Name).entity), "Rectangle");
const body = start.get(components.Body).slice();
try expectEqual(body.len, 3);
const r = blk: {
const define = body[0];
try expectEqual(define.get(components.AstKind), .define);
try expectEqual(typeOf(define), builtins.Void);
const local = define.get(components.Local).entity;
try expectEqual(local.get(components.AstKind), .local);
try expectEqualStrings(literalOf(local.get(components.Name).entity), "r");
const construct = define.get(components.Value).entity;
try expectEqual(typeOf(construct), rectangle);
try expectEqual(typeOf(local), rectangle);
try expectEqualStrings(literalOf(rectangle.get(components.Name).entity), "Rectangle");
try expectEqual(construct.get(components.AstKind), .construct);
try expectEqual(typeOf(construct), rectangle);
const arguments = construct.get(components.Arguments).slice();
try expectEqual(arguments.len, 2);
try expectEqualStrings(literalOf(arguments[0]), "10");
try expectEqualStrings(literalOf(arguments[1]), "30");
break :blk local;
};
const assign_field = body[1];
try expectEqual(assign_field.get(components.AstKind), .assign_field);
try expectEqual(typeOf(assign_field), builtins.Void);
try expectEqual(assign_field.get(components.Local).entity, r);
try expectEqualStrings(literalOf(assign_field.get(components.Field).entity), "width");
try expectEqualStrings(literalOf(assign_field.get(components.Value).entity), "45");
try expectEqual(body[2], r);
}
test "codegen of struct" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
var fs = try MockFileSystem.init(&arena);
_ = try fs.newFile("foo.yeti",
\\struct Rectangle {
\\ width: f64
\\ height: f64
\\}
\\
\\start() Rectangle {
\\ Rectangle(10, 30)
\\}
);
const module = try analyzeSemantics(codebase, fs, "foo.yeti");
try codegen(module);
const top_level = module.get(components.TopLevel);
const start = top_level.findString("start").get(components.Overloads).slice()[0];
const wasm_instructions = start.get(components.WasmInstructions).slice();
try expectEqual(wasm_instructions.len, 2);
{
const constant = wasm_instructions[0];
try expectEqual(constant.get(components.WasmInstructionKind), .f64_const);
try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "10");
}
{
const constant = wasm_instructions[1];
try expectEqual(constant.get(components.WasmInstructionKind), .f64_const);
try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "30");
}
}
test "codegen of struct field write" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
var fs = try MockFileSystem.init(&arena);
_ = try fs.newFile("foo.yeti",
\\struct Rectangle {
\\ width: f64
\\ height: f64
\\}
\\
\\start() Rectangle {
\\ r = Rectangle(10, 30)
\\ r.width = 45
\\ r
\\}
);
const module = try analyzeSemantics(codebase, fs, "foo.yeti");
try codegen(module);
const top_level = module.get(components.TopLevel);
const start = top_level.findString("start").get(components.Overloads).slice()[0];
const wasm_instructions = start.get(components.WasmInstructions).slice();
try expectEqual(wasm_instructions.len, 6);
{
const constant = wasm_instructions[0];
try expectEqual(constant.get(components.WasmInstructionKind), .f64_const);
try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "10");
}
{
const constant = wasm_instructions[1];
try expectEqual(constant.get(components.WasmInstructionKind), .f64_const);
try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "30");
}
{
const local_set = wasm_instructions[2];
try expectEqual(local_set.get(components.WasmInstructionKind), .local_set);
const local = local_set.get(components.Local).entity;
try expectEqualStrings(literalOf(local.get(components.Name).entity), "r");
}
{
const constant = wasm_instructions[3];
try expectEqual(constant.get(components.WasmInstructionKind), .f64_const);
try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "45");
}
{
const assign_field = wasm_instructions[4];
try expectEqual(assign_field.get(components.WasmInstructionKind), .assign_field);
const local = assign_field.get(components.Local).entity;
try expectEqualStrings(literalOf(local.get(components.Name).entity), "r");
try expectEqualStrings(literalOf(assign_field.get(components.Field).entity), "width");
}
{
const local_get = wasm_instructions[5];
try expectEqual(local_get.get(components.WasmInstructionKind), .local_get);
const local = local_get.get(components.Local).entity;
try expectEqualStrings(literalOf(local.get(components.Name).entity), "r");
}
}
test "print wasm struct" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
var fs = try MockFileSystem.init(&arena);
_ = try fs.newFile("foo.yeti",
\\struct Rectangle {
\\ width: f64
\\ height: f64
\\}
\\
\\start() Rectangle {
\\ Rectangle(10, 30)
\\}
);
const module = try analyzeSemantics(codebase, fs, "foo.yeti");
try codegen(module);
const wasm = try printWasm(module);
try expectEqualStrings(wasm,
\\(module
\\
\\ (func $foo/start (result f64 f64)
\\ (f64.const 10)
\\ (f64.const 30))
\\
\\ (export "_start" (func $foo/start)))
);
}
test "print wasm assign struct to variable" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
var fs = try MockFileSystem.init(&arena);
_ = try fs.newFile("foo.yeti",
\\struct Rectangle {
\\ width: f64
\\ height: f64
\\}
\\
\\start() Rectangle {
\\ r = Rectangle(10, 30)
\\ r
\\}
);
const module = try analyzeSemantics(codebase, fs, "foo.yeti");
try codegen(module);
const wasm = try printWasm(module);
try expectEqualStrings(wasm,
\\(module
\\
\\ (func $foo/start (result f64 f64)
\\ (local $r.width f64)
\\ (local $r.height f64)
\\ (f64.const 10)
\\ (f64.const 30)
\\ (local.set $r.height)
\\ (local.set $r.width)
\\ (local.get $r.width)
\\ (local.get $r.height))
\\
\\ (export "_start" (func $foo/start)))
);
}
test "print wasm pass struct to function" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
var fs = try MockFileSystem.init(&arena);
_ = try fs.newFile("foo.yeti",
\\struct Rectangle {
\\ width: f64
\\ height: f64
\\}
\\
\\id(r: Rectangle) Rectangle {
\\ r
\\}
\\
\\start() Rectangle {
\\ id(Rectangle(10, 30))
\\}
);
const module = try analyzeSemantics(codebase, fs, "foo.yeti");
try codegen(module);
const wasm = try printWasm(module);
try expectEqualStrings(wasm,
\\(module
\\
\\ (func $foo/start (result f64 f64)
\\ (f64.const 10)
\\ (f64.const 30)
\\ (call $foo/id..r.Rectangle))
\\
\\ (func $foo/id..r.Rectangle (param $r.width f64) (param $r.height f64) (result f64 f64)
\\ (local.get $r.width)
\\ (local.get $r.height))
\\
\\ (export "_start" (func $foo/start)))
);
}
test "print wasm struct field access" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
var fs = try MockFileSystem.init(&arena);
_ = try fs.newFile("foo.yeti",
\\struct Rectangle {
\\ width: f64
\\ height: f64
\\}
\\
\\start() f64 {
\\ r = Rectangle(10, 30)
\\ r.width
\\}
);
const module = try analyzeSemantics(codebase, fs, "foo.yeti");
try codegen(module);
const wasm = try printWasm(module);
try expectEqualStrings(wasm,
\\(module
\\
\\ (func $foo/start (result f64)
\\ (local $r.width f64)
\\ (local $r.height f64)
\\ (f64.const 10)
\\ (f64.const 30)
\\ (local.set $r.height)
\\ (local.set $r.width)
\\ (local.get $r.width))
\\
\\ (export "_start" (func $foo/start)))
);
}
test "print wasm struct field write" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
var fs = try MockFileSystem.init(&arena);
_ = try fs.newFile("foo.yeti",
\\struct Rectangle {
\\ width: f64
\\ height: f64
\\}
\\
\\start() Rectangle {
\\ r = Rectangle(10, 30)
\\ r.width = 45
\\ r
\\}
);
const module = try analyzeSemantics(codebase, fs, "foo.yeti");
try codegen(module);
const wasm = try printWasm(module);
try expectEqualStrings(wasm,
\\(module
\\
\\ (func $foo/start (result f64 f64)
\\ (local $r.width f64)
\\ (local $r.height f64)
\\ (f64.const 10)
\\ (f64.const 30)
\\ (local.set $r.height)
\\ (local.set $r.width)
\\ (f64.const 45)
\\ (local.set $r.width)
\\ (local.get $r.width)
\\ (local.get $r.height))
\\
\\ (export "_start" (func $foo/start)))
);
} | src/tests/test_struct.zig |
const std = @import("std");
const builtin = @import("builtin");
const build_options = @import("build_options");
const io = std.io;
const mem = std.mem;
const process = std.process;
const Allocator = mem.Allocator;
const CrossTarget = std.zig.CrossTarget;
const Zld = @import("Zld.zig");
var gpa_allocator = std.heap.GeneralPurposeAllocator(.{}){};
const usage =
\\Usage: zld [files...]
\\
\\Commands:
\\ <empty> [files...] (default) Generate final executable artifact 'a.out' from input '.o' files
\\
\\General Options:
\\-h, --help Print this help and exit
\\--verbose Print the full invocation
\\-dynamic Perform dynamic linking
\\-dylib Create dynamic library
\\-shared Create dynamic library
\\-syslibroot [path] Specify the syslibroot
\\-l[name] Specify library to link against
\\-L[path] Specify library search dir
\\-framework [name] Specify framework to link against
\\-weak_framework [name] Specify weak framework to link against
\\-F[path] Specify framework search dir
\\-rpath [path] Specify runtime path
\\-stack Override default stack size
\\-o [path] Specify output path for the final artifact
\\--debug-log [name] Turn on debugging for [name] backend (requires zld to be compiled with -Dlog)
;
fn printHelpAndExit() noreturn {
io.getStdOut().writeAll(usage) catch {};
process.exit(0);
}
fn fatal(comptime format: []const u8, args: anytype) noreturn {
ret: {
const msg = std.fmt.allocPrint(gpa_allocator.allocator(), format, args) catch break :ret;
io.getStdErr().writeAll(msg) catch {};
}
process.exit(1);
}
pub const log_level: std.log.Level = switch (builtin.mode) {
.Debug => .debug,
.ReleaseSafe, .ReleaseFast => .err,
.ReleaseSmall => .crit,
};
var log_scopes: std.ArrayListUnmanaged([]const u8) = .{};
pub fn log(
comptime level: std.log.Level,
comptime scope: @TypeOf(.EnumLiteral),
comptime format: []const u8,
args: anytype,
) void {
// Hide debug messages unless:
// * logging enabled with `-Dlog`.
// * the --debug-log arg for the scope has been provided
if (@enumToInt(level) > @enumToInt(std.log.level) or
@enumToInt(level) > @enumToInt(std.log.Level.info))
{
if (!build_options.enable_logging) return;
const scope_name = @tagName(scope);
for (log_scopes.items) |log_scope| {
if (mem.eql(u8, log_scope, scope_name))
break;
} else return;
}
// We only recognize 4 log levels in this application.
const level_txt = switch (level) {
.err => "error",
.warn => "warning",
.info => "info",
.debug => "debug",
};
const prefix1 = level_txt;
const prefix2 = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): ";
// Print the message to stderr, silently ignoring any errors
std.debug.print(prefix1 ++ prefix2 ++ format ++ "\n", args);
}
pub fn main() anyerror!void {
var gpa = gpa_allocator.allocator();
var arena_allocator = std.heap.ArenaAllocator.init(gpa);
defer arena_allocator.deinit();
const arena = arena_allocator.allocator();
const all_args = try process.argsAlloc(gpa);
defer process.argsFree(gpa, all_args);
const args = all_args[1..];
if (args.len == 0) {
printHelpAndExit();
}
var positionals = std.ArrayList([]const u8).init(arena);
var libs = std.ArrayList([]const u8).init(arena);
var lib_dirs = std.ArrayList([]const u8).init(arena);
var frameworks = std.ArrayList([]const u8).init(arena);
var framework_dirs = std.ArrayList([]const u8).init(arena);
var rpath_list = std.ArrayList([]const u8).init(arena);
var out_path: ?[]const u8 = null;
var syslibroot: ?[]const u8 = null;
var stack: ?u64 = null;
var dynamic: bool = false;
var verbose: bool = false;
var dylib: bool = false;
var shared: bool = false;
var compatibility_version: ?std.builtin.Version = null;
var current_version: ?std.builtin.Version = null;
var i: usize = 0;
while (i < args.len) : (i += 1) {
const arg = args[i];
if (mem.eql(u8, arg, "--help") or mem.eql(u8, arg, "-h")) {
printHelpAndExit();
}
if (mem.eql(u8, arg, "--debug-log")) {
if (i + 1 >= args.len) fatal("Expected parameter after {s}", .{arg});
i += 1;
try log_scopes.append(arena, args[i]);
continue;
}
if (mem.eql(u8, arg, "-syslibroot")) {
if (i + 1 >= args.len) fatal("Expected path after {s}", .{arg});
i += 1;
syslibroot = args[i];
continue;
}
if (mem.startsWith(u8, arg, "-l")) {
try libs.append(args[i][2..]);
continue;
}
if (mem.startsWith(u8, arg, "-L")) {
try lib_dirs.append(args[i][2..]);
continue;
}
if (mem.eql(u8, arg, "-framework") or mem.eql(u8, arg, "-weak_framework")) {
if (i + 1 >= args.len) fatal("Expected framework name after {s}", .{arg});
i += 1;
try frameworks.append(args[i]);
continue;
}
if (mem.startsWith(u8, arg, "-F")) {
try framework_dirs.append(args[i][2..]);
continue;
}
if (mem.eql(u8, arg, "-o")) {
if (i + 1 >= args.len) fatal("Expected output path after {s}", .{arg});
i += 1;
out_path = args[i];
continue;
}
if (mem.eql(u8, arg, "-stack")) {
if (i + 1 >= args.len) fatal("Expected stack size value after {s}", .{arg});
i += 1;
stack = try std.fmt.parseInt(u64, args[i], 10);
continue;
}
if (mem.eql(u8, arg, "-dylib")) {
dylib = true;
continue;
}
if (mem.eql(u8, arg, "-shared")) {
shared = true;
continue;
}
if (mem.eql(u8, arg, "-dynamic")) {
dynamic = true;
continue;
}
if (mem.eql(u8, arg, "-rpath")) {
if (i + 1 >= args.len) fatal("Expected path after {s}", .{arg});
i += 1;
try rpath_list.append(args[i]);
continue;
}
if (mem.eql(u8, arg, "-compatibility_version")) {
if (i + 1 >= args.len) fatal("Expected version after {s}", .{arg});
i += 1;
compatibility_version = std.builtin.Version.parse(args[i]) catch |err| {
fatal("Unable to parse {s} {s}: {s}", .{ arg, args[i], @errorName(err) });
};
continue;
}
if (mem.eql(u8, arg, "-current_version")) {
if (i + 1 >= args.len) fatal("Expected version after {s}", .{arg});
i += 1;
current_version = std.builtin.Version.parse(args[i]) catch |err| {
fatal("Unable to parse {s} {s}: {s}", .{ arg, args[i], @errorName(err) });
};
continue;
}
if (mem.eql(u8, arg, "--verbose")) {
verbose = true;
continue;
}
try positionals.append(arg);
}
if (positionals.items.len == 0) {
fatal("Expected at least one input .o file", .{});
}
if (verbose) {
var argv = std.ArrayList([]const u8).init(arena);
try argv.append("zld");
if (dynamic) {
try argv.append("-dynamic");
}
if (syslibroot) |path| {
try argv.append("-syslibroot");
try argv.append(path);
}
if (shared) {
try argv.append("-shared");
}
if (dylib) {
try argv.append("-dylib");
}
if (stack) |st| {
try argv.append("-stack");
try argv.append(try std.fmt.allocPrint(arena, "{d}", .{st}));
}
if (out_path) |path| {
try argv.append("-o");
try argv.append(path);
}
for (libs.items) |lib| {
try argv.append(try std.fmt.allocPrint(arena, "-l{s}", .{lib}));
}
for (lib_dirs.items) |dir| {
try argv.append(try std.fmt.allocPrint(arena, "-L{s}", .{dir}));
}
for (frameworks.items) |fw| {
try argv.append("-framework");
try argv.append(fw);
}
for (framework_dirs.items) |dir| {
try argv.append(try std.fmt.allocPrint(arena, "-F{s}", .{dir}));
}
for (rpath_list.items) |rpath| {
try argv.append("-rpath");
try argv.append(rpath);
}
for (positionals.items) |pos| {
try argv.append(pos);
}
try argv.append("\n");
try io.getStdOut().writeAll(try mem.join(arena, " ", argv.items));
}
// TODO allow for non-native targets
const target = builtin.target;
var zld = try Zld.openPath(gpa, .{
.emit = .{
.directory = std.fs.cwd(),
.sub_path = out_path orelse "a.out",
},
.dynamic = dynamic,
.target = target,
.output_mode = if (dylib or shared) .lib else .exe,
.syslibroot = syslibroot,
.positionals = positionals.items,
.libs = libs.items,
.frameworks = frameworks.items,
.lib_dirs = lib_dirs.items,
.framework_dirs = framework_dirs.items,
.rpath_list = rpath_list.items,
.stack_size_override = stack,
.compatibility_version = compatibility_version,
.current_version = current_version,
});
defer zld.deinit();
try zld.flush();
} | src/main.zig |
const std = @import("std");
const webgpu = @import("../../../webgpu.zig");
const vulkan = @import("../vulkan.zig");
const vk = @import("../vk.zig");
const Buffer = @This();
pub const vtable = webgpu.Buffer.VTable{
.destroy_fn = destroy,
.get_const_mapped_range_fn = undefined,
.get_mapped_range_fn = undefined,
.map_async_fn = undefined,
.unmap_fn = undefined,
};
super: webgpu.Buffer,
handle: vk.Buffer,
pub fn create(device: *vulkan.Device, descriptor: webgpu.BufferDescriptor) webgpu.Device.CreateBufferError!*Buffer {
var buffer = try device.allocator.create(Buffer);
errdefer device.allocator.destroy(buffer);
buffer.super = .{
.__vtable = &vtable,
.device = &device.super,
};
const create_info = vk.BufferCreateInfo{
.flags = .{},
.size = descriptor.size,
.usage = toBufferUsageFlags(descriptor.usage),
.sharing_mode = .exclusive,
.queue_family_index_count = 1,
.p_queue_family_indices = @ptrCast([*]const u32, &device.queue_families.graphics.?),
};
buffer.handle = device.vkd.createBuffer(device.handle, &create_info, null)
catch return error.Failed;
errdefer device.vkd.destroyBuffer(device.handle, buffer.handle, null);
return buffer;
}
fn destroy(super: *webgpu.Buffer) void {
var buffer = @fieldParentPtr(Buffer, "super", super);
var device = @fieldParentPtr(vulkan.Device, "super", super.device);
device.vkd.destroyBuffer(device.handle, buffer.handle, null);
device.allocator.destroy(buffer);
}
fn getConstMappedRange(super: *webgpu.Buffer, offset: usize, size: usize) webgpu.Buffer.GetConstMappedRangeError![]align(16) const u8 {
_ = super;
_ = offset;
_ = size;
unreachable;
}
fn getMappedRange(super: *webgpu.Buffer, offset: usize, size: usize) webgpu.Buffer.GetMappedRangeError![]align(16) u8 {
_ = super;
_ = offset;
_ = size;
unreachable;
}
fn mapAsync(super: *webgpu.Buffer, mode: webgpu.MapMode, offset: usize, size: usize) webgpu.Buffer.MapAsyncError!void {
_ = super;
_ = mode;
_ = offset;
_ = size;
}
fn unmap(super: *webgpu.Buffer) webgpu.Buffer.UnmapError!void {
_ = super;
}
inline fn toBufferUsageFlags(usage: webgpu.BufferUsage) vk.BufferUsageFlags {
return .{
.transfer_src_bit = usage.copy_src,
.transfer_dst_bit = usage.copy_dst,
.uniform_buffer_bit = usage.uniform,
.storage_buffer_bit = usage.storage,
.index_buffer_bit = usage.index,
.vertex_buffer_bit = usage.vertex,
.indirect_buffer_bit = usage.indirect,
};
} | src/backends/vulkan/resource/Buffer.zig |
const std = @import("std");
const builtin = @import("builtin");
const IsWasm = builtin.target.isWasm();
const stdx = @import("stdx");
const platform = @import("platform");
const graphics = @import("graphics");
const Color = graphics.Color;
const ui = @import("ui");
const Row = ui.widgets.Row;
const Text = ui.widgets.Text;
const TextButton = ui.widgets.TextButton;
const Padding = ui.widgets.Padding;
const Center = ui.widgets.Center;
const helper = @import("helper.zig");
const log = stdx.log.scoped(.main);
pub const App = struct {
counter: u32,
const Self = @This();
pub fn init(self: *Self, _: *ui.InitContext) void {
self.counter = 0;
}
pub fn build(self: *Self, c: *ui.BuildContext) ui.FrameId {
const S = struct {
fn onClick(self_: *Self, _: platform.MouseUpEvent) void {
self_.counter += 1;
}
};
return c.decl(Center, .{
.child = c.decl(Row, .{
.expand = false,
.children = c.list(.{
c.decl(Padding, .{
.padding = 10,
.pad_left = 30,
.pad_right = 30,
.child = c.decl(Text, .{
.text = c.fmt("{}", .{self.counter}),
.color = Color.White,
}),
}),
c.decl(TextButton, .{
.text = "Count",
.onClick = c.funcExt(self, S.onClick),
.corner_radius = 10,
}),
}),
}),
});
}
};
var app: helper.App = undefined;
pub fn main() !void {
// This is the app loop for desktop. For web/wasm see wasm exports below.
app.init("Counter");
defer app.deinit();
app.runEventLoop(update);
}
fn update(delta_ms: f32) void {
const S = struct {
fn buildRoot(_: void, c: *ui.BuildContext) ui.FrameId {
return c.decl(App, .{});
}
};
const ui_width = @intToFloat(f32, app.win.getWidth());
const ui_height = @intToFloat(f32, app.win.getHeight());
app.ui_mod.updateAndRender(delta_ms, {}, S.buildRoot, ui_width, ui_height) catch unreachable;
}
pub usingnamespace if (IsWasm) struct {
export fn wasmInit() *const u8 {
return helper.wasmInit(&app, "Counter");
}
export fn wasmUpdate(cur_time_ms: f64, input_buffer_len: u32) *const u8 {
return helper.wasmUpdate(cur_time_ms, input_buffer_len, &app, update);
}
/// Not that useful since it's a long lived process in the browser.
export fn wasmDeinit() void {
app.deinit();
stdx.wasm.deinit();
}
} else struct {}; | ui/examples/counter.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const print = std.debug.print;
const input = @embedFile("../in04.txt");
const valid_ecls = .{
"amb", "blu", "brn", "gry", "grn", "hzl", "oth",
};
fn in_range(comptime T: type, num: ?[]const u8, min: T, max: T) bool {
var n = std.fmt.parseInt(T, num orelse "", 10) catch |e| return false;
return (n >= min and n <= max);
}
const Passport = struct {
byr: ?[]const u8 = null,
iyr: ?[]const u8 = null,
eyr: ?[]const u8 = null,
hgt: ?[]const u8 = null,
hcl: ?[]const u8 = null,
ecl: ?[]const u8 = null,
pid: ?[]const u8 = null,
// cid: ?[]const u8 = null,
pub fn check(self: *Passport) bool {
print("CHECKING: ", .{});
if (!in_range(i16, self.byr, 1920, 2002)) return false;
print("valid byr 1920<={}<=2002 - ", .{self.byr});
if (!in_range(i16, self.iyr, 2010, 2020)) return false;
print("valid iyr 2010<={}<=2020 - ", .{self.iyr});
if (!in_range(i16, self.eyr, 2020, 2030)) return false;
print("valid eyr 2020<={}<=2030 - ", .{self.eyr});
if (self.hgt) |hgt| {
var hgtnum = hgt[0 .. hgt.len - 2];
if (std.mem.endsWith(u8, hgt, "in")) {
if (!in_range(u16, hgtnum, 59, 76)) return false;
print("valid hgt 59in <= {} <= 76 - ", .{hgtnum});
} else if (std.mem.endsWith(u8, hgt, "cm")) {
if (!in_range(u8, hgtnum, 150, 193)) return false;
print("valid hgt 150cm <= {} <= 193 - ", .{hgtnum});
} else {
return false;
}
} else {
print("missing hgt", .{});
return false;
}
if (self.hcl) |hcl| {
if (hcl[0] != '#' or hcl.len != 7) return false;
for (hcl[1..]) |c| {
if (std.mem.indexOfScalar(u8, "0123456789abcdef", c) == null) return false;
}
print("valid hcl {} is 6 hex - ", .{hcl});
} else {
print("missing hcl", .{});
return false;
}
if (self.ecl) |ecl| {
inline for (valid_ecls) |c| {
if (std.mem.eql(u8, ecl, c)) break;
} else {
print("unknown ecl", .{});
return false;
}
} else {
print("missing ecl", .{});
return false;
}
print("valid ecl - ", .{});
if (self.pid) |pid| {
if (pid.len != 9) return false;
for (pid) |c| if (c < '0' or c > '9') return false;
} else {
print("missing pid", .{});
return false;
}
print("valid pid - Valid!", .{});
return true;
}
};
fn keyis(key: []const u8, word: []const u8) bool {
var result = std.mem.startsWith(u8, word, key) and word[3] == ':';
print("keyis({}, {}) -> {}\n", .{ key, word, result });
return result;
}
pub fn main() !void {
var passport_it = std.mem.split(input, "\n\n");
var valids: usize = 0;
while (passport_it.next()) |text| {
print("---\ngot Passport text:\n{}\n", .{text});
var pass = Passport{};
var kv_it = std.mem.tokenize(text, " \n");
while (kv_it.next()) |kv| {
var part_it = std.mem.tokenize(kv, ":");
var key = part_it.next() orelse "";
inline for (std.meta.fields(Passport)) |field| {
if (std.mem.eql(u8, key, field.name)) {
@field(pass, field.name) = part_it.next();
break;
}
}
}
if (pass.check()) valids += 1;
print("\n", .{});
}
print("found {} valid passports\n", .{valids});
} | src/day04.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const ArrayList = std.ArrayList;
const fs = std.fs;
const log = std.log;
const parse = @import("parse.zig");
const http = @import("http.zig");
const Uri = @import("zuri").Uri;
const url_util = @import("url.zig");
const time = std.time;
const fmt = std.fmt;
const mem = std.mem;
const print = std.debug.print;
const db = @import("db.zig");
const shame = @import("shame.zig");
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const expectEqualStrings = std.testing.expectEqualStrings;
const assert = std.debug.assert;
const Storage = @import("feed_db.zig").Storage;
pub fn makeCli(
allocator: Allocator,
feed_db: *Storage,
options: CliOptions,
writer: anytype,
reader: anytype,
) Cli(@TypeOf(writer), @TypeOf(reader)) {
return Cli(@TypeOf(writer), @TypeOf(reader)){
.allocator = allocator,
.feed_db = feed_db,
.options = options,
.writer = writer,
.reader = reader,
};
}
pub const CliOptions = struct {
url: bool = true,
local: bool = true,
force: bool = false,
default: ?i32 = null,
};
pub const TagArgs = struct {
action: enum { add, remove, remove_all, none } = .none,
location: []const u8 = "",
id: u64 = 0,
};
pub fn Cli(comptime Writer: type, comptime Reader: type) type {
return struct {
const Self = @This();
allocator: Allocator,
feed_db: *Storage,
writer: Writer,
reader: Reader,
options: CliOptions = CliOptions{},
const Host = struct {
title: []const u8,
name: []const u8,
feeds: []const Feed,
const Feed = struct {
title: Fmt,
link: Fmt,
};
const Fmt = struct {
start: []const u8,
end: []const u8,
};
};
pub fn addFeed(
self: *Self,
locations: []const []const u8,
tags: []const u8, // comma separated
) !void {
var path_buf: [fs.MAX_PATH_BYTES]u8 = undefined;
for (locations) |location| {
if (self.options.local) {
if (fs.cwd().realpath(location, &path_buf)) |abs_path| {
try self.addFeedLocal(abs_path, tags);
try self.writer.print("Added local feed: {s}\n", .{abs_path});
continue;
} else |err| switch (err) {
error.FileNotFound => {}, // Skip to checking self.options.url
else => {
log.err("Failed to add local feed '{s}'.", .{location});
log.err("Error: '{s}'.", .{err});
continue;
},
}
}
if (self.options.url) {
self.addFeedHttp(location, tags) catch |err| {
log.err("Failed to add url feed '{s}'.", .{location});
log.err("Error: '{s}'.", .{err});
};
}
}
}
pub fn addFeedLocal(self: *Self, abs_path: []const u8, tags: []const u8) !void {
var arena = std.heap.ArenaAllocator.init(self.allocator);
defer arena.deinit();
const feed = blk: {
const contents = try shame.getFileContents(arena.allocator(), abs_path);
const ext = fs.path.extension(abs_path);
if (mem.eql(u8, ".xml", ext)) {
break :blk try parse.parse(&arena, contents);
} else if (mem.eql(u8, ".atom", ext)) {
break :blk try parse.Atom.parse(&arena, contents);
} else if (mem.eql(u8, ".json", ext)) {
break :blk try parse.Json.parse(&arena, contents);
}
log.err("Unhandled file type '{s}'", .{ext});
return error.UnhandledFileType;
};
const mtime_sec = blk: {
const file = try fs.openFileAbsolute(abs_path, .{});
defer file.close();
const stat = try file.stat();
break :blk @intCast(i64, @divFloor(stat.mtime, time.ns_per_s));
};
var savepoint = try self.feed_db.db.sql_db.savepoint("addFeedLocal");
defer savepoint.rollback();
const id = try self.feed_db.addFeed(feed, abs_path);
try self.feed_db.addFeedLocal(id, mtime_sec);
try self.feed_db.addItems(id, feed.items);
try self.feed_db.addTags(id, tags);
savepoint.commit();
}
pub fn addFeedHttp(self: *Self, input_url: []const u8, tags: []const u8) !void {
var arena = std.heap.ArenaAllocator.init(self.allocator);
defer arena.deinit();
const writer = self.writer;
const feed_db = self.feed_db;
const url = try url_util.makeValidUrl(arena.allocator(), input_url);
try writer.print("Fetching feed {s}\n", .{url});
const resp = try getFeedHttp(&arena, url, writer, self.reader, self.options.default);
switch (resp) {
.fail => |msg| {
log.err("Failed to resolve url {s}", .{url});
log.err("Failed message: {s}", .{msg});
return;
},
.not_modified => {
log.err("Request returned not modified which should not be happening when adding new feed", .{});
return;
},
.ok => {},
}
const location = resp.ok.location;
log.info("Feed fetched", .{});
log.info("Feed location '{s}'", .{location});
log.info("Parsing feed", .{});
var feed = try parseFeedResponseBody(&arena, resp.ok.body, resp.ok.content_type);
log.info("Feed parsed", .{});
if (feed.link == null) feed.link = url;
var savepoint = try feed_db.db.sql_db.savepoint("addFeedUrl");
defer savepoint.rollback();
const query = "select id as feed_id, updated_timestamp from feed where location = ? limit 1;";
if (try feed_db.db.one(Storage.CurrentData, query, .{location})) |row| {
try writer.print("Feed already exists. Updating feed {s}\n", .{location});
try feed_db.updateUrlFeed(.{
.current = row,
.headers = resp.ok.headers,
.feed = feed,
}, .{ .force = true });
try self.feed_db.addTags(row.feed_id, tags);
try writer.print("Feed updated {s}\n", .{location});
} else {
log.info("Saving feed", .{});
const feed_id = try feed_db.addFeed(feed, location);
try feed_db.addFeedUrl(feed_id, resp.ok.headers);
try feed_db.addItems(feed_id, feed.items);
try self.feed_db.addTags(feed_id, tags);
try writer.print("Feed added {s}\n", .{location});
}
savepoint.commit();
}
pub fn deleteFeed(self: *Self, search_inputs: [][]const u8) !void {
const results = try self.feed_db.search(self.allocator, search_inputs);
if (results.len == 0) {
try self.writer.print("Found no matches for '{s}' to delete.\n", .{search_inputs});
return;
}
try self.writer.print("Found {} result(s):\n", .{results.len});
for (results) |result, i| {
const link = result.link orelse "<no-link>";
try self.writer.print(" {}. {s} | {s} | {s}\n", .{
i + 1,
result.title,
link,
result.location,
});
}
var buf: [32]u8 = undefined;
var index = try pickNumber(&buf, results.len, self.options.default, self.writer, self.reader);
while (index == null) {
index = try pickNumber(&buf, results.len, null, self.writer, self.reader);
}
const result = results[index.?];
try self.feed_db.deleteFeed(result.id);
try self.writer.print("Deleted feed '{s}'\n", .{result.location});
}
pub fn cleanItems(self: *Self) !void {
try self.writer.print("Cleaning feeds' links.\n", .{});
self.feed_db.cleanItems() catch {
log.warn("Failed to clean feeds' links.", .{});
return;
};
try self.writer.print("Feeds' items cleaned\n", .{});
}
pub fn printAllItems(self: *Self) !void {
const Result = struct {
title: []const u8,
link: ?[]const u8,
id: u64,
};
// most recently updated feed
const most_recent_feeds_query = "SELECT title, link, id FROM feed;";
const most_recent_feeds = try self.feed_db.db.selectAll(Result, most_recent_feeds_query, .{});
if (most_recent_feeds.len == 0) {
try self.writer.print("There are 0 feeds\n", .{});
return;
}
// grouped by feed_id
const all_items_query =
\\SELECT
\\ title, link, feed_id
\\FROM
\\ item
\\ORDER BY
\\ feed_id DESC,
\\ pub_date_utc DESC,
\\ modified_at DESC
;
const all_items = try self.feed_db.db.selectAll(Result, all_items_query, .{});
for (most_recent_feeds) |feed| {
const id = feed.id;
const start_index = blk: {
for (all_items) |item, idx| {
if (item.id == id) break :blk idx;
}
break; // Should not happen
};
const feed_link = feed.link orelse "<no-link>";
try self.writer.print("{s} - {s}\n", .{ feed.title, feed_link });
for (all_items[start_index..]) |item| {
if (item.id != id) break;
const item_link = item.link orelse "<no-link>";
try self.writer.print(" {s}\n {s}\n\n", .{
item.title,
item_link,
});
}
}
}
pub fn updateFeeds(self: *Self) !void {
if (self.options.url) {
self.feed_db.updateUrlFeeds(.{ .force = self.options.force }) catch {
log.err("Failed to update feeds", .{});
return;
};
try self.writer.print("Updated url feeds\n", .{});
}
if (self.options.local) {
self.feed_db.updateLocalFeeds(.{ .force = self.options.force }) catch {
log.err("Failed to update local feeds", .{});
return;
};
try self.writer.print("Updated local feeds\n", .{});
}
}
pub fn printFeeds(self: *Self) !void {
const Result = struct {
id: u64,
title: []const u8,
location: []const u8,
link: ?[]const u8,
};
const query = "SELECT id, title, location, link FROM feed;";
var stmt = try self.feed_db.db.sql_db.prepare(query);
defer stmt.deinit();
const all_items = stmt.all(Result, self.allocator, .{}, .{}) catch |err| {
log.warn("{s}\nFailed query:\n{s}", .{ self.feed_db.db.sql_db.getDetailedError().message, query });
return err;
};
if (all_items.len == 0) {
try self.writer.print("There are no feeds to print\n", .{});
return;
} else if (all_items.len == 1) {
try self.writer.print("There is 1 feed\n", .{});
} else {
try self.writer.print("There are {d} feeds\n", .{all_items.len});
}
const print_fmt =
\\{s}
\\ link: {s}
\\ location: {s}
\\
;
for (all_items) |item| {
const link = item.link orelse "<no-link>";
try self.writer.print(print_fmt, .{ item.title, link, item.location });
const tags = try self.feed_db.db.selectAll(struct { tag: []const u8 }, "select tag from feed_tag where feed_id = ?", .{item.id});
if (tags.len > 0) {
try self.writer.print(" tags: ", .{});
try self.writer.print("{s}", .{tags[0].tag});
for (tags[1..]) |tag| {
try self.writer.print(", {s}\n", .{tag.tag});
}
}
try self.writer.print("\n", .{});
}
}
pub fn search(self: *Self, terms: [][]const u8) !void {
const results = try self.feed_db.search(self.allocator, terms);
if (results.len == 0) {
try self.writer.print("Found no matches\n", .{});
return;
} else if (results.len == 1) {
try self.writer.print("Found 1 match:\n", .{});
} else {
try self.writer.print("Found {d} matches:\n", .{results.len});
}
for (results) |result| {
try self.writer.print("{s}\n id: {}\n link: {s}\n feed link: {s}\n", .{ result.title, result.id, result.link, result.location });
}
}
pub fn tagCmd(self: *Self, tags: [][]const u8, args: TagArgs) !void {
assert(args.id != 0 or args.location.len != 0);
assert(args.action != .none);
switch (args.action) {
.add => {
var cap = tags.len - 1; // commas
for (tags) |tag| cap += tag.len;
var arr_tags = try ArrayList(u8).initCapacity(self.allocator, cap);
if (tags.len > 0) {
arr_tags.appendSliceAssumeCapacity(tags[0]);
for (tags[1..]) |tag| {
arr_tags.appendAssumeCapacity(',');
arr_tags.appendSliceAssumeCapacity(tag);
}
}
if (args.id != 0) {
try self.feed_db.addTagsById(arr_tags.items, args.id);
} else if (args.location.len != 0) {
try self.feed_db.addTagsByLocation(arr_tags.items, args.location);
}
},
.remove => {
if (args.id != 0) {
try self.feed_db.removeTagsById(tags, args.id);
} else if (args.location.len != 0) {
try self.feed_db.removeTagsByLocation(tags, args.location);
}
},
.remove_all => try self.feed_db.removeTags(tags),
.none => unreachable,
}
}
};
}
test "Cli.printAllItems, Cli.printFeeds" {
std.testing.log_level = .debug;
const base_allocator = std.testing.allocator;
var arena = std.heap.ArenaAllocator.init(base_allocator);
defer arena.deinit();
const allocator = arena.allocator();
var buf: [4096]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buf);
var feed_db = try Storage.init(allocator, null);
var cli = Cli(@TypeOf(fbs).Writer, @TypeOf(fbs).Reader){
.allocator = allocator,
.feed_db = &feed_db,
.writer = fbs.writer(),
.reader = fbs.reader(),
};
const location = "test/rss2.xml";
const rss_url = "/media/hdd/code/feedgaze/test/rss2.xml";
{
const expected = fmt.comptimePrint("Added local feed: {s}\n", .{rss_url});
fbs.reset();
try cli.addFeed(&.{location});
try expectEqualStrings(expected, fbs.getWritten());
}
{
const expected = fmt.comptimePrint(
\\Liftoff News - http://liftoff.msfc.nasa.gov/
\\ Star City's Test
\\ http://liftoff.msfc.nasa.gov/news/2003/news-starcity.asp
\\
\\ Sky watchers in Europe, Asia, and parts of Alaska{s}
\\ <no-link>
\\
\\ TEST THIS
\\ <no-link>
\\
\\ Astronauts' Dirty Laundry
\\ http://liftoff.msfc.nasa.gov/news/2003/news-laundry.asp
\\
\\ The Engine That Does More
\\ http://liftoff.msfc.nasa.gov/news/2003/news-VASIMR.asp
\\
\\ TEST THIS1
\\ <no-link>
\\
\\
, .{" "}); // Because kakoune remove spaces from end of line
fbs.reset();
try cli.printAllItems();
try expectEqualStrings(expected, fbs.getWritten());
}
{
const expected = fmt.comptimePrint(
\\There is 1 feed
\\Liftoff News
\\ link: http://liftoff.msfc.nasa.gov/
\\ location: {s}
\\
\\
, .{rss_url});
fbs.reset();
try cli.printFeeds();
try expectEqualStrings(expected, fbs.getWritten());
}
}
fn printUrl(writer: anytype, uri: Uri, path: ?[]const u8) !void {
try writer.print("{s}://{s}", .{ uri.scheme, uri.host.name });
if (uri.port) |port| {
if (port != 443 and port != 80) {
try writer.print(":{d}", .{port});
}
}
const out_path = if (path) |p| p else uri.path;
try writer.print("{s}", .{out_path});
}
fn pickFeedLink(
page: parse.Html.Page,
uri: Uri,
writer: anytype,
reader: anytype,
default_pick: ?i32,
) !u32 {
const no_title = "<no-title>";
const page_title = page.title orelse no_title;
try writer.print("{s} | ", .{page_title});
try printUrl(writer, uri, null);
try writer.print("\n", .{});
for (page.links) |link, i| {
const link_title = link.title orelse no_title;
try writer.print(" {d}. [{s}] ", .{ i + 1, parse.Html.MediaType.toString(link.media_type) });
if (link.href[0] == '/') {
try printUrl(writer, uri, link.href);
} else {
try writer.print("{s}", .{link.href});
}
try writer.print(" | {s}\n", .{link_title});
}
// TODO?: can input several numbers. Space separated, or both?
var buf: [64]u8 = undefined;
var index = try pickNumber(&buf, page.links.len, default_pick, writer, reader);
while (index == null) {
index = try pickNumber(&buf, page.links.len, null, writer, reader);
}
return index.?;
}
fn pickNumber(buf: []u8, page_links_len: usize, default_pick: ?i32, writer: anytype, reader: anytype) !?u32 {
var nr: u32 = 0;
try writer.print("Enter link number: ", .{});
if (default_pick) |value| {
nr = @intCast(u32, value);
try writer.print("{d}\n", .{value});
} else {
const input = try reader.readUntilDelimiter(buf, '\n');
const value = std.mem.trim(u8, input, &std.ascii.spaces);
nr = fmt.parseUnsigned(u32, value, 10) catch {
try writer.print("Invalid number: '{s}'. Try again.\n", .{input});
return null;
};
}
if (nr < 1 or nr > page_links_len) {
try writer.print("Number out of range: '{d}'. Try again.\n", .{nr});
return null;
}
return nr - 1;
}
fn getFeedHttp(arena: *ArenaAllocator, url: []const u8, writer: anytype, reader: anytype, default_pick: ?i32) !http.FeedResponse {
// make http request
var resp = try http.resolveRequest(arena, url, null, null);
const html_data = if (resp == .ok and resp.ok.content_type == .html)
try parse.Html.parseLinks(arena.allocator(), resp.ok.body)
else
null;
if (html_data) |data| {
if (data.links.len > 0) {
const uri = try Uri.parse(resp.ok.location, true);
// user input
const index = try pickFeedLink(data, uri, writer, reader, default_pick);
const new_url = try url_util.makeWholeUrl(arena.allocator(), uri, data.links[index].href);
resp = try http.resolveRequest(arena, new_url, null, null);
} else {
try writer.print("Found no feed links in html\n", .{});
}
}
return resp;
}
pub fn parseFeedResponseBody(
arena: *ArenaAllocator,
body: []const u8,
content_type: http.ContentType,
) !parse.Feed {
return switch (content_type) {
.xml => try parse.parse(arena, body),
.xml_atom => try parse.Atom.parse(arena, body),
.xml_rss => try parse.Rss.parse(arena, body),
.json => try parse.Json.parse(arena, body),
.json_feed => try parse.Json.parse(arena, body),
.html, .unknown => unreachable, // html should have been parsed before getting here
};
}
test "local and url: add, update, delete, html links, add into update" {
const g = @import("feed_db.zig").g;
std.testing.log_level = .debug;
const base_allocator = std.testing.allocator;
var arena = std.heap.ArenaAllocator.init(base_allocator);
defer arena.deinit();
const allocator = arena.allocator();
var buf: [4096]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buf);
var storage = try Storage.init(allocator, null);
var cli = Cli(@TypeOf(fbs).Writer, @TypeOf(fbs).Reader){
.allocator = allocator,
.feed_db = &storage,
.writer = fbs.writer(),
.reader = fbs.reader(),
};
// local 'test/rss2.xml' and url 'http://localhost:8080/rss2.rss' have same content
// Test add local feed
// ./feedgaze add test/rss2.xml
const rel_path = "test/rss2.xml";
const abs_path = "/media/hdd/code/feedgaze/" ++ rel_path;
{
g.max_items_per_feed = 1;
const expected = "Added local feed: " ++ abs_path ++ "\n";
// Copying is required when reading from stdout
mem.copy(u8, fbs.buffer, expected);
try cli.addFeed(&.{rel_path});
try expectEqualStrings(expected, fbs.getWritten());
}
// Test add url feed
// ./feedgaze add http://localhost:8080/rss2.rss
const url = "http://localhost:8080/rss2.rss";
{
g.max_items_per_feed = 2;
const expected = fmt.comptimePrint(
\\Adding feed {s}
\\Feed added {s}
\\
, .{url} ** 2);
fbs.reset();
try cli.addFeed(&.{url});
try expectEqualStrings(expected, fbs.getWritten());
}
const FeedResult = struct {
id: u64,
title: []const u8,
link: ?[]const u8,
updated_raw: ?[]const u8,
updated_timestamp: ?i64,
};
const ItemResult = struct {
title: []const u8,
link: ?[]const u8,
guid: ?[]const u8,
pub_date: ?[]const u8,
pub_date_utc: ?i64,
};
var local_id: u64 = undefined;
var url_id: u64 = undefined;
// Test if local and url feeds' table fields have same values
{
const feed_query = "select id,title,link,updated_raw,updated_timestamp from feed";
const feeds = try storage.db.selectAll(FeedResult, feed_query, .{});
try expectEqual(@as(usize, 2), feeds.len);
const local_result = feeds[0];
const url_result = feeds[1];
local_id = local_result.id;
url_id = url_result.id;
try std.testing.expectEqualStrings(local_result.title, url_result.title);
if (local_result.link) |link| try std.testing.expectEqualStrings(link, url_result.link.?);
if (local_result.updated_raw) |updated_raw| try std.testing.expectEqualStrings(updated_raw, url_result.updated_raw.?);
if (local_result.updated_timestamp) |updated_timestamp| try std.testing.expectEqual(updated_timestamp, url_result.updated_timestamp.?);
}
// Test row count in feed_update_local and feed_update_http tables
{
const feed_url_local_counts_query = "select count(feed_update_local.feed_id) as local_count, count(feed_update_http.feed_id) as url_count from feed_update_local, feed_update_http";
const counts = try storage.db.one(struct { local_count: u32, url_count: u32 }, feed_url_local_counts_query, .{});
try expectEqual(@as(usize, 1), counts.?.local_count);
try expectEqual(@as(usize, 1), counts.?.url_count);
}
// Test if two (local and url) feeds' first(newest) items are same
const item_query = "select title,link,guid,pub_date,pub_date_utc from item where feed_id = ? order by id DESC";
{
const local_items = try storage.db.selectAll(ItemResult, item_query, .{local_id});
const url_items = try storage.db.selectAll(ItemResult, item_query, .{url_id});
try expectEqual(@as(usize, 1), local_items.len);
try expectEqual(@as(usize, 2), url_items.len);
const l_item = local_items[0];
const u_item = url_items[0];
try std.testing.expectEqualStrings(l_item.title, u_item.title);
if (l_item.link) |link| try std.testing.expectEqualStrings(link, u_item.link.?);
if (l_item.guid) |guid| try std.testing.expectEqualStrings(guid, u_item.guid.?);
if (l_item.pub_date) |pub_date| try std.testing.expectEqualStrings(pub_date, u_item.pub_date.?);
if (l_item.pub_date_utc) |pub_date_utc| try std.testing.expectEqual(pub_date_utc, u_item.pub_date_utc.?);
}
g.max_items_per_feed = 10;
// Test parsing links from html
// Test feed already existing
// ./feedgaze add http://localhost:8080/many-links.html
{
const html_url = "http://localhost:8080/many-links.html";
const expected =
\\Adding feed http://localhost:8080/many-links.html
\\Parse Feed Links | http://localhost:8080/many-links.html
\\ 1. [RSS] http://localhost:8080/rss2.rss | Rss 2
\\ 2. [Unknown] http://localhost:8080/rss2.xml | Rss 2
\\ 3. [Atom] http://localhost:8080/atom.atom | Atom feed
\\ 4. [Atom] http://localhost:8080/rss2.rss | Not Duplicate
\\ 5. [Unknown] http://localhost:8080/atom.xml | Atom feed
\\Enter link number: 1
\\Feed already exists. Updating feed http://localhost:8080/rss2.rss
\\Feed updated http://localhost:8080/rss2.rss
\\
;
fbs.reset();
// Copying is required when reading from stdout
mem.copy(u8, fbs.buffer, expected);
try cli.addFeed(&.{html_url});
try expectEqualStrings(expected, fbs.getWritten());
const url_items = try storage.db.selectAll(ItemResult, item_query, .{url_id});
try expectEqual(@as(usize, 6), url_items.len);
}
// Test update feeds
// ./feedgaze update
{
const expected =
\\Updated url feeds
\\Updated local feeds
\\
;
fbs.reset();
cli.options.force = true;
try cli.updateFeeds();
cli.options.force = false;
try expectEqualStrings(expected, fbs.getWritten());
const local_items = try storage.db.selectAll(ItemResult, item_query, .{local_id});
const url_items = try storage.db.selectAll(ItemResult, item_query, .{url_id});
try expectEqual(@as(usize, 6), local_items.len);
try expectEqual(local_items.len, url_items.len);
for (local_items) |l_item, i| {
const u_item = url_items[i];
try std.testing.expectEqualStrings(l_item.title, u_item.title);
if (l_item.link) |link| try std.testing.expectEqualStrings(link, u_item.link.?);
if (l_item.guid) |guid| try std.testing.expectEqualStrings(guid, u_item.guid.?);
if (l_item.pub_date) |pub_date| try std.testing.expectEqualStrings(pub_date, u_item.pub_date.?);
if (l_item.pub_date_utc) |pub_date_utc| try std.testing.expectEqual(pub_date_utc, u_item.pub_date_utc.?);
}
}
// Test clean items
// ./feedgaze clean
{
g.max_items_per_feed = 2;
try storage.cleanItems();
const local_items = try storage.db.selectAll(ItemResult, item_query, .{local_id});
const url_items = try storage.db.selectAll(ItemResult, item_query, .{url_id});
try expectEqual(@as(usize, g.max_items_per_feed), local_items.len);
try expectEqual(@as(usize, g.max_items_per_feed), url_items.len);
}
// Test delete local feed
// ./feedgaze delete rss2
const enter_nr = "Enter feed number to delete?";
{
const expected = fmt.comptimePrint(
\\Found 2 result(s):
\\ 1. Liftoff News | http://liftoff.msfc.nasa.gov/ | {s}
\\ 2. Liftoff News | http://liftoff.msfc.nasa.gov/ | {s}
\\{s} 1a
\\Invalid number entered: '1a'. Try again.
\\{s} 14
\\Entered number out of range. Try again.
\\{s} 1
\\Deleted feed '{s}'
\\
, .{ abs_path, url, enter_nr, enter_nr, enter_nr, abs_path });
fbs.reset();
mem.copy(u8, fbs.buffer, expected);
cli.deleteFeed("rss2") catch print("|{s}|\n", .{fbs.getWritten()});
try expectEqualStrings(expected, fbs.getWritten());
}
// Test delete url feed
// ./feedgaze delete rss2
{
const expected = fmt.comptimePrint(
\\Found 1 result(s):
\\ 1. Liftoff News | http://liftoff.msfc.nasa.gov/ | {s}
\\{s} 1
\\Deleted feed '{s}'
\\
, .{ url, enter_nr, url });
fbs.reset();
mem.copy(u8, fbs.buffer, expected);
try cli.deleteFeed("rss2");
try expectEqualStrings(expected, fbs.getWritten());
}
const AllCounts = struct {
feed: u32,
item: u32,
update_http: u32,
update_local: u32,
};
// Test that local and url feeds were deleted
{
const all_counts_query =
\\ select
\\ count(feed.id) as feed,
\\ count(item.feed_id) as item,
\\ count(feed_update_local.feed_id) as update_http,
\\ count(feed_update_http.feed_id) as update_local
\\ from feed, item, feed_update_local, feed_update_http;
;
const all_counts = try storage.db.one(AllCounts, all_counts_query, .{});
try expectEqual(AllCounts{ .feed = 0, .item = 0, .update_http = 0, .update_local = 0 }, all_counts.?);
}
} | src/cli.zig |
const std = @import("std");
const helper = @import("helper.zig");
const Allocator = std.mem.Allocator;
const HashMap = std.AutoHashMap;
const input = @embedFile("../inputs/day17.txt");
pub fn run(alloc: Allocator, stdout_: anytype) !void {
const area = try Area.parse(input);
var stepnums = try getStepNums(alloc, area);
defer stepnums.deinit();
const res1 = getMaxYPossible(stepnums, area);
var velmap = HashMap(Point, void).init(alloc);
defer velmap.deinit();
try calculateAllVelocities(stepnums, area, &velmap);
const res2 = velmap.count();
if (stdout_) |stdout| {
try stdout.print("Part 1: {}\n", .{res1});
try stdout.print("Part 2: {}\n", .{res2});
}
}
fn getMaxYPossible(stepnums: HashMap(Point, void), area: Area) i64 {
var max: i64 = std.math.minInt(i64);
var keys = stepnums.keyIterator();
while (keys.next()) |steps| {
// if this was more complicated to solve, we'd have to iterate over all
// possible values of y in a loop - however, since this is essentially
// solving a linear equation, we can do the whole area at once as an
// optimization.
if (getPositiveY(steps.y, area)) |y| {
max = std.math.max(max, y);
}
}
return max;
}
fn getPositiveY(steps: i64, area: Area) ?i64 {
// trying to solve:
// y_init + (y_init - 1) + ... + 1 + 0 - 1 - ... - (steps - y_init - 1) = t
//
// this reduces to:
// (steps^2 - steps)/2 + t = steps*y_init
// which is solved by:
// y_init = (steps^2 - steps + 2t)/2steps
// (there's a prettier form but it's harder to verify that there's an integer solution for it)
//
// to solve an inequality f(y_init, steps) <= t where f is the function above,
// we can simply substitute the equals sign for the <= sign because y_init switches
// sides and there's a single negative division. Similarly for >=.
if (steps <= 0) { // degenerate case that must be handled first
return null;
}
const enumerator = steps * steps - steps;
const enumerator_min = enumerator + 2 * area.ymin;
const enumerator_max = enumerator + 2 * area.ymax;
const denominator = 2 * steps;
const y_init_max = @divFloor(enumerator_max, denominator); // flooring division is intentional
if (y_init_max * denominator < enumerator_min) { // no integer solutions will fit here
return null;
}
if (y_init_max > 0) {
return @divExact(y_init_max * (y_init_max + 1), 2); // y_init_max + (y_init_max - 1) + ... + 1 + 0
} else {
return 0;
}
}
fn calculateAllVelocities(
stepnums: HashMap(Point, void),
area: Area,
velmap: *HashMap(Point, void),
) !void {
var keys = stepnums.keyIterator();
while (keys.next()) |pt| {
const vx = pt.x;
const steps = pt.y;
try addVYs(vx, steps, velmap, area);
}
}
fn addVYs(vx: i64, steps: i64, velmap: *HashMap(Point, void), area: Area) !void {
if (steps <= 0) { // degenerate case that must be handled first
return;
}
const enumerator = steps * steps - steps;
const enumerator_min = enumerator + 2 * area.ymin;
const enumerator_max = enumerator + 2 * area.ymax;
const denominator = 2 * steps;
var y_init = @divFloor(enumerator_max, denominator);
while (y_init * denominator >= enumerator_min) : (y_init -= 1) {
try velmap.put(Point{ .x = vx, .y = y_init }, {});
}
}
fn getStepNums(alloc: Allocator, area: Area) !HashMap(Point, void) {
var stepmap = HashMap(Point, void).init(alloc);
var vx: i64 = 0;
while (vx <= area.xmax) : (vx += 1) {
try getStepsFromVx(vx, area, &stepmap);
}
return stepmap;
}
fn getStepsFromVx(vx_: i64, area: Area, stepmap: *HashMap(Point, void)) !void {
var vx = vx_;
if (vx < 0) unreachable;
var t: i64 = 0;
var xpos: i64 = 0;
while (xpos < area.xmax and t < 1000) { // arbitrary limit for t :(
xpos += vx;
if (vx > 0) {
vx -= 1;
}
t += 1;
if (area.xmin <= xpos and area.xmax >= xpos) {
try stepmap.put(Point{ .x = vx_, .y = t }, {});
}
}
}
const Point = struct { x: i64, y: i64 };
const Area = struct {
xmin: i64,
xmax: i64,
ymin: i64,
ymax: i64,
const Self = @This();
pub fn parse(inp: []const u8) !Self {
var nums_iter = tokenize(u8, inp, "targe :x=.,y\r\n"); // crude but eh
const x1 = try parseInt(i64, nums_iter.next().?, 10);
const x2 = try parseInt(i64, nums_iter.next().?, 10);
const y1 = try parseInt(i64, nums_iter.next().?, 10);
const y2 = try parseInt(i64, nums_iter.next().?, 10);
return Self{
.xmin = std.math.min(x1, x2),
.xmax = std.math.max(x1, x2),
.ymin = std.math.min(y1, y2),
.ymax = std.math.max(y1, y2),
};
}
pub fn contains(self: Self, pt: Point) bool {
const x = pt.x;
const y = pt.y;
return (self.xmin <= x and self.xmax >= x and self.ymin <= y and self.ymax >= y);
}
};
const eql = std.mem.eql;
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const count = std.mem.count;
const parseUnsigned = std.fmt.parseUnsigned;
const parseInt = std.fmt.parseInt;
const sort = std.sort.sort;
const absInt = std.math.absInt; | src/day17.zig |
const std = @import("std");
const SDL = @import("sdl2");
const zgl = @import("zgl");
const rasterizer = @import("rasterizer.zig");
const quality: Quality = .fast;
const multithreading: ?comptime_int = 8;
const level_file = "assets/lost_empire";
const DepthType = u32;
const PixelType = u8;
const screen = struct {
const scaler = 1;
const width = 800;
const height = 480;
};
var palette: [256]u32 = undefined;
var exampleTex: rasterizer.Texture(PixelType) = undefined;
pub fn gameMain() !void {
try SDL.init(.{
.video = true,
.events = true,
.audio = true,
});
defer SDL.quit();
var window = try SDL.createWindow(
"SoftRender: Triangle",
.{ .centered = {} },
.{ .centered = {} },
screen.scaler * screen.width,
screen.scaler * screen.height,
.{ .shown = true },
);
defer window.destroy();
var renderer = try SDL.createRenderer(window, null, .{ .accelerated = true, .presentVSync = true });
defer renderer.destroy();
var texture = try SDL.createTexture(renderer, .rgbx8888, .streaming, screen.width, screen.height);
defer texture.destroy();
// initialized by https://lospec.com/palette-list/dawnbringer-16
palette[0] = 0x140c1cFF; // black
palette[1] = 0x442434FF; // dark purple
palette[2] = 0x30346dFF; // blue
palette[3] = 0x4e4a4eFF; // gray
palette[4] = 0x854c30FF; // brown
palette[5] = 0x346524FF; // green
palette[6] = 0xd04648FF; // tomato
palette[7] = 0x757161FF; // khaki
palette[8] = 0x597dceFF; // baby blue
palette[9] = 0xd27d2cFF; // orange
palette[10] = 0x8595a1FF; // silver
palette[11] = 0x6daa2cFF; // lime
palette[12] = 0xd2aa99FF; // skin
palette[13] = 0x6dc2caFF; // sky
palette[14] = 0xdad45eFF; // piss
palette[15] = 0xdeeed6FF; // white
{
var file = try std.fs.cwd().openRead(level_file ++ ".pcx");
defer file.close();
var img = try zgl.pcx.load(std.heap.c_allocator, &file);
errdefer img.deinit();
if (img == .bpp8) {
exampleTex.width = img.bpp8.width;
exampleTex.height = img.bpp8.height;
exampleTex.pixels = img.bpp8.pixels;
if (img.bpp8.palette) |pal| {
for (palette) |*col, i| {
const RGBA = packed struct {
x: u8 = 0,
b: u8,
g: u8,
r: u8,
};
var c: RGBA = .{
.r = pal[i].r,
.g = pal[i].g,
.b = pal[i].b,
};
col.* = @bitCast(u32, c);
}
}
} else {
img.deinit();
return error.InvalidTexture;
}
}
var model = try zgl.wavefrontObj.load(std.heap.c_allocator, level_file ++ ".obj");
std.debug.warn("model size: {}\n", .{model.faces.len});
var bestTime: f64 = 10000;
var worstTime: f64 = 0;
var totalTime: f64 = 0;
var totalFrames: f64 = 0;
var perfStats: [256]f64 = [_]f64{0} ** 256;
var perfPtr: u8 = 0;
const Camera = struct {
pan: f32,
tilt: f32,
position: zgl.math3d.Vec3,
};
var camera: Camera = .{
.pan = 0,
.tilt = 0,
.position = .{ .x = 0, .y = 0, .z = 0 },
};
var backBuffer = try rasterizer.Texture(u8).init(std.heap.c_allocator, screen.width, screen.height);
defer backBuffer.deinit();
var depthBuffer = try rasterizer.Texture(u32).init(std.heap.c_allocator, screen.width, screen.height);
defer depthBuffer.deinit();
const Context = rasterizer.Context(u8, .beautiful, 8);
// a bit weird construct, but this is required because
// result location isn't working right yet.
var softwareRenderer: Context = undefined;
try softwareRenderer.init();
defer softwareRenderer.deinit();
try softwareRenderer.setRenderTarget(&backBuffer, &depthBuffer);
var fcount: usize = 0;
mainLoop: while (true) : (fcount += 1) {
while (SDL.pollEvent()) |ev| {
switch (ev) {
.quit => {
break :mainLoop;
},
.keyDown => |key| {
switch (key.keysym.scancode) {
.SDL_SCANCODE_ESCAPE => break :mainLoop,
else => std.debug.warn("key pressed: {}\n", .{key.keysym.scancode}),
}
},
else => {},
}
}
const kbd = SDL.getKeyboardState();
var speed = if (kbd.isPressed(.SDL_SCANCODE_LSHIFT)) @as(f32, 100.0) else @as(f32, 1);
if (kbd.isPressed(.SDL_SCANCODE_LEFT))
camera.pan += 0.015;
if (kbd.isPressed(.SDL_SCANCODE_RIGHT))
camera.pan -= 0.015;
if (kbd.isPressed(.SDL_SCANCODE_PAGEUP))
camera.tilt += 0.015;
if (kbd.isPressed(.SDL_SCANCODE_PAGEDOWN))
camera.tilt -= 0.015;
const camdir = angleToVec3(camera.pan, camera.tilt);
if (kbd.isPressed(.SDL_SCANCODE_UP))
camera.position = camera.position.add(camdir.scale(speed * 0.01));
if (kbd.isPressed(.SDL_SCANCODE_DOWN))
camera.position = camera.position.add(camdir.scale(speed * -0.01));
const angle = 0.0007 * @intToFloat(f32, SDL.getTicks());
backBuffer.fill(0); // Fill with "background/transparent"
depthBuffer.fill(std.math.maxInt(u32));
const persp = zgl.math3d.Mat4.createPerspective(
60.0 * std.math.tau / 360.0,
4.0 / 3.0,
0.01,
10000.0,
);
const view = zgl.math3d.Mat4.createLookAt(camera.position, camera.position.add(camdir), zgl.math3d.Vec3.unitY);
var timer = try std.time.Timer.start();
var visible_polycount: usize = 0;
var total_polycount: usize = 0;
{
softwareRenderer.beginFrame();
defer softwareRenderer.endFrame();
const world = zgl.math3d.Mat4.identity; // (5.0 * worldX, 0.0, 5.0 * worldZ); // createAngleAxis(.{ .x = 0, .y = 1, .z = 0 }, angle);
const mvp = world.mul(view).mul(persp);
const faces = model.faces.toSliceConst();
const positions = model.positions.toSliceConst();
const uvCoords = model.textureCoordinates.toSliceConst();
for (model.objects.toSliceConst()) |obj| {
var i: usize = 0;
face: while (i < obj.count) : (i += 1) {
const src_face = faces[obj.start + i];
if (src_face.count != 3)
continue;
total_polycount += 1;
var face = rasterizer.Face(u8){
.vertices = undefined,
.texture = &exampleTex,
};
for (face.vertices) |*vert, j| {
const vtx = src_face.vertices[j];
const local_pos = positions[vtx.position];
var screen_pos = local_pos.swizzle("xyz1").transform(mvp);
if (std.math.fabs(screen_pos.w) <= 1e-9)
continue :face;
var linear_screen_pos = screen_pos.swizzle("xyz").scale(1.0 / screen_pos.w);
if (screen_pos.w < 0)
continue :face;
if (std.math.fabs(linear_screen_pos.x) > 3.0)
continue :face;
if (std.math.fabs(linear_screen_pos.y) > 3.0)
continue :face;
// std.debug.warn("{d} {d}\n", .{ linear_screen_pos.x, linear_screen_pos.y });
vert.x = @floatToInt(i32, @floor(screen.width * (0.5 + 0.5 * linear_screen_pos.x)));
vert.y = @floatToInt(i32, @floor(screen.height * (0.5 - 0.5 * linear_screen_pos.y)));
vert.z = linear_screen_pos.z;
vert.u = uvCoords[vtx.textureCoordinate.?].x;
vert.v = 1.0 - uvCoords[vtx.textureCoordinate.?].y;
}
// (B - A) x (C - A)
var winding = zgl.math3d.Vec3.cross(.{
.x = @intToFloat(f32, face.vertices[1].x - face.vertices[0].x),
.y = @intToFloat(f32, face.vertices[1].y - face.vertices[0].y),
.z = 0,
}, .{
.x = @intToFloat(f32, face.vertices[2].x - face.vertices[0].x),
.y = @intToFloat(f32, face.vertices[2].y - face.vertices[0].y),
.z = 0,
});
if (winding.z < 0)
continue;
visible_polycount += 1;
try softwareRenderer.renderPolygonTextured(face);
}
}
}
{
var time = @intToFloat(f64, timer.read()) / 1000.0;
totalTime += time;
totalFrames += 1;
bestTime = std.math.min(bestTime, time);
worstTime = std.math.max(worstTime, time);
std.debug.warn("total time: {d: >10.3}µs\ttriangle time: {d: >10.3}µs\tpoly count: {}/{}\n", .{
time,
time / @intToFloat(f64, visible_polycount),
visible_polycount,
total_polycount,
});
perfStats[perfPtr] = time;
perfPtr +%= 1;
}
// Update the screen buffer
{
var rgbaScreen: [screen.height][screen.width]u32 = undefined;
for (rgbaScreen) |*row, y| {
for (row) |*pix, x| {
pix.* = palette[backBuffer.getPixel(x, y)];
}
}
try texture.update(@sliceToBytes(rgbaScreen[0..]), screen.width * 4, null);
}
try renderer.setColorRGB(0, 0, 0);
try renderer.clear();
try renderer.copy(texture, null, null);
try renderer.setDrawBlendMode(.SDL_BLENDMODE_BLEND);
{
const getY = struct {
fn getY(v: f64) i32 {
return 256 - @floatToInt(i32, @round(256 * v / 17000));
}
}.getY;
try renderer.setColor(SDL.Color.parse("#FFFFFF40") catch unreachable);
try renderer.fillRect(.{
.x = 0,
.y = 0,
.width = 256,
.height = 256,
});
try renderer.setColor(SDL.Color.parse("#00000080") catch unreachable);
var ms: f64 = 1;
while (ms <= 16) : (ms += 1) {
try renderer.drawLine(0, getY(ms * 1000), 256, getY(ms * 1000));
}
try renderer.drawLine(0, getY(0), 256, getY(0));
try renderer.setColor(SDL.Color.parse("#FF8000") catch unreachable);
{
var i: u8 = 0;
while (i < 255) : (i += 1) {
var t0 = perfStats[perfPtr +% i +% 0];
var t1 = perfStats[perfPtr +% i +% 1];
try renderer.drawLine(i + 0, getY(t0), i + 1, getY(t1));
}
}
try renderer.setColor(SDL.Color.parse("#00FF00") catch unreachable);
try renderer.drawLine(0, getY(bestTime), 256, getY(bestTime));
try renderer.setColor(SDL.Color.parse("#FF0000") catch unreachable);
try renderer.drawLine(0, getY(worstTime), 256, getY(worstTime));
try renderer.setColor(SDL.Color.parse("#FFFFFF") catch unreachable);
try renderer.drawLine(0, getY(totalTime / totalFrames), 256, getY(totalTime / totalFrames));
}
renderer.present();
}
std.debug.warn("best time: {d: >10.3}µs\n", .{bestTime});
std.debug.warn("avg time: {d: >10.3}µs\n", .{totalTime / totalFrames});
std.debug.warn("worst time: {d: >10.3}µs\n", .{worstTime});
}
fn angleToVec3(pan: f32, tilt: f32) zgl.math3d.Vec3 {
return .{
.x = std.math.sin(pan) * std.math.cos(tilt),
.y = std.math.sin(tilt),
.z = -std.math.cos(pan) * std.math.cos(tilt),
};
}
/// wraps gameMain, so we can react to an SdlError and print
/// its error message
pub fn main() !void {
gameMain() catch |err| switch (err) {
error.SdlError => {
std.debug.warn("SDL Failure: {}\n", .{SDL.getError()});
return err;
},
else => return err,
};
} | src/main.zig |
const std = @import("std");
const util = @import("util.zig");
// const Scanner = @import("scan.zig").Scanner;
/// These are the delimiters that will be used as tokens.
const DelimiterToken = enum(u8) {
Percent = '%', // 0x25 37
OpenParen = '(', // 0x28 40
CloseParen = ')', // 0x29 41
Plus = '+', // 0x2B 43
Equals = '=', // 0x3D 61
Question = '?', // 0x3F 63
OpenSquare = '[', // 0x5B 91
CloseSquare = ']', // 0x5D 93
OpenCurly = '{', // 0x7B 123
CloseCurly = '}', // 0x7D 125
};
/// These are the delimiters that will NOT be used as tokens.
const DelimiterNonToken = enum(u8) {
Tab = '\t', // 0x09 9
LineFeed = '\n', // 0x0A 10
CarriageReturn = '\r', // 0x0D 13
Space = ' ', // 0x20 32
Quote = '"', // 0x22 34
Dollar = '$', // 0x24 36
Comma = ',', // 0x2C 44
Dot = '.', // 0x2E 46
ReverseSolidus = '\\', // 0x5C 92
};
/// A enum that represents all individual delimiters (regardless of their use as actual tokens).
const Delimiter = @Type(blk: {
const fields = @typeInfo(DelimiterToken).Enum.fields ++ @typeInfo(DelimiterNonToken).Enum.fields ++ &[_]std.builtin.TypeInfo.EnumField{.{ .name = "None", .value = 0 }};
break :blk .{
.Enum = .{
.layout = .Auto,
.tag_type = u8,
.decls = &[_]std.builtin.TypeInfo.Declaration{},
.fields = fields,
.is_exhaustive = true,
},
};
});
/// Since we need to iterate through the delimiters sometimes, we have this slice of them.
const delimiters = blk: {
var delims: []const u8 = &[_]u8{};
inline for (std.meta.fields(Delimiter)) |d| {
if (d.value > 0) { // ignore the None field
delims = delims ++ &[_]u8{d.value};
}
}
break :blk delims;
};
/// Special token types (usually a combination of Delimiters and strings)
const SpecialToken = enum(u8) {
None = 0,
Newline,
Comment,
String,
RawString,
MacroKey,
MacroParamKey,
MacroAccessor,
};
// The final TokenType comprised of SpecialTokens and DelimiterTokens.
pub const TokenType = @Type(out: {
const fields = @typeInfo(SpecialToken).Enum.fields ++ @typeInfo(DelimiterToken).Enum.fields;
break :out .{
.Enum = .{
.layout = .Auto,
.tag_type = u8,
.decls = &[_]std.builtin.TypeInfo.Declaration{},
.fields = fields,
.is_exhaustive = true,
},
};
});
/// Token - We store only the starting offset and the size instead of slices because we don't want
/// to deal with carrying around pointers and all of the stuff that goes with that.
pub const Token = struct {
/// The offset into the file where this token begins.
offset: usize = undefined,
/// The number of bytes in this token.
size: usize = 0,
/// The line in the file where this token was discovered. This is based on the number of
/// newline tokens the Tokenizer has encountered. If the calling code has altered the cursor
line: usize = undefined,
/// The type of this token (duh)
token_type: TokenType = .None,
/// Whether this token is a valid ZOMB token.
is_valid: bool = false,
const Self = @This();
/// Given the original input, return the slice of that input which this token represents.
pub fn slice(self: Self, buffer_: []const u8) ![]const u8 {
if (self.offset > buffer_.len) {
return error.TokenOffsetTooBig;
}
if (self.offset + self.size > buffer_.len) {
return error.TokenSizeTooBig;
}
return buffer_[self.offset .. self.offset + self.size];
}
pub fn log(self: Self, writer_: anytype, input_: []const u8) anyerror!void {
if (!util.DEBUG) return;
try writer_.print(
\\----[Token]----
\\Type = {}
\\Value = {s}
\\Line = {}
\\Valid = {}
\\
, .{
self.token_type,
try self.slice(input_),
self.line,
self.is_valid,
}
);
}
};
/// Parses tokens from the given input buffer.
pub const Tokenizer = struct {
const Self = @This();
const State = enum {
None,
QuotedString,
MacroX,
BareString,
RawString,
BareStringOrComment,
};
state: State = State.None,
state_stage: u8 = 0,
crlf: bool = false,
/// The input buffer
buffer: []const u8 = undefined,
buffer_cursor: usize = 0,
current_line: usize = 1,
at_end_of_buffer: bool = false,
/// This Tokenizer is capable of parsing buffered (or streaming) input, so we keep track of how
/// many buffers we've parsed.
buffer_index: usize = 0,
/// The token currently being discovered
token: Token = Token{},
pub fn log(self: Self, writer_: anytype) std.os.WriteError!void {
if (!util.DEBUG) return;
try writer_.print(
\\----[Tokenizer]----
\\State = {}
\\Stage = {}
\\Line = {}
\\End = {}
\\
, .{
self.state,
self.state_stage,
self.current_line,
self.at_end_of_buffer,
}
);
}
pub fn init(buffer_: []const u8) Self {
return Self{
.buffer = buffer_,
};
}
fn tokenComplete(self: *Self) void {
self.state = State.None;
self.token.is_valid = true;
}
fn tokenMaybeComplete(self: *Self) void {
self.token.is_valid = true;
}
fn tokenNotComplete(self: *Self) void {
self.token.is_valid = false;
}
/// Get the next token. Cases where a valid token is not found indicate that either EOF has been
/// reached or the current input buffer (when streaming the input) needs to be refilled. If an
/// error is encountered, the error is returned.
pub fn next(self: *Self) !?Token {
if (self.at_end_of_buffer) {
return null;
}
while (!self.at_end_of_buffer) {
// std.log.err(
// \\
// \\State = {} (stage = {})
// \\Token = {}
// \\Slice = {s}
// \\Byte = {c}
// \\
// , .{self.state, self.state_stage, self.token, self.token.slice(self.buffer), self.peek().?});
switch (self.state) {
.None => {
if ((try self.skipSeparators()) == false) return null;
self.token = Token{
.offset = self.buffer_cursor,
.line = self.current_line,
};
self.state_stage = 0;
const byte = self.peek().?;
const byte_as_delimiter = std.meta.intToEnum(Delimiter, byte) catch Delimiter.None;
switch (byte_as_delimiter) {
.Quote => {
self.token.token_type = TokenType.String;
self.state = State.QuotedString;
},
.Dollar => {
self.token.token_type = TokenType.MacroKey;
self.state = State.MacroX;
},
.Percent => {
self.token.token_type = TokenType.MacroParamKey;
self.state = State.MacroX;
},
.Dot => {
self.token.token_type = TokenType.MacroAccessor;
self.state = State.MacroX;
},
.ReverseSolidus => {
self.state = State.RawString;
},
.None => {
switch (byte) {
0x00...0x1F => return error.InvalidControlCharacter,
'/' => self.state = State.BareStringOrComment,
else => {
self.token.token_type = TokenType.String;
self.state = State.BareString;
},
}
},
else => {
_ = self.consume();
self.token.token_type = std.meta.intToEnum(TokenType, byte) catch unreachable;
self.tokenComplete();
return self.token;
},
}
},
.QuotedString => switch (self.state_stage) {
0 => { // starting quotation mark
if (self.advance().? != '"') return error.UnexpectedCommonQuotedStringStage0Byte;
self.token.offset = self.buffer_cursor;
self.state_stage = 1;
},
1 => if (self.consumeToBytes("\\\"")) |_| { // non-escaped bytes or ending quotation mark
switch (self.peek().?) {
'"' => {
_ = self.advance();
self.tokenComplete();
return self.token;
},
'\\' => {
_ = self.consume();
self.state_stage = 2; // consume the escape sequence from stage 3
},
else => unreachable,
}
},
2 => switch (try self.consumeEscapedByte()) { // escaped byte
'u' => self.state_stage = 3,
else => self.state_stage = 1,
},
3 => { // hex 1
try self.consumeHex();
self.state_stage = 4;
},
4 => { // hex 2
try self.consumeHex();
self.state_stage = 5;
},
5 => { // hex 3
try self.consumeHex();
self.state_stage = 6;
},
6 => { // hex 4
try self.consumeHex();
self.state_stage = 1;
},
else => return error.UnexpectedCommonQuotedStringStage,
},
.MacroX => switch (self.state_stage) {
0 => switch (self.peek().?) { // initial delimiter
'$', '.' => {
_ = self.advance().?;
self.state_stage = 2;
},
'%' => {
_ = self.consume().?;
self.state_stage = 1;
},
else => return error.UnexpectedMacroXStage0Byte,
},
1 => switch (self.peek().?) { // possible single percent token
' ', '\t', '\r', '\n', '[' => {
self.token.token_type = TokenType.Percent;
self.tokenComplete();
return self.token;
},
else => { // reverse the consumption of the percent delimiter
self.token.size -= 1;
self.state_stage = 2;
},
},
2 => {
switch (self.peek().?) {
'"' => {
self.state_stage = 0;
self.state = State.QuotedString;
},
else => self.state = State.BareString,
}
self.token.offset = self.buffer_cursor;
},
else => return error.UnexpectedMacroXStage,
},
.BareString => {
if (self.consumeToBytes(delimiters) != null) {
self.tokenComplete();
return self.token;
}
// we've reached the end of the buffer without knowing if we've completed this bare string token,
// however, bare strings are technically valid all the way to EOF, so we mark it as such, but we
// stay in this state in case there's more input and this bare string continues
self.tokenMaybeComplete();
},
.RawString => switch (self.state_stage) {
0 => { // first reverse solidus
if (self.advance().? != '\\') return error.UnexpectedRawStringStage0Byte;
self.state_stage = 1;
},
1 => { // second reverse solidus
if (self.advance().? != '\\') return error.UnexpectedRawStringStage1Byte;
// we may be continuing a raw string and since raw string tokens are broken into
// their individual lines (for parsing reasons) we need to make sure this is a new token and not
// a continuation of the previous one
self.token = Token{
.offset = self.buffer_cursor,
.line = self.current_line,
.token_type = TokenType.RawString,
};
// ex -> key = \\this is the rest of the string<EOF>
// ^ ^^ ^...raw string end + file end
// | ||...start of buffer 2 + start of raw string
// | |...end of buffer 1
// |...file start + start of buffer 1
self.tokenMaybeComplete();
self.state_stage = 2;
},
2 => if (self.consumeToBytes("\r\n")) |_| { // all bytes to (and including) end of line
switch (self.advance().?) { // don't consume the newline yet
'\r' => {
self.crlf = true;
self.state_stage = 3;
self.tokenNotComplete();
},
'\n' => {
self.crlf = false;
self.state_stage = 4;
},
else => unreachable,
}
},
3 => { // ending linefeed for CRLF
if (self.advance().? != '\n') return error.UnexpectedRawStringStage3Byte;
self.state_stage = 4;
self.tokenMaybeComplete();
},
4 => if (self.skipWhileBytes("\t ") != null) { // leading white space
self.state_stage = 5;
},
5 => switch (self.peek().?) { // next raw string or end of raw string
'\\' => {
self.state_stage = 0;
// since we're continuing this raw string on the next line, count the previous
// newline as part of this string
self.token.size += @as(usize, if (self.crlf) 2 else 1);
// we know we'll be continuing a raw string and since raw string tokens are
// broken into their individual lines (for parsing reasons) we return this one
return self.token;
},
else => {
self.tokenComplete();
return self.token;
},
},
else => return error.UnexpectedRawStringStage,
},
.BareStringOrComment => switch (self.state_stage) {
0 => {
if (self.consume().? != '/') return error.UnexpectedBareStringOrCommentStage0Byte;
self.state_stage = 1;
// so far, this is a valid bare string
self.token.token_type = TokenType.String;
self.tokenMaybeComplete();
},
1 => {
switch (self.peek().?) {
'/' => {
self.token.token_type = TokenType.Comment;
self.state_stage = 2;
},
else => {
self.state = State.BareString;
},
}
},
2 => if (self.consumeToBytes("\r\n") != null) {
self.tokenComplete();
return self.token;
},
else => return error.UnexpectedBareStringOrCommentStage,
},
} // end state switch
} // end :loop
std.log.info("Buffer depleted!", .{});
return self.token;
}
// ---- Scanning Operations
/// Returns the byte currently pointed to by the buffer cursor. If the buffer cursor points to
/// the end of the buffer, then `null` is returned.
fn peek(self: Self) ?u8 {
if (self.at_end_of_buffer) {
return null;
}
return self.buffer[self.buffer_cursor];
}
/// Advances the buffer cursor to the next byte, and returns the byte that the cursor previously
/// pointed to. This also increments the current line if the byte returned is `\n`. If the input
/// cursor already points to the end of the buffer, then `null` is returned.
fn advance(self: *Self) ?u8 {
if (self.at_end_of_buffer) {
return null;
}
self.buffer_cursor += 1;
self.at_end_of_buffer = self.buffer_cursor == self.buffer.len;
const byte = self.buffer[self.buffer_cursor - 1];
if (byte == '\n') self.current_line += 1;
return byte;
}
/// Advances the buffer cursor to the next byte, saves and adds the byte previously pointed to
/// by the buffer cursor to the token size (i.e. consumes it), and returns that previous byte.
/// If the buffer cursor already pointed to the end of the buffer, then `null` is returned.
fn consume(self: *Self) ?u8 {
if (self.advance()) |byte| {
self.token.size += 1;
return byte;
}
return null;
}
/// Consume all bytes until one of the target bytes is found, and return that target byte. If
/// the buffer cursor points to the end of the buffer, this returns `null`.
fn consumeToBytes(self: *Self, targets_: []const u8) ?u8 {
while (self.peek()) |byte| {
for (targets_) |target| {
if (byte == target) {
return byte;
}
}
_ = self.consume();
}
// We didn't find any of the target bytes, and we've exhausted the buffer.
return null;
}
/// Skips all bytes while they match one of the given targets, and return the first byte that
/// does not match a target. If the buffer cursor points to the end of the buffer, this returns
/// `null`.
fn skipWhileBytes(self: *Self, targets_: []const u8) ?u8 {
peekloop: while (self.peek()) |byte| {
for (targets_) |target| {
if (byte == target) {
_ = self.advance();
continue :peekloop;
}
}
// The byte we're looking at did not match any target, so return.
return byte;
}
return null; // we've exhausted the buffer
}
/// Consumes (and returns) the next byte and expects it to be a valid escaped byte.
fn consumeEscapedByte(self: *Self) !u8 {
if (self.consume()) |byte| {
switch (byte) {
'b', 'f', 'n', 'r', 't', 'u', '\\', '\"' => return byte,
else => return error.InvalidEscapedByte,
}
}
return error.InvalidEscapedByte;
}
/// Consumes the next byte and expects it to be a valid HEX character.
fn consumeHex(self: *Self) !void {
if (self.consume()) |byte| {
switch (byte) {
'0'...'9', 'A'...'F', 'a'...'f' => return,
else => return error.InvalidHex,
}
}
return error.InvalidHex;
}
/// Advances the buffer cursor until a non-separator byte is encountered and returns `true`. If
/// no non-separator is encountered, this returns `false`. If more than one comma is encountered
/// then `error.TooManyCommas` is returned. If an invalid CRLF is encountered then
/// `error.CarriageReturnError` is returned.
fn skipSeparators(self: *Self) !bool {
var found_comma = false;
while (self.peek()) |byte| {
switch (byte) {
' ', '\t', '\n' => {
_ = self.advance();
},
'\r' => { // TODO: is this block necessary?
_ = self.advance();
if ((self.peek() orelse 0) == '\n') {
_ = self.advance();
} else {
return error.CarriageReturnError;
}
},
',' => {
if (found_comma) {
return error.TooManyCommas;
}
found_comma = true;
_ = self.advance();
},
else => return true,
}
}
return false;
}
}; // end Tokenizer struct
//==============================================================================
//
//
//
// Testing
//==============================================================================
const testing = std.testing;
const test_allocator = testing.allocator;
/// A structure describing the expected token.
const ExpectedToken = struct {
str: []const u8,
line: usize,
token_type: TokenType,
// most tests should expect the token to be valid, so make that the default
is_valid: bool = true,
};
fn expectToken(expected_token_: ExpectedToken, token_: Token, orig_str_: []const u8) !void {
const str = try token_.slice(orig_str_);
var ok = true;
testing.expectEqualStrings(expected_token_.str, str) catch {
ok = false;
};
testing.expectEqual(expected_token_.line, token_.line) catch {
ok = false;
};
testing.expectEqual(expected_token_.token_type, token_.token_type) catch {
ok = false;
};
testing.expectEqual(expected_token_.is_valid, token_.is_valid) catch {
ok = false;
};
if (!ok) {
return error.TokenTestFailure;
}
}
fn doTokenTest(str_: []const u8, expected_tokens_: []const ExpectedToken) !void {
var tokenizer = Tokenizer.init(str_);
for (expected_tokens_) |expected_token, i| {
const actual_token = (try tokenizer.next()) orelse return error.NullToken;
errdefer {
std.debug.print(
\\
\\Expected (#{}):
\\ ExpectedToken{{ .str = "{s}", .line = {}, .token_type = {} }}
\\Actual:
\\ {}
\\
\\
, .{ i, expected_token.str, expected_token.line, expected_token.token_type, actual_token });
}
try expectToken(expected_token, actual_token, str_);
}
}
test "simple comment" {
const str = "// this is a comment";
const expected_tokens = [_]ExpectedToken{
ExpectedToken{ .str = str, .line = 1, .token_type = TokenType.Comment },
};
try doTokenTest(str, &expected_tokens);
}
test "comment at end of line" {
const str =
\\name = Zooce // this is a comment
\\one = 12345// this is not a comment
;
const expected_tokens = [_]ExpectedToken{
ExpectedToken{ .str = "name", .line = 1, .token_type = TokenType.String },
ExpectedToken{ .str = "=", .line = 1, .token_type = TokenType.Equals },
ExpectedToken{ .str = "Zooce", .line = 1, .token_type = TokenType.String },
ExpectedToken{ .str = "// this is a comment", .line = 1, .token_type = TokenType.Comment },
ExpectedToken{ .str = "one", .line = 2, .token_type = TokenType.String },
ExpectedToken{ .str = "=", .line = 2, .token_type = TokenType.Equals },
ExpectedToken{ .str = "12345//", .line = 2, .token_type = TokenType.String },
ExpectedToken{ .str = "this", .line = 2, .token_type = TokenType.String },
ExpectedToken{ .str = "is", .line = 2, .token_type = TokenType.String },
ExpectedToken{ .str = "not", .line = 2, .token_type = TokenType.String },
ExpectedToken{ .str = "a", .line = 2, .token_type = TokenType.String },
ExpectedToken{ .str = "comment", .line = 2, .token_type = TokenType.String },
};
try doTokenTest(str, &expected_tokens);
}
// TODO: test complex comment - i.e. make sure no special Unicode characters mess this up
test "bare strings" {
// IMPORTANT - this string is only for testing - it is not a valid zombie-file string
const str = "I am.a,bunch{of\nstrings 01abc 123xyz=%d";
const expected_tokens = [_]ExpectedToken{
ExpectedToken{ .str = "I", .line = 1, .token_type = TokenType.String },
ExpectedToken{ .str = "am", .line = 1, .token_type = TokenType.String },
ExpectedToken{ .str = "a", .line = 1, .token_type = TokenType.MacroAccessor },
ExpectedToken{ .str = "bunch", .line = 1, .token_type = TokenType.String },
ExpectedToken{ .str = "{", .line = 1, .token_type = TokenType.OpenCurly },
ExpectedToken{ .str = "of", .line = 1, .token_type = TokenType.String },
ExpectedToken{ .str = "strings", .line = 2, .token_type = TokenType.String },
ExpectedToken{ .str = "01abc", .line = 2, .token_type = TokenType.String },
ExpectedToken{ .str = "123xyz", .line = 2, .token_type = TokenType.String },
ExpectedToken{ .str = "=", .line = 2, .token_type = TokenType.Equals },
ExpectedToken{ .str = "d", .line = 2, .token_type = TokenType.MacroParamKey },
};
try doTokenTest(str, &expected_tokens);
}
test "quoted string" {
const str = "\"this is a \\\"quoted\\\" string\\u1234 \\t\\r\\n$(){}[].,=\"";
const expected_tokens = [_]ExpectedToken{
ExpectedToken{ .str = str[1 .. str.len - 1], .line = 1, .token_type = TokenType.String },
};
try doTokenTest(str, &expected_tokens);
}
// raw String Tests
test "basic raw string" {
const str =
\\\\line one
\\\\line two
\\\\line three
\\
;
const expected_tokens = [_]ExpectedToken{
ExpectedToken{ .str = "line one\n", .line = 1, .token_type = TokenType.RawString },
ExpectedToken{ .str = "line two\n", .line = 2, .token_type = TokenType.RawString },
ExpectedToken{ .str = "line three", .line = 3, .token_type = TokenType.RawString },
};
try doTokenTest(str, &expected_tokens);
}
test "raw string with leading space" {
const str =
\\ \\line one
\\ \\line two
\\ \\line three
\\
;
const expected_tokens = [_]ExpectedToken{
ExpectedToken{ .str = "line one\n", .line = 1, .token_type = TokenType.RawString },
ExpectedToken{ .str = "line two\n", .line = 2, .token_type = TokenType.RawString },
ExpectedToken{ .str = "line three", .line = 3, .token_type = TokenType.RawString },
};
try doTokenTest(str, &expected_tokens);
}
test "raw string at EOF" {
const str =
\\\\line one
\\\\line two
\\\\line three
;
const expected_tokens = [_]ExpectedToken{
ExpectedToken{ .str = "line one\n", .line = 1, .token_type = TokenType.RawString },
ExpectedToken{ .str = "line two\n", .line = 2, .token_type = TokenType.RawString },
ExpectedToken{ .str = "line three", .line = 3, .token_type = TokenType.RawString },
};
try doTokenTest(str, &expected_tokens);
}
test "string-raw-string kv-pair" {
const str =
\\key = \\first line
\\ \\ second line
\\ \\ third line
\\123 = 456
;
const expected_tokens = [_]ExpectedToken{
ExpectedToken{ .str = "key", .line = 1, .token_type = TokenType.String },
ExpectedToken{ .str = "=", .line = 1, .token_type = TokenType.Equals },
ExpectedToken{ .str = "first line\n", .line = 1, .token_type = TokenType.RawString },
ExpectedToken{ .str = " second line\n", .line = 2, .token_type = TokenType.RawString },
ExpectedToken{ .str = " third line", .line = 3, .token_type = TokenType.RawString },
ExpectedToken{ .str = "123", .line = 4, .token_type = TokenType.String },
ExpectedToken{ .str = "=", .line = 4, .token_type = TokenType.Equals },
ExpectedToken{ .str = "456", .line = 4, .token_type = TokenType.String },
};
try doTokenTest(str, &expected_tokens);
}
test "string-string concat" {
const str =
\\key = "hello, " + world
;
const expected_tokens = [_]ExpectedToken{
ExpectedToken{ .str = "key", .line = 1, .token_type = TokenType.String },
ExpectedToken{ .str = "=", .line = 1, .token_type = TokenType.Equals },
ExpectedToken{ .str = "hello, ", .line = 1, .token_type = TokenType.String },
ExpectedToken{ .str = "+", .line = 1, .token_type = TokenType.Plus },
ExpectedToken{ .str = "world", .line = 1, .token_type = TokenType.String },
};
try doTokenTest(str, &expected_tokens);
}
// TODO: the following tests aren't really testing macros - move these to the parsing file
test "simple macro declaration" {
const str =
\\$name = "Zooce Dark"
;
const expected_tokens = [_]ExpectedToken{
ExpectedToken{ .str = "name", .line = 1, .token_type = TokenType.MacroKey },
ExpectedToken{ .str = "=", .line = 1, .token_type = TokenType.Equals },
ExpectedToken{ .str = "Zooce Dark", .line = 1, .token_type = TokenType.String },
};
try doTokenTest(str, &expected_tokens);
}
test "macro object declaration" {
const str =
\\$black_forground = {
\\ foreground = #2b2b2b
\\}
;
const expected_tokens = [_]ExpectedToken{
ExpectedToken{ .str = "black_forground", .line = 1, .token_type = TokenType.MacroKey },
ExpectedToken{ .str = "=", .line = 1, .token_type = TokenType.Equals },
ExpectedToken{ .str = "{", .line = 1, .token_type = TokenType.OpenCurly },
ExpectedToken{ .str = "foreground", .line = 2, .token_type = TokenType.String },
ExpectedToken{ .str = "=", .line = 2, .token_type = TokenType.Equals },
ExpectedToken{ .str = "#2b2b2b", .line = 2, .token_type = TokenType.String },
ExpectedToken{ .str = "}", .line = 3, .token_type = TokenType.CloseCurly },
};
try doTokenTest(str, &expected_tokens);
}
// ref: https://zigforum.org/t/how-to-debug-zig-tests-with-gdb-or-other-debugger/487/4?u=zooce
// zig test ./test.zig --test-cmd gdb --test-cmd '--eval-command=run' --test-cmd-bin
// zig test src/token.zig --test-cmd lldb --test-cmd-bin
// zig test --test-filter "macro array declaration" src/token.zig --test-cmd lldb --test-cmd-bin
test "macro array declaration" {
const str =
\\$ports = [ 8000 8001 8002 ]
;
const expected_tokens = [_]ExpectedToken{
ExpectedToken{ .str = "ports", .line = 1, .token_type = TokenType.MacroKey },
ExpectedToken{ .str = "=", .line = 1, .token_type = TokenType.Equals },
ExpectedToken{ .str = "[", .line = 1, .token_type = TokenType.OpenSquare },
ExpectedToken{ .str = "8000", .line = 1, .token_type = TokenType.String },
ExpectedToken{ .str = "8001", .line = 1, .token_type = TokenType.String },
ExpectedToken{ .str = "8002", .line = 1, .token_type = TokenType.String },
ExpectedToken{ .str = "]", .line = 1, .token_type = TokenType.CloseSquare },
};
try doTokenTest(str, &expected_tokens);
}
test "macro with parameters declaration" {
const str =
\\$scope_def (scope settings) = {
\\ scope = %scope
\\ settings = %settings
\\}
;
const expected_tokens = [_]ExpectedToken{
ExpectedToken{ .str = "scope_def", .line = 1, .token_type = TokenType.MacroKey },
ExpectedToken{ .str = "(", .line = 1, .token_type = TokenType.OpenParen },
ExpectedToken{ .str = "scope", .line = 1, .token_type = TokenType.String },
ExpectedToken{ .str = "settings", .line = 1, .token_type = TokenType.String },
ExpectedToken{ .str = ")", .line = 1, .token_type = TokenType.CloseParen },
ExpectedToken{ .str = "=", .line = 1, .token_type = TokenType.Equals },
ExpectedToken{ .str = "{", .line = 1, .token_type = TokenType.OpenCurly },
ExpectedToken{ .str = "scope", .line = 2, .token_type = TokenType.String },
ExpectedToken{ .str = "=", .line = 2, .token_type = TokenType.Equals },
ExpectedToken{ .str = "scope", .line = 2, .token_type = TokenType.MacroParamKey },
ExpectedToken{ .str = "settings", .line = 3, .token_type = TokenType.String },
ExpectedToken{ .str = "=", .line = 3, .token_type = TokenType.Equals },
ExpectedToken{ .str = "settings", .line = 3, .token_type = TokenType.MacroParamKey },
ExpectedToken{ .str = "}", .line = 4, .token_type = TokenType.CloseCurly },
};
try doTokenTest(str, &expected_tokens);
}
test "quoted macro keys and parameters" {
const str =
\\$" ok = ." = 5
\\$" = {\""(" = ") = {
\\ scope = %" = "
\\}
\\
;
const expected_tokens = [_]ExpectedToken{
ExpectedToken{ .str = " ok = .", .line = 1, .token_type = TokenType.MacroKey },
ExpectedToken{ .str = "=", .line = 1, .token_type = TokenType.Equals },
ExpectedToken{ .str = "5", .line = 1, .token_type = TokenType.String },
ExpectedToken{ .str = " = {\\\"", .line = 2, .token_type = TokenType.MacroKey },
ExpectedToken{ .str = "(", .line = 2, .token_type = TokenType.OpenParen },
ExpectedToken{ .str = " = ", .line = 2, .token_type = TokenType.String },
ExpectedToken{ .str = ")", .line = 2, .token_type = TokenType.CloseParen },
ExpectedToken{ .str = "=", .line = 2, .token_type = TokenType.Equals },
ExpectedToken{ .str = "{", .line = 2, .token_type = TokenType.OpenCurly },
ExpectedToken{ .str = "scope", .line = 3, .token_type = TokenType.String },
ExpectedToken{ .str = "=", .line = 3, .token_type = TokenType.Equals },
ExpectedToken{ .str = " = ", .line = 3, .token_type = TokenType.MacroParamKey },
ExpectedToken{ .str = "}", .line = 4, .token_type = TokenType.CloseCurly },
};
try doTokenTest(str, &expected_tokens);
}
test "macro accessor" {
const str =
\\person = { name = Zooce,
\\ occupation = $job(a b c).occupations.0 }
;
const expected_tokens = [_]ExpectedToken{
ExpectedToken{ .str = "person", .line = 1, .token_type = TokenType.String },
ExpectedToken{ .str = "=", .line = 1, .token_type = TokenType.Equals },
ExpectedToken{ .str = "{", .line = 1, .token_type = TokenType.OpenCurly },
ExpectedToken{ .str = "name", .line = 1, .token_type = TokenType.String },
ExpectedToken{ .str = "=", .line = 1, .token_type = TokenType.Equals },
ExpectedToken{ .str = "Zooce", .line = 1, .token_type = TokenType.String },
ExpectedToken{ .str = "occupation", .line = 2, .token_type = TokenType.String },
ExpectedToken{ .str = "=", .line = 2, .token_type = TokenType.Equals },
ExpectedToken{ .str = "job", .line = 2, .token_type = TokenType.MacroKey },
ExpectedToken{ .str = "(", .line = 2, .token_type = TokenType.OpenParen },
ExpectedToken{ .str = "a", .line = 2, .token_type = TokenType.String },
ExpectedToken{ .str = "b", .line = 2, .token_type = TokenType.String },
ExpectedToken{ .str = "c", .line = 2, .token_type = TokenType.String },
ExpectedToken{ .str = ")", .line = 2, .token_type = TokenType.CloseParen },
ExpectedToken{ .str = "occupations", .line = 2, .token_type = TokenType.MacroAccessor },
ExpectedToken{ .str = "0", .line = 2, .token_type = TokenType.MacroAccessor },
};
try doTokenTest(str, &expected_tokens);
}
test "string-string kv-pair" {
const str = "key = value";
const expected_tokens = [_]ExpectedToken{
ExpectedToken{ .str = "key", .line = 1, .token_type = TokenType.String },
ExpectedToken{ .str = "=", .line = 1, .token_type = TokenType.Equals },
ExpectedToken{ .str = "value", .line = 1, .token_type = TokenType.String },
};
try doTokenTest(str, &expected_tokens);
}
test "number-number kv-pair" {
const str = "123 = 456";
const expected_tokens = [_]ExpectedToken{
ExpectedToken{ .str = "123", .line = 1, .token_type = TokenType.String },
ExpectedToken{ .str = "=", .line = 1, .token_type = TokenType.Equals },
ExpectedToken{ .str = "456", .line = 1, .token_type = TokenType.String },
};
try doTokenTest(str, &expected_tokens);
}
test "batching tokens" {
const str =
\\key =
\\ $m(? 3, ?) % [
\\ [ a b ]
\\ ]
;
const expected_tokens = [_]ExpectedToken{
ExpectedToken{ .str = "key", .line = 1, .token_type = TokenType.String },
ExpectedToken{ .str = "=", .line = 1, .token_type = TokenType.Equals },
ExpectedToken{ .str = "m", .line = 2, .token_type = TokenType.MacroKey },
ExpectedToken{ .str = "(", .line = 2, .token_type = TokenType.OpenParen },
ExpectedToken{ .str = "?", .line = 2, .token_type = TokenType.Question },
ExpectedToken{ .str = "3", .line = 2, .token_type = TokenType.String },
ExpectedToken{ .str = "?", .line = 2, .token_type = TokenType.Question },
ExpectedToken{ .str = ")", .line = 2, .token_type = TokenType.CloseParen },
ExpectedToken{ .str = "%", .line = 2, .token_type = TokenType.Percent },
ExpectedToken{ .str = "[", .line = 2, .token_type = TokenType.OpenSquare },
ExpectedToken{ .str = "[", .line = 3, .token_type = TokenType.OpenSquare },
ExpectedToken{ .str = "a", .line = 3, .token_type = TokenType.String },
ExpectedToken{ .str = "b", .line = 3, .token_type = TokenType.String },
ExpectedToken{ .str = "]", .line = 3, .token_type = TokenType.CloseSquare },
ExpectedToken{ .str = "]", .line = 4, .token_type = TokenType.CloseSquare },
};
try doTokenTest(str, &expected_tokens);
} | src/token.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const List = std.ArrayList;
const Map = std.AutoHashMap;
const StrMap = std.StringHashMap;
const BitSet = std.DynamicBitSet;
const Str = []const u8;
const util = @import("util.zig");
const gpa = util.gpa;
const data = @embedFile("../data/day02.txt");
const MoveDir = enum {
forward,
down,
up,
};
const Move = struct {
dir: MoveDir,
distance: i64,
};
fn parseInput(input_text: []const u8) std.ArrayList(Move) {
var list = std.ArrayList(Move).init(std.testing.allocator);
var lines = tokenize(u8, input_text, "\r\n");
while (lines.next()) |line| {
var tokens = tokenize(u8, line, " ");
const dir_str = tokens.next().?;
const dir: MoveDir = switch (dir_str[0]) {
'f' => .forward,
'd' => .down,
'u' => .up,
else => unreachable,
};
const dist = parseInt(i64, tokens.next().?, 10) catch unreachable;
list.append(Move{ .dir = dir, .distance = dist }) catch unreachable;
}
return list;
}
fn finalProductXY(input: std.ArrayList(Move)) i64 {
var horizontal: i64 = 0;
var depth: i64 = 0;
for (input.items) |move| {
switch (move.dir) {
.forward => {
horizontal += move.distance;
},
.down => {
depth += move.distance;
},
.up => {
depth -= move.distance;
},
}
}
return horizontal * depth;
}
fn finalProductXYWithAim(input: std.ArrayList(Move)) i64 {
var horizontal: i64 = 0;
var depth: i64 = 0;
var aim: i64 = 0;
for (input.items) |move| {
switch (move.dir) {
MoveDir.forward => {
horizontal += move.distance;
depth += aim * move.distance;
},
MoveDir.down => {
aim += move.distance;
},
MoveDir.up => {
aim -= move.distance;
},
}
}
return horizontal * depth;
}
pub fn main() !void {}
const test_data =
\\forward 5
\\down 5
\\forward 8
\\up 3
\\down 8
\\forward 2
;
test "part1" {
const test_input = parseInput(test_data);
defer test_input.deinit();
const result = finalProductXY(test_input);
try std.testing.expectEqual(@as(i64, 150), result);
const input = parseInput(data);
defer input.deinit();
try std.testing.expectEqual(@as(i64, 1804520), finalProductXY(input));
}
test "part2" {
const test_input = parseInput(test_data);
defer test_input.deinit();
try std.testing.expectEqual(@as(i64, 900), finalProductXYWithAim(test_input));
const input = parseInput(data);
defer input.deinit();
try std.testing.expectEqual(@as(i64, 1971095320), finalProductXYWithAim(input));
}
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const indexOf = std.mem.indexOfScalar;
const indexOfAny = std.mem.indexOfAny;
const indexOfStr = std.mem.indexOfPosLinear;
const lastIndexOf = std.mem.lastIndexOfScalar;
const lastIndexOfAny = std.mem.lastIndexOfAny;
const lastIndexOfStr = std.mem.lastIndexOfLinear;
const trim = std.mem.trim;
const sliceMin = std.mem.min;
const sliceMax = std.mem.max;
const parseInt = std.fmt.parseInt;
const parseFloat = std.fmt.parseFloat;
const min = std.math.min;
const min3 = std.math.min3;
const max = std.math.max;
const max3 = std.math.max3;
const print = std.debug.print;
const assert = std.debug.assert;
const sort = std.sort.sort;
const asc = std.sort.asc;
const desc = std.sort.desc; | src/day02.zig |
const std = @import("std");
const Arena = std.heap.ArenaAllocator;
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const panic = std.debug.panic;
const yeti = @import("yeti");
const initCodebase = yeti.initCodebase;
const analyzeSemantics = yeti.analyzeSemantics;
const codegen = yeti.codegen;
const printWasm = yeti.printWasm;
const printErrors = yeti.printErrors;
const List = yeti.List;
const components = yeti.components;
const FileSystem = struct {
const Files = List(std.fs.File, .{});
files: Files,
allocator: Allocator,
fn init(arena: *Arena) FileSystem {
return FileSystem{
.files = Files.init(arena.allocator()),
.allocator = arena.allocator(),
};
}
fn deinit(self: *FileSystem) void {
for (self.files.slice()) |file| {
file.close();
}
self.files.deinit();
}
pub fn read(self: *FileSystem, name: []const u8) error{ OutOfMemory, CantOpenFile }![]const u8 {
const file = std.fs.cwd().openFile(name, std.fs.File.OpenFlags{}) catch return error.CantOpenFile;
try self.files.append(file);
return file.readToEndAlloc(self.allocator, std.math.maxInt(i64)) catch return error.OutOfMemory;
}
};
pub fn main() !void {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const args = try std.process.argsAlloc(allocator);
assert(args.len == 2);
var fs = FileSystem.init(&arena);
defer fs.deinit();
var codebase = try initCodebase(&arena);
const yeti_filename = args[1];
const module = analyzeSemantics(codebase, &fs, yeti_filename) catch |e| switch (e) {
error.CompileError => {
const errors = try printErrors(codebase);
std.debug.print("{s}", .{errors});
return;
},
else => |err| panic("\ncompiler crashed with error {}\n", .{err}),
};
try codegen(module);
const wasm = try printWasm(module);
const foreign_exports = module.get(components.ForeignExports).slice();
const wat_filename = try allocator.alloc(u8, yeti_filename.len - 1);
const cutoff = yeti_filename.len - 4;
std.mem.copy(u8, wat_filename, yeti_filename[0..cutoff]);
std.mem.copy(u8, wat_filename[cutoff..], "wat");
const cwd = std.fs.cwd();
try cwd.writeFile(wat_filename, wasm);
if (foreign_exports.len > 0) {
_ = try std.ChildProcess.exec(.{
.allocator = arena.allocator(),
.argv = &.{ "wat2wasm", wat_filename },
});
return;
}
const result = try std.ChildProcess.exec(.{
.allocator = arena.allocator(),
.argv = &.{ "wasmtime", wat_filename },
});
std.debug.print("{s}", .{result.stdout});
try cwd.deleteFile(wat_filename);
} | src/main.zig |
const std = @import("std");
const stdx = @import("stdx");
const Duration = stdx.time.Duration;
const Function = stdx.Function;
const platform = @import("platform");
const MouseDownEvent = platform.MouseDownEvent;
const KeyDownEvent = platform.KeyDownEvent;
const graphics = @import("graphics");
const Color = graphics.Color;
const ui = @import("../ui.zig");
const Node = ui.Node;
const Padding = ui.widgets.Padding;
const log = stdx.log.scoped(.text_field);
const NullId = std.math.maxInt(u32);
/// Handles a single line of text input.
pub const TextField = struct {
props: struct {
bg_color: Color = Color.White,
text_color: Color = Color.Black,
focused_border_color: Color = Color.Blue,
font_id: graphics.FontId = NullId,
font_size: f32 = 20,
onChangeEnd: ?Function(fn ([]const u8) void) = null,
onKeyDown: ?Function(fn (ui.WidgetRef(Self), KeyDownEvent) void) = null,
padding: f32 = 10,
placeholder: ?[]const u8 = null,
width: ?f32 = null,
focused_show_border: bool = true,
},
buf: stdx.textbuf.TextBuffer,
inner: ui.WidgetRef(TextFieldInner),
/// Used to determine if the text changed since it received focus.
last_buf_hash: [16]u8,
ctx: *ui.CommonContext,
node: *Node,
const Self = @This();
pub fn init(self: *Self, c: *ui.InitContext) void {
self.buf = stdx.textbuf.TextBuffer.init(c.alloc, "") catch @panic("error");
self.last_buf_hash = undefined;
c.addKeyDownHandler(self, Self.onKeyDown);
c.addMouseDownHandler(self, Self.onMouseDown);
self.ctx = c.common;
self.node = c.node;
}
pub fn deinit(node: *Node, _: std.mem.Allocator) void {
const self = node.getWidget(Self);
self.buf.deinit();
}
pub fn build(self: *Self, c: *ui.BuildContext) ui.FrameId {
return c.decl(Padding, .{
.padding = self.props.padding,
.child = c.decl(TextFieldInner, .{
.bind = &self.inner,
.text = self.buf.buf.items,
.font_size = self.props.font_size,
.font_id = self.props.font_id,
.text_color = self.props.text_color,
.placeholder = self.props.placeholder,
}),
});
}
pub fn setValueFmt(self: *Self, comptime format: []const u8, args: anytype) void {
self.buf.clear();
self.buf.appendFmt(format, args);
self.ensureCaretPos();
}
pub fn clear(self: *Self) void {
self.buf.clear();
self.ensureCaretPos();
}
fn ensureCaretPos(self: *Self) void {
const inner = self.inner.getWidget();
if (inner.caret_idx > self.buf.num_chars) {
inner.caret_idx = self.buf.num_chars;
}
}
/// Request focus on the TextField.
pub fn requestFocus(self: *Self) void {
self.ctx.requestFocus(self.node, onBlur);
const inner = self.inner.getWidget();
inner.setFocused();
std.crypto.hash.Md5.hash(self.buf.buf.items, &self.last_buf_hash, .{});
}
pub fn getValue(self: Self) []const u8 {
return self.buf.buf.items;
}
fn onMouseDown(self: *Self, e: ui.MouseDownEvent) ui.EventResult {
const me = e.val;
self.requestFocus();
// Map mouse pos to caret pos.
const inner = self.inner.getWidget();
const xf = @intToFloat(f32, me.x);
inner.caret_idx = self.getCaretIdx(e.ctx.common, xf - inner.node.abs_pos.x + inner.scroll_x);
return .Continue;
}
fn onBlur(node: *Node, ctx: *ui.CommonContext) void {
_ = ctx;
const self = node.getWidget(Self);
self.inner.getWidget().focused = false;
var hash: [16]u8 = undefined;
std.crypto.hash.Md5.hash(self.buf.buf.items, &hash, .{});
if (!std.mem.eql(u8, &hash, &self.last_buf_hash)) {
self.fireOnChangeEnd();
}
}
fn fireOnChangeEnd(self: *Self) void {
if (self.props.onChangeEnd) |cb| {
cb.call(.{ self.buf.buf.items });
}
}
fn getCaretIdx(self: *Self, ctx: *ui.CommonContext, x: f32) u32 {
const font_gid = ctx.getFontGroupForSingleFontOrDefault(self.props.font_id);
var iter = ctx.textGlyphIter(font_gid, self.props.font_size, self.buf.buf.items);
if (iter.nextCodepoint()) {
if (x < iter.state.advance_width/2) {
return 0;
}
} else {
return 0;
}
var char_idx: u32 = 1;
var cur_x: f32 = iter.state.advance_width;
while (iter.nextCodepoint()) {
if (x < cur_x + iter.state.advance_width/2) {
return char_idx;
}
cur_x = @round(cur_x + iter.state.kern);
cur_x += iter.state.advance_width;
char_idx += 1;
}
return char_idx;
}
fn onKeyDown(self: *Self, e: ui.KeyDownEvent) void {
const ke = e.val;
// User onKeyDown is fired first. In the future this could let the user cancel the default behavior.
if (self.props.onKeyDown) |cb| {
cb.call(.{ ui.WidgetRef(Self).init(e.ctx.node), ke });
}
const inner = self.inner.getWidget();
if (ke.code == .Backspace) {
if (inner.caret_idx > 0) {
if (self.buf.num_chars == inner.caret_idx) {
self.buf.removeChar(self.buf.num_chars-1);
} else {
self.buf.removeChar(inner.caret_idx-1);
}
// self.postLineUpdate(self.caret_line);
inner.caret_idx -= 1;
inner.keepCaretFixedInView();
inner.resetCaretAnim();
}
} else if (ke.code == .Delete) {
if (inner.caret_idx < self.buf.num_chars) {
self.buf.removeChar(inner.caret_idx);
inner.keepCaretFixedInView();
inner.resetCaretAnim();
}
} else if (ke.code == .Enter) {
var hash: [16]u8 = undefined;
std.crypto.hash.Md5.hash(self.buf.buf.items, &hash, .{});
if (!std.mem.eql(u8, &hash, &self.last_buf_hash)) {
self.fireOnChangeEnd();
self.last_buf_hash = hash;
inner.resetCaretAnim();
}
} else if (ke.code == .ArrowLeft) {
if (inner.caret_idx > 0) {
inner.caret_idx -= 1;
inner.keepCaretInView();
inner.resetCaretAnim();
}
} else if (ke.code == .ArrowRight) {
if (inner.caret_idx < self.buf.num_chars) {
inner.caret_idx += 1;
inner.keepCaretInView();
inner.resetCaretAnim();
}
} else {
if (ke.getPrintChar()) |ch| {
if (inner.caret_idx == self.buf.num_chars) {
self.buf.appendCodepoint(ch) catch @panic("error");
} else {
self.buf.insertCodepoint(inner.caret_idx, ch) catch @panic("error");
}
// self.postLineUpdate(self.caret_line);
inner.caret_idx += 1;
inner.keepCaretInView();
inner.resetCaretAnim();
}
}
}
pub fn layout(self: *Self, c: *ui.LayoutContext) ui.LayoutSize {
const cstr = c.getSizeConstraint();
const child = c.getNode().children.items[0];
if (self.props.width) |width| {
const child_size = c.computeLayoutStretch(child, ui.LayoutSize.init(width, cstr.height), true, c.prefer_exact_height);
c.setLayout(child, ui.Layout.init(0, 0, child_size.width, child_size.height));
return child_size;
} else {
const child_size = c.computeLayoutStretch(child, cstr, c.prefer_exact_width, c.prefer_exact_height);
c.setLayout(child, ui.Layout.init(0, 0, child_size.width, child_size.height));
return child_size;
}
}
pub fn render(self: *Self, c: *ui.RenderContext) void {
_ = self;
const alo = c.getAbsLayout();
const g = c.getGraphics();
// Background.
g.setFillColor(self.props.bg_color);
g.fillRect(alo.x, alo.y, alo.width, alo.height);
if (c.isFocused() and self.props.focused_show_border) {
g.setStrokeColor(self.props.focused_border_color);
g.setLineWidth(2);
g.drawRect(alo.x, alo.y, alo.width, alo.height);
}
}
};
pub const TextFieldInner = struct {
props: struct {
text_color: Color = Color.Black,
font_size: f32 = 20,
font_id: graphics.FontId = NullId,
placeholder: ?[]const u8 = null,
text: []const u8 = "",
},
scroll_x: f32,
text_width: f32,
caret_idx: u32,
caret_pos_x: f32,
caret_anim_id: u32,
caret_anim_show: bool,
focused: bool,
ctx: *ui.CommonContext,
node: *Node,
/// [0,1]
fixed_in_view: f32,
const Self = @This();
pub fn init(self: *Self, c: *ui.InitContext) void {
self.scroll_x = 0;
self.caret_idx = 0;
self.caret_pos_x = 0;
self.caret_anim_show = true;
self.caret_anim_id = c.addInterval(Duration.initSecsF(0.6), self, onCaretInterval);
self.focused = false;
self.ctx = c.common;
self.node = c.node;
}
pub fn postPropsUpdate(self: *Self) void {
// Make sure caret_idx is in bounds.
if (self.caret_idx > self.props.text.len) {
self.caret_idx = @intCast(u32, self.props.text.len);
}
}
fn setFocused(self: *Self) void {
self.focused = true;
self.resetCaretAnim();
}
fn resetCaretAnim(self: *Self) void {
self.caret_anim_show = true;
self.ctx.resetInterval(self.caret_anim_id);
}
fn onCaretInterval(self: *Self, e: ui.IntervalEvent) void {
_ = e;
self.caret_anim_show = !self.caret_anim_show;
}
fn keepCaretFixedInView(self: *Self) void {
const S = struct {
fn cb(self_: *Self) void {
self_.scroll_x = self_.caret_pos_x - self_.fixed_in_view * self_.node.layout.width;
if (self_.scroll_x < 0) {
self_.scroll_x = 0;
}
}
};
self.fixed_in_view = (self.caret_pos_x - self.scroll_x) / self.node.layout.width;
if (self.fixed_in_view < 0) {
self.fixed_in_view = 0;
} else if (self.fixed_in_view > 1) {
self.fixed_in_view = 1;
}
self.ctx.nextPostLayout(self, S.cb);
}
fn keepCaretInView(self: *Self) void {
const S = struct {
fn cb(self_: *Self) void {
const layout_width = self_.node.layout.width;
if (self_.caret_pos_x > self_.scroll_x + layout_width - 2) {
// Caret is to the right of the view. Add a tiny padding since it's at the edge.
self_.scroll_x = self_.caret_pos_x - layout_width + 2;
} else if (self_.caret_pos_x < self_.scroll_x) {
// Caret is to the left of the view
self_.scroll_x = self_.caret_pos_x;
}
}
};
self.ctx.nextPostLayout(self, S.cb);
}
pub fn layout(self: *Self, c: *ui.LayoutContext) ui.LayoutSize {
const cstr = c.getSizeConstraint();
const font_gid = c.getFontGroupForSingleFontOrDefault(self.props.font_id);
const vmetrics = c.getPrimaryFontVMetrics(font_gid, self.props.font_size);
const metrics = c.measureText(font_gid, self.props.font_size, self.props.text);
self.text_width = metrics.width;
self.caret_pos_x = c.measureText(font_gid, self.props.font_size, self.props.text[0..self.caret_idx]).width;
var res = ui.LayoutSize.init(metrics.width, vmetrics.height);
if (c.prefer_exact_width) {
res.width = cstr.width;
} else if (res.width > cstr.width) {
res.width = cstr.width;
}
return res;
}
pub fn render(self: *Self, c: *ui.RenderContext) void {
const alo = c.getAbsLayout();
const g = c.getGraphics();
const needs_clipping = self.scroll_x > 0 or alo.width < self.text_width;
if (needs_clipping) {
g.pushState();
g.clipRect(alo.x, alo.y, alo.width, alo.height);
}
g.setFillColor(self.props.text_color);
if (self.props.font_id == NullId) {
g.setFont(g.getDefaultFontId(), self.props.font_size);
} else {
g.setFont(self.props.font_id, self.props.font_size);
}
g.fillText(alo.x - self.scroll_x, alo.y, self.props.text);
if (self.props.text.len == 0) {
if (self.props.placeholder) |placeholder| {
g.setFillColor(Color.init(100, 100, 100, 255));
g.fillText(alo.x, alo.y, placeholder);
}
}
// Draw caret.
if (self.focused) {
if (self.caret_anim_show) {
g.fillRect(@round(alo.x - self.scroll_x + self.caret_pos_x), alo.y, 1, alo.height);
}
}
if (needs_clipping) {
g.popState();
}
}
}; | ui/src/widgets/text_field.zig |
const std = @import("../index.zig");
const builtin = @import("builtin");
const Os = builtin.Os;
const is_windows = builtin.os == Os.windows;
const is_posix = switch (builtin.os) {
builtin.Os.linux, builtin.Os.macosx => true,
else => false,
};
const os = this;
test "std.os" {
_ = @import("child_process.zig");
_ = @import("darwin.zig");
_ = @import("darwin_errno.zig");
_ = @import("get_user_id.zig");
_ = @import("linux/index.zig");
_ = @import("path.zig");
_ = @import("test.zig");
_ = @import("time.zig");
_ = @import("windows/index.zig");
}
pub const windows = @import("windows/index.zig");
pub const darwin = @import("darwin.zig");
pub const linux = @import("linux/index.zig");
pub const zen = @import("zen.zig");
pub const posix = switch (builtin.os) {
Os.linux => linux,
Os.macosx, Os.ios => darwin,
Os.zen => zen,
else => @compileError("Unsupported OS"),
};
pub const net = @import("net.zig");
pub const ChildProcess = @import("child_process.zig").ChildProcess;
pub const path = @import("path.zig");
pub const File = @import("file.zig").File;
pub const time = @import("time.zig");
pub const FileMode = switch (builtin.os) {
Os.windows => void,
else => u32,
};
pub const default_file_mode = switch (builtin.os) {
Os.windows => {},
else => 0o666,
};
pub const page_size = 4 * 1024;
pub const UserInfo = @import("get_user_id.zig").UserInfo;
pub const getUserInfo = @import("get_user_id.zig").getUserInfo;
const windows_util = @import("windows/util.zig");
pub const windowsWaitSingle = windows_util.windowsWaitSingle;
pub const windowsWrite = windows_util.windowsWrite;
pub const windowsIsCygwinPty = windows_util.windowsIsCygwinPty;
pub const windowsOpen = windows_util.windowsOpen;
pub const windowsLoadDll = windows_util.windowsLoadDll;
pub const windowsUnloadDll = windows_util.windowsUnloadDll;
pub const createWindowsEnvBlock = windows_util.createWindowsEnvBlock;
pub const WindowsWaitError = windows_util.WaitError;
pub const WindowsOpenError = windows_util.OpenError;
pub const WindowsWriteError = windows_util.WriteError;
pub const FileHandle = if (is_windows) windows.HANDLE else i32;
const debug = std.debug;
const assert = debug.assert;
const c = std.c;
const mem = std.mem;
const Allocator = mem.Allocator;
const BufMap = std.BufMap;
const cstr = std.cstr;
const io = std.io;
const base64 = std.base64;
const ArrayList = std.ArrayList;
const Buffer = std.Buffer;
const math = std.math;
/// Fills `buf` with random bytes. If linking against libc, this calls the
/// appropriate OS-specific library call. Otherwise it uses the zig standard
/// library implementation.
pub fn getRandomBytes(buf: []u8) !void {
switch (builtin.os) {
Os.linux => while (true) {
// TODO check libc version and potentially call c.getrandom.
// See #397
const err = posix.getErrno(posix.getrandom(buf.ptr, buf.len, 0));
if (err > 0) {
switch (err) {
posix.EINVAL => unreachable,
posix.EFAULT => unreachable,
posix.EINTR => continue,
posix.ENOSYS => {
const fd = try posixOpenC(c"/dev/urandom", posix.O_RDONLY | posix.O_CLOEXEC, 0);
defer close(fd);
try posixRead(fd, buf);
return;
},
else => return unexpectedErrorPosix(err),
}
}
return;
},
Os.macosx, Os.ios => {
const fd = try posixOpenC(c"/dev/urandom", posix.O_RDONLY | posix.O_CLOEXEC, 0);
defer close(fd);
try posixRead(fd, buf);
},
Os.windows => {
var hCryptProv: windows.HCRYPTPROV = undefined;
if (windows.CryptAcquireContextA(&hCryptProv, null, null, windows.PROV_RSA_FULL, 0) == 0) {
const err = windows.GetLastError();
return switch (err) {
else => unexpectedErrorWindows(err),
};
}
defer _ = windows.CryptReleaseContext(hCryptProv, 0);
if (windows.CryptGenRandom(hCryptProv, @intCast(windows.DWORD, buf.len), buf.ptr) == 0) {
const err = windows.GetLastError();
return switch (err) {
else => unexpectedErrorWindows(err),
};
}
},
Os.zen => {
const randomness = []u8{ 42, 1, 7, 12, 22, 17, 99, 16, 26, 87, 41, 45 };
var i: usize = 0;
while (i < buf.len) : (i += 1) {
if (i > randomness.len) return error.Unknown;
buf[i] = randomness[i];
}
},
else => @compileError("Unsupported OS"),
}
}
test "os.getRandomBytes" {
var buf: [50]u8 = undefined;
try getRandomBytes(buf[0..]);
}
/// Raises a signal in the current kernel thread, ending its execution.
/// If linking against libc, this calls the abort() libc function. Otherwise
/// it uses the zig standard library implementation.
pub fn abort() noreturn {
@setCold(true);
if (builtin.link_libc) {
c.abort();
}
switch (builtin.os) {
Os.linux, Os.macosx, Os.ios => {
_ = posix.raise(posix.SIGABRT);
_ = posix.raise(posix.SIGKILL);
while (true) {}
},
Os.windows => {
if (builtin.mode == builtin.Mode.Debug) {
@breakpoint();
}
windows.ExitProcess(3);
},
else => @compileError("Unsupported OS"),
}
}
/// Exits the program cleanly with the specified status code.
pub fn exit(status: u8) noreturn {
@setCold(true);
if (builtin.link_libc) {
c.exit(status);
}
switch (builtin.os) {
Os.linux, Os.macosx, Os.ios => {
posix.exit(status);
},
Os.windows => {
windows.ExitProcess(status);
},
else => @compileError("Unsupported OS"),
}
}
/// When a file descriptor is closed on linux, it pops the first
/// node from this queue and resumes it.
/// Async functions which get the EMFILE error code can suspend,
/// putting their coroutine handle into this list.
/// TODO make this an atomic linked list
pub var emfile_promise_queue = std.LinkedList(promise).init();
/// Closes the file handle. Keeps trying if it gets interrupted by a signal.
pub fn close(handle: FileHandle) void {
if (is_windows) {
windows_util.windowsClose(handle);
} else {
while (true) {
const err = posix.getErrno(posix.close(handle));
switch (err) {
posix.EINTR => continue,
else => {
if (emfile_promise_queue.popFirst()) |p| resume p.data;
return;
},
}
}
}
}
/// Calls POSIX read, and keeps trying if it gets interrupted.
pub fn posixRead(fd: i32, buf: []u8) !void {
// Linux can return EINVAL when read amount is > 0x7ffff000
// See https://github.com/ziglang/zig/pull/743#issuecomment-363158274
const max_buf_len = 0x7ffff000;
var index: usize = 0;
while (index < buf.len) {
const want_to_read = math.min(buf.len - index, usize(max_buf_len));
const rc = posix.read(fd, buf.ptr + index, want_to_read);
const err = posix.getErrno(rc);
if (err > 0) {
return switch (err) {
posix.EINTR => continue,
posix.EINVAL, posix.EFAULT => unreachable,
posix.EAGAIN => error.WouldBlock,
posix.EBADF => error.FileClosed,
posix.EIO => error.InputOutput,
posix.EISDIR => error.IsDir,
posix.ENOBUFS, posix.ENOMEM => error.SystemResources,
else => unexpectedErrorPosix(err),
};
}
index += rc;
}
}
pub const PosixWriteError = error{
WouldBlock,
FileClosed,
DestinationAddressRequired,
DiskQuota,
FileTooBig,
InputOutput,
NoSpaceLeft,
AccessDenied,
BrokenPipe,
Unexpected,
};
/// Calls POSIX write, and keeps trying if it gets interrupted.
pub fn posixWrite(fd: i32, bytes: []const u8) !void {
// Linux can return EINVAL when write amount is > 0x7ffff000
// See https://github.com/ziglang/zig/pull/743#issuecomment-363165856
const max_bytes_len = 0x7ffff000;
var index: usize = 0;
while (index < bytes.len) {
const amt_to_write = math.min(bytes.len - index, usize(max_bytes_len));
const rc = posix.write(fd, bytes.ptr + index, amt_to_write);
const write_err = posix.getErrno(rc);
if (write_err > 0) {
return switch (write_err) {
posix.EINTR => continue,
posix.EINVAL, posix.EFAULT => unreachable,
posix.EAGAIN => PosixWriteError.WouldBlock,
posix.EBADF => PosixWriteError.FileClosed,
posix.EDESTADDRREQ => PosixWriteError.DestinationAddressRequired,
posix.EDQUOT => PosixWriteError.DiskQuota,
posix.EFBIG => PosixWriteError.FileTooBig,
posix.EIO => PosixWriteError.InputOutput,
posix.ENOSPC => PosixWriteError.NoSpaceLeft,
posix.EPERM => PosixWriteError.AccessDenied,
posix.EPIPE => PosixWriteError.BrokenPipe,
else => unexpectedErrorPosix(write_err),
};
}
index += rc;
}
}
pub const PosixOpenError = error{
OutOfMemory,
AccessDenied,
FileTooBig,
IsDir,
SymLinkLoop,
ProcessFdQuotaExceeded,
NameTooLong,
SystemFdQuotaExceeded,
NoDevice,
PathNotFound,
SystemResources,
NoSpaceLeft,
NotDir,
PathAlreadyExists,
Unexpected,
};
/// ::file_path needs to be copied in memory to add a null terminating byte.
/// Calls POSIX open, keeps trying if it gets interrupted, and translates
/// the return value into zig errors.
pub fn posixOpen(allocator: *Allocator, file_path: []const u8, flags: u32, perm: usize) PosixOpenError!i32 {
const path_with_null = try cstr.addNullByte(allocator, file_path);
defer allocator.free(path_with_null);
return posixOpenC(path_with_null.ptr, flags, perm);
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn posixOpenC(file_path: [*]const u8, flags: u32, perm: usize) !i32 {
while (true) {
const result = posix.open(file_path, flags, perm);
const err = posix.getErrno(result);
if (err > 0) {
switch (err) {
posix.EINTR => continue,
posix.EFAULT => unreachable,
posix.EINVAL => unreachable,
posix.EACCES => return PosixOpenError.AccessDenied,
posix.EFBIG, posix.EOVERFLOW => return PosixOpenError.FileTooBig,
posix.EISDIR => return PosixOpenError.IsDir,
posix.ELOOP => return PosixOpenError.SymLinkLoop,
posix.EMFILE => return PosixOpenError.ProcessFdQuotaExceeded,
posix.ENAMETOOLONG => return PosixOpenError.NameTooLong,
posix.ENFILE => return PosixOpenError.SystemFdQuotaExceeded,
posix.ENODEV => return PosixOpenError.NoDevice,
posix.ENOENT => return PosixOpenError.PathNotFound,
posix.ENOMEM => return PosixOpenError.SystemResources,
posix.ENOSPC => return PosixOpenError.NoSpaceLeft,
posix.ENOTDIR => return PosixOpenError.NotDir,
posix.EPERM => return PosixOpenError.AccessDenied,
posix.EEXIST => return PosixOpenError.PathAlreadyExists,
else => return unexpectedErrorPosix(err),
}
}
return @intCast(i32, result);
}
}
pub fn posixDup2(old_fd: i32, new_fd: i32) !void {
while (true) {
const err = posix.getErrno(posix.dup2(old_fd, new_fd));
if (err > 0) {
return switch (err) {
posix.EBUSY, posix.EINTR => continue,
posix.EMFILE => error.ProcessFdQuotaExceeded,
posix.EINVAL => unreachable,
else => unexpectedErrorPosix(err),
};
}
return;
}
}
pub fn createNullDelimitedEnvMap(allocator: *Allocator, env_map: *const BufMap) ![]?[*]u8 {
const envp_count = env_map.count();
const envp_buf = try allocator.alloc(?[*]u8, envp_count + 1);
mem.set(?[*]u8, envp_buf, null);
errdefer freeNullDelimitedEnvMap(allocator, envp_buf);
{
var it = env_map.iterator();
var i: usize = 0;
while (it.next()) |pair| : (i += 1) {
const env_buf = try allocator.alloc(u8, pair.key.len + pair.value.len + 2);
@memcpy(env_buf.ptr, pair.key.ptr, pair.key.len);
env_buf[pair.key.len] = '=';
@memcpy(env_buf.ptr + pair.key.len + 1, pair.value.ptr, pair.value.len);
env_buf[env_buf.len - 1] = 0;
envp_buf[i] = env_buf.ptr;
}
assert(i == envp_count);
}
assert(envp_buf[envp_count] == null);
return envp_buf;
}
pub fn freeNullDelimitedEnvMap(allocator: *Allocator, envp_buf: []?[*]u8) void {
for (envp_buf) |env| {
const env_buf = if (env) |ptr| ptr[0 .. cstr.len(ptr) + 1] else break;
allocator.free(env_buf);
}
allocator.free(envp_buf);
}
/// This function must allocate memory to add a null terminating bytes on path and each arg.
/// It must also convert to KEY=VALUE\0 format for environment variables, and include null
/// pointers after the args and after the environment variables.
/// `argv[0]` is the executable path.
/// This function also uses the PATH environment variable to get the full path to the executable.
pub fn posixExecve(argv: []const []const u8, env_map: *const BufMap, allocator: *Allocator) !void {
const argv_buf = try allocator.alloc(?[*]u8, argv.len + 1);
mem.set(?[*]u8, argv_buf, null);
defer {
for (argv_buf) |arg| {
const arg_buf = if (arg) |ptr| cstr.toSlice(ptr) else break;
allocator.free(arg_buf);
}
allocator.free(argv_buf);
}
for (argv) |arg, i| {
const arg_buf = try allocator.alloc(u8, arg.len + 1);
@memcpy(arg_buf.ptr, arg.ptr, arg.len);
arg_buf[arg.len] = 0;
argv_buf[i] = arg_buf.ptr;
}
argv_buf[argv.len] = null;
const envp_buf = try createNullDelimitedEnvMap(allocator, env_map);
defer freeNullDelimitedEnvMap(allocator, envp_buf);
const exe_path = argv[0];
if (mem.indexOfScalar(u8, exe_path, '/') != null) {
return posixExecveErrnoToErr(posix.getErrno(posix.execve(argv_buf[0].?, argv_buf.ptr, envp_buf.ptr)));
}
const PATH = getEnvPosix("PATH") orelse "/usr/local/bin:/bin/:/usr/bin";
// PATH.len because it is >= the largest search_path
// +1 for the / to join the search path and exe_path
// +1 for the null terminating byte
const path_buf = try allocator.alloc(u8, PATH.len + exe_path.len + 2);
defer allocator.free(path_buf);
var it = mem.split(PATH, ":");
var seen_eacces = false;
var err: usize = undefined;
while (it.next()) |search_path| {
mem.copy(u8, path_buf, search_path);
path_buf[search_path.len] = '/';
mem.copy(u8, path_buf[search_path.len + 1 ..], exe_path);
path_buf[search_path.len + exe_path.len + 1] = 0;
err = posix.getErrno(posix.execve(path_buf.ptr, argv_buf.ptr, envp_buf.ptr));
assert(err > 0);
if (err == posix.EACCES) {
seen_eacces = true;
} else if (err != posix.ENOENT) {
return posixExecveErrnoToErr(err);
}
}
if (seen_eacces) {
err = posix.EACCES;
}
return posixExecveErrnoToErr(err);
}
pub const PosixExecveError = error{
SystemResources,
AccessDenied,
InvalidExe,
FileSystem,
IsDir,
FileNotFound,
NotDir,
FileBusy,
Unexpected,
};
fn posixExecveErrnoToErr(err: usize) PosixExecveError {
assert(err > 0);
return switch (err) {
posix.EFAULT => unreachable,
posix.E2BIG, posix.EMFILE, posix.ENAMETOOLONG, posix.ENFILE, posix.ENOMEM => error.SystemResources,
posix.EACCES, posix.EPERM => error.AccessDenied,
posix.EINVAL, posix.ENOEXEC => error.InvalidExe,
posix.EIO, posix.ELOOP => error.FileSystem,
posix.EISDIR => error.IsDir,
posix.ENOENT => error.FileNotFound,
posix.ENOTDIR => error.NotDir,
posix.ETXTBSY => error.FileBusy,
else => unexpectedErrorPosix(err),
};
}
pub var linux_aux_raw = []usize{0} ** 38;
pub var posix_environ_raw: [][*]u8 = undefined;
/// Caller must free result when done.
pub fn getEnvMap(allocator: *Allocator) !BufMap {
var result = BufMap.init(allocator);
errdefer result.deinit();
if (is_windows) {
const ptr = windows.GetEnvironmentStringsA() orelse return error.OutOfMemory;
defer assert(windows.FreeEnvironmentStringsA(ptr) != 0);
var i: usize = 0;
while (true) {
if (ptr[i] == 0) return result;
const key_start = i;
while (ptr[i] != 0 and ptr[i] != '=') : (i += 1) {}
const key = ptr[key_start..i];
if (ptr[i] == '=') i += 1;
const value_start = i;
while (ptr[i] != 0) : (i += 1) {}
const value = ptr[value_start..i];
i += 1; // skip over null byte
try result.set(key, value);
}
} else {
for (posix_environ_raw) |ptr| {
var line_i: usize = 0;
while (ptr[line_i] != 0 and ptr[line_i] != '=') : (line_i += 1) {}
const key = ptr[0..line_i];
var end_i: usize = line_i;
while (ptr[end_i] != 0) : (end_i += 1) {}
const value = ptr[line_i + 1 .. end_i];
try result.set(key, value);
}
return result;
}
}
pub fn getEnvPosix(key: []const u8) ?[]const u8 {
for (posix_environ_raw) |ptr| {
var line_i: usize = 0;
while (ptr[line_i] != 0 and ptr[line_i] != '=') : (line_i += 1) {}
const this_key = ptr[0..line_i];
if (!mem.eql(u8, key, this_key)) continue;
var end_i: usize = line_i;
while (ptr[end_i] != 0) : (end_i += 1) {}
const this_value = ptr[line_i + 1 .. end_i];
return this_value;
}
return null;
}
/// Caller must free returned memory.
pub fn getEnvVarOwned(allocator: *mem.Allocator, key: []const u8) ![]u8 {
if (is_windows) {
const key_with_null = try cstr.addNullByte(allocator, key);
defer allocator.free(key_with_null);
var buf = try allocator.alloc(u8, 256);
errdefer allocator.free(buf);
while (true) {
const windows_buf_len = try math.cast(windows.DWORD, buf.len);
const result = windows.GetEnvironmentVariableA(key_with_null.ptr, buf.ptr, windows_buf_len);
if (result == 0) {
const err = windows.GetLastError();
return switch (err) {
windows.ERROR.ENVVAR_NOT_FOUND => error.EnvironmentVariableNotFound,
else => unexpectedErrorWindows(err),
};
}
if (result > buf.len) {
buf = try allocator.realloc(u8, buf, result);
continue;
}
return allocator.shrink(u8, buf, result);
}
} else {
const result = getEnvPosix(key) orelse return error.EnvironmentVariableNotFound;
return mem.dupe(allocator, u8, result);
}
}
/// Caller must free the returned memory.
pub fn getCwd(allocator: *Allocator) ![]u8 {
switch (builtin.os) {
Os.windows => {
var buf = try allocator.alloc(u8, 256);
errdefer allocator.free(buf);
while (true) {
const result = windows.GetCurrentDirectoryA(@intCast(windows.WORD, buf.len), buf.ptr);
if (result == 0) {
const err = windows.GetLastError();
return switch (err) {
else => unexpectedErrorWindows(err),
};
}
if (result > buf.len) {
buf = try allocator.realloc(u8, buf, result);
continue;
}
return allocator.shrink(u8, buf, result);
}
},
else => {
var buf = try allocator.alloc(u8, 1024);
errdefer allocator.free(buf);
while (true) {
const err = posix.getErrno(posix.getcwd(buf.ptr, buf.len));
if (err == posix.ERANGE) {
buf = try allocator.realloc(u8, buf, buf.len * 2);
continue;
} else if (err > 0) {
return unexpectedErrorPosix(err);
}
return allocator.shrink(u8, buf, cstr.len(buf.ptr));
}
},
}
}
test "os.getCwd" {
// at least call it so it gets compiled
_ = getCwd(debug.global_allocator);
}
pub const SymLinkError = PosixSymLinkError || WindowsSymLinkError;
pub fn symLink(allocator: *Allocator, existing_path: []const u8, new_path: []const u8) SymLinkError!void {
if (is_windows) {
return symLinkWindows(allocator, existing_path, new_path);
} else {
return symLinkPosix(allocator, existing_path, new_path);
}
}
pub const WindowsSymLinkError = error{
OutOfMemory,
Unexpected,
};
pub fn symLinkWindows(allocator: *Allocator, existing_path: []const u8, new_path: []const u8) WindowsSymLinkError!void {
const existing_with_null = try cstr.addNullByte(allocator, existing_path);
defer allocator.free(existing_with_null);
const new_with_null = try cstr.addNullByte(allocator, new_path);
defer allocator.free(new_with_null);
if (windows.CreateSymbolicLinkA(existing_with_null.ptr, new_with_null.ptr, 0) == 0) {
const err = windows.GetLastError();
return switch (err) {
else => unexpectedErrorWindows(err),
};
}
}
pub const PosixSymLinkError = error{
OutOfMemory,
AccessDenied,
DiskQuota,
PathAlreadyExists,
FileSystem,
SymLinkLoop,
NameTooLong,
FileNotFound,
SystemResources,
NoSpaceLeft,
ReadOnlyFileSystem,
NotDir,
Unexpected,
};
pub fn symLinkPosix(allocator: *Allocator, existing_path: []const u8, new_path: []const u8) PosixSymLinkError!void {
const full_buf = try allocator.alloc(u8, existing_path.len + new_path.len + 2);
defer allocator.free(full_buf);
const existing_buf = full_buf;
mem.copy(u8, existing_buf, existing_path);
existing_buf[existing_path.len] = 0;
const new_buf = full_buf[existing_path.len + 1 ..];
mem.copy(u8, new_buf, new_path);
new_buf[new_path.len] = 0;
const err = posix.getErrno(posix.symlink(existing_buf.ptr, new_buf.ptr));
if (err > 0) {
return switch (err) {
posix.EFAULT, posix.EINVAL => unreachable,
posix.EACCES, posix.EPERM => error.AccessDenied,
posix.EDQUOT => error.DiskQuota,
posix.EEXIST => error.PathAlreadyExists,
posix.EIO => error.FileSystem,
posix.ELOOP => error.SymLinkLoop,
posix.ENAMETOOLONG => error.NameTooLong,
posix.ENOENT => error.FileNotFound,
posix.ENOTDIR => error.NotDir,
posix.ENOMEM => error.SystemResources,
posix.ENOSPC => error.NoSpaceLeft,
posix.EROFS => error.ReadOnlyFileSystem,
else => unexpectedErrorPosix(err),
};
}
}
// here we replace the standard +/ with -_ so that it can be used in a file name
const b64_fs_encoder = base64.Base64Encoder.init("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", base64.standard_pad_char);
pub fn atomicSymLink(allocator: *Allocator, existing_path: []const u8, new_path: []const u8) !void {
if (symLink(allocator, existing_path, new_path)) {
return;
} else |err| switch (err) {
error.PathAlreadyExists => {},
else => return err, // TODO zig should know this set does not include PathAlreadyExists
}
const dirname = os.path.dirname(new_path) orelse ".";
var rand_buf: [12]u8 = undefined;
const tmp_path = try allocator.alloc(u8, dirname.len + 1 + base64.Base64Encoder.calcSize(rand_buf.len));
defer allocator.free(tmp_path);
mem.copy(u8, tmp_path[0..], dirname);
tmp_path[dirname.len] = os.path.sep;
while (true) {
try getRandomBytes(rand_buf[0..]);
b64_fs_encoder.encode(tmp_path[dirname.len + 1 ..], rand_buf);
if (symLink(allocator, existing_path, tmp_path)) {
return rename(allocator, tmp_path, new_path);
} else |err| switch (err) {
error.PathAlreadyExists => continue,
else => return err, // TODO zig should know this set does not include PathAlreadyExists
}
}
}
pub const DeleteFileError = error{
FileNotFound,
AccessDenied,
FileBusy,
FileSystem,
IsDir,
SymLinkLoop,
NameTooLong,
NotDir,
SystemResources,
ReadOnlyFileSystem,
OutOfMemory,
Unexpected,
};
pub fn deleteFile(allocator: *Allocator, file_path: []const u8) DeleteFileError!void {
if (builtin.os == Os.windows) {
return deleteFileWindows(allocator, file_path);
} else {
return deleteFilePosix(allocator, file_path);
}
}
pub fn deleteFileWindows(allocator: *Allocator, file_path: []const u8) !void {
const buf = try allocator.alloc(u8, file_path.len + 1);
defer allocator.free(buf);
mem.copy(u8, buf, file_path);
buf[file_path.len] = 0;
if (windows.DeleteFileA(buf.ptr) == 0) {
const err = windows.GetLastError();
return switch (err) {
windows.ERROR.FILE_NOT_FOUND => error.FileNotFound,
windows.ERROR.ACCESS_DENIED => error.AccessDenied,
windows.ERROR.FILENAME_EXCED_RANGE, windows.ERROR.INVALID_PARAMETER => error.NameTooLong,
else => unexpectedErrorWindows(err),
};
}
}
pub fn deleteFilePosix(allocator: *Allocator, file_path: []const u8) !void {
const buf = try allocator.alloc(u8, file_path.len + 1);
defer allocator.free(buf);
mem.copy(u8, buf, file_path);
buf[file_path.len] = 0;
const err = posix.getErrno(posix.unlink(buf.ptr));
if (err > 0) {
return switch (err) {
posix.EACCES, posix.EPERM => error.AccessDenied,
posix.EBUSY => error.FileBusy,
posix.EFAULT, posix.EINVAL => unreachable,
posix.EIO => error.FileSystem,
posix.EISDIR => error.IsDir,
posix.ELOOP => error.SymLinkLoop,
posix.ENAMETOOLONG => error.NameTooLong,
posix.ENOENT => error.FileNotFound,
posix.ENOTDIR => error.NotDir,
posix.ENOMEM => error.SystemResources,
posix.EROFS => error.ReadOnlyFileSystem,
else => unexpectedErrorPosix(err),
};
}
}
/// Guaranteed to be atomic. However until https://patchwork.kernel.org/patch/9636735/ is
/// merged and readily available,
/// there is a possibility of power loss or application termination leaving temporary files present
/// in the same directory as dest_path.
/// Destination file will have the same mode as the source file.
pub fn copyFile(allocator: *Allocator, source_path: []const u8, dest_path: []const u8) !void {
var in_file = try os.File.openRead(allocator, source_path);
defer in_file.close();
const mode = try in_file.mode();
var atomic_file = try AtomicFile.init(allocator, dest_path, mode);
defer atomic_file.deinit();
var buf: [page_size]u8 = undefined;
while (true) {
const amt = try in_file.read(buf[0..]);
try atomic_file.file.write(buf[0..amt]);
if (amt != buf.len) {
return atomic_file.finish();
}
}
}
/// Guaranteed to be atomic. However until https://patchwork.kernel.org/patch/9636735/ is
/// merged and readily available,
/// there is a possibility of power loss or application termination leaving temporary files present
pub fn copyFileMode(allocator: *Allocator, source_path: []const u8, dest_path: []const u8, mode: FileMode) !void {
var in_file = try os.File.openRead(allocator, source_path);
defer in_file.close();
var atomic_file = try AtomicFile.init(allocator, dest_path, mode);
defer atomic_file.deinit();
var buf: [page_size]u8 = undefined;
while (true) {
const amt = try in_file.read(buf[0..]);
try atomic_file.file.write(buf[0..amt]);
if (amt != buf.len) {
return atomic_file.finish();
}
}
}
pub const AtomicFile = struct {
allocator: *Allocator,
file: os.File,
tmp_path: []u8,
dest_path: []const u8,
finished: bool,
/// dest_path must remain valid for the lifetime of AtomicFile
/// call finish to atomically replace dest_path with contents
pub fn init(allocator: *Allocator, dest_path: []const u8, mode: FileMode) !AtomicFile {
const dirname = os.path.dirname(dest_path);
var rand_buf: [12]u8 = undefined;
const dirname_component_len = if (dirname) |d| d.len + 1 else 0;
const tmp_path = try allocator.alloc(u8, dirname_component_len +
base64.Base64Encoder.calcSize(rand_buf.len));
errdefer allocator.free(tmp_path);
if (dirname) |dir| {
mem.copy(u8, tmp_path[0..], dir);
tmp_path[dir.len] = os.path.sep;
}
while (true) {
try getRandomBytes(rand_buf[0..]);
b64_fs_encoder.encode(tmp_path[dirname_component_len..], rand_buf);
const file = os.File.openWriteNoClobber(allocator, tmp_path, mode) catch |err| switch (err) {
error.PathAlreadyExists => continue,
// TODO zig should figure out that this error set does not include PathAlreadyExists since
// it is handled in the above switch
else => return err,
};
return AtomicFile{
.allocator = allocator,
.file = file,
.tmp_path = tmp_path,
.dest_path = dest_path,
.finished = false,
};
}
}
/// always call deinit, even after successful finish()
pub fn deinit(self: *AtomicFile) void {
if (!self.finished) {
self.file.close();
deleteFile(self.allocator, self.tmp_path) catch {};
self.allocator.free(self.tmp_path);
self.finished = true;
}
}
pub fn finish(self: *AtomicFile) !void {
assert(!self.finished);
self.file.close();
try rename(self.allocator, self.tmp_path, self.dest_path);
self.allocator.free(self.tmp_path);
self.finished = true;
}
};
pub fn rename(allocator: *Allocator, old_path: []const u8, new_path: []const u8) !void {
const full_buf = try allocator.alloc(u8, old_path.len + new_path.len + 2);
defer allocator.free(full_buf);
const old_buf = full_buf;
mem.copy(u8, old_buf, old_path);
old_buf[old_path.len] = 0;
const new_buf = full_buf[old_path.len + 1 ..];
mem.copy(u8, new_buf, new_path);
new_buf[new_path.len] = 0;
if (is_windows) {
const flags = windows.MOVEFILE_REPLACE_EXISTING | windows.MOVEFILE_WRITE_THROUGH;
if (windows.MoveFileExA(old_buf.ptr, new_buf.ptr, flags) == 0) {
const err = windows.GetLastError();
return switch (err) {
else => unexpectedErrorWindows(err),
};
}
} else {
const err = posix.getErrno(posix.rename(old_buf.ptr, new_buf.ptr));
if (err > 0) {
return switch (err) {
posix.EACCES, posix.EPERM => error.AccessDenied,
posix.EBUSY => error.FileBusy,
posix.EDQUOT => error.DiskQuota,
posix.EFAULT, posix.EINVAL => unreachable,
posix.EISDIR => error.IsDir,
posix.ELOOP => error.SymLinkLoop,
posix.EMLINK => error.LinkQuotaExceeded,
posix.ENAMETOOLONG => error.NameTooLong,
posix.ENOENT => error.FileNotFound,
posix.ENOTDIR => error.NotDir,
posix.ENOMEM => error.SystemResources,
posix.ENOSPC => error.NoSpaceLeft,
posix.EEXIST, posix.ENOTEMPTY => error.PathAlreadyExists,
posix.EROFS => error.ReadOnlyFileSystem,
posix.EXDEV => error.RenameAcrossMountPoints,
else => unexpectedErrorPosix(err),
};
}
}
}
pub fn makeDir(allocator: *Allocator, dir_path: []const u8) !void {
if (is_windows) {
return makeDirWindows(allocator, dir_path);
} else {
return makeDirPosix(allocator, dir_path);
}
}
pub fn makeDirWindows(allocator: *Allocator, dir_path: []const u8) !void {
const path_buf = try cstr.addNullByte(allocator, dir_path);
defer allocator.free(path_buf);
if (windows.CreateDirectoryA(path_buf.ptr, null) == 0) {
const err = windows.GetLastError();
return switch (err) {
windows.ERROR.ALREADY_EXISTS => error.PathAlreadyExists,
windows.ERROR.PATH_NOT_FOUND => error.FileNotFound,
else => unexpectedErrorWindows(err),
};
}
}
pub fn makeDirPosix(allocator: *Allocator, dir_path: []const u8) !void {
const path_buf = try cstr.addNullByte(allocator, dir_path);
defer allocator.free(path_buf);
const err = posix.getErrno(posix.mkdir(path_buf.ptr, 0o755));
if (err > 0) {
return switch (err) {
posix.EACCES, posix.EPERM => error.AccessDenied,
posix.EDQUOT => error.DiskQuota,
posix.EEXIST => error.PathAlreadyExists,
posix.EFAULT => unreachable,
posix.ELOOP => error.SymLinkLoop,
posix.EMLINK => error.LinkQuotaExceeded,
posix.ENAMETOOLONG => error.NameTooLong,
posix.ENOENT => error.FileNotFound,
posix.ENOMEM => error.SystemResources,
posix.ENOSPC => error.NoSpaceLeft,
posix.ENOTDIR => error.NotDir,
posix.EROFS => error.ReadOnlyFileSystem,
else => unexpectedErrorPosix(err),
};
}
}
/// Calls makeDir recursively to make an entire path. Returns success if the path
/// already exists and is a directory.
pub fn makePath(allocator: *Allocator, full_path: []const u8) !void {
const resolved_path = try path.resolve(allocator, full_path);
defer allocator.free(resolved_path);
var end_index: usize = resolved_path.len;
while (true) {
makeDir(allocator, resolved_path[0..end_index]) catch |err| {
if (err == error.PathAlreadyExists) {
// TODO stat the file and return an error if it's not a directory
// this is important because otherwise a dangling symlink
// could cause an infinite loop
if (end_index == resolved_path.len) return;
} else if (err == error.FileNotFound) {
// march end_index backward until next path component
while (true) {
end_index -= 1;
if (os.path.isSep(resolved_path[end_index])) break;
}
continue;
} else {
return err;
}
};
if (end_index == resolved_path.len) return;
// march end_index forward until next path component
while (true) {
end_index += 1;
if (end_index == resolved_path.len or os.path.isSep(resolved_path[end_index])) break;
}
}
}
pub const DeleteDirError = error{
AccessDenied,
FileBusy,
SymLinkLoop,
NameTooLong,
FileNotFound,
SystemResources,
NotDir,
DirNotEmpty,
ReadOnlyFileSystem,
OutOfMemory,
Unexpected,
};
/// Returns ::error.DirNotEmpty if the directory is not empty.
/// To delete a directory recursively, see ::deleteTree
pub fn deleteDir(allocator: *Allocator, dir_path: []const u8) DeleteDirError!void {
const path_buf = try allocator.alloc(u8, dir_path.len + 1);
defer allocator.free(path_buf);
mem.copy(u8, path_buf, dir_path);
path_buf[dir_path.len] = 0;
switch (builtin.os) {
Os.windows => {
if (windows.RemoveDirectoryA(path_buf.ptr) == 0) {
const err = windows.GetLastError();
return switch (err) {
windows.ERROR.PATH_NOT_FOUND => error.FileNotFound,
windows.ERROR.DIR_NOT_EMPTY => error.DirNotEmpty,
else => unexpectedErrorWindows(err),
};
}
},
Os.linux, Os.macosx, Os.ios => {
const err = posix.getErrno(posix.rmdir(path_buf.ptr));
if (err > 0) {
return switch (err) {
posix.EACCES, posix.EPERM => error.AccessDenied,
posix.EBUSY => error.FileBusy,
posix.EFAULT, posix.EINVAL => unreachable,
posix.ELOOP => error.SymLinkLoop,
posix.ENAMETOOLONG => error.NameTooLong,
posix.ENOENT => error.FileNotFound,
posix.ENOMEM => error.SystemResources,
posix.ENOTDIR => error.NotDir,
posix.EEXIST, posix.ENOTEMPTY => error.DirNotEmpty,
posix.EROFS => error.ReadOnlyFileSystem,
else => unexpectedErrorPosix(err),
};
}
},
else => @compileError("unimplemented"),
}
}
/// Whether ::full_path describes a symlink, file, or directory, this function
/// removes it. If it cannot be removed because it is a non-empty directory,
/// this function recursively removes its entries and then tries again.
const DeleteTreeError = error{
OutOfMemory,
AccessDenied,
FileTooBig,
IsDir,
SymLinkLoop,
ProcessFdQuotaExceeded,
NameTooLong,
SystemFdQuotaExceeded,
NoDevice,
PathNotFound,
SystemResources,
NoSpaceLeft,
PathAlreadyExists,
ReadOnlyFileSystem,
NotDir,
FileNotFound,
FileSystem,
FileBusy,
DirNotEmpty,
Unexpected,
};
pub fn deleteTree(allocator: *Allocator, full_path: []const u8) DeleteTreeError!void {
start_over: while (true) {
var got_access_denied = false;
// First, try deleting the item as a file. This way we don't follow sym links.
if (deleteFile(allocator, full_path)) {
return;
} else |err| switch (err) {
error.FileNotFound => return,
error.IsDir => {},
error.AccessDenied => got_access_denied = true,
error.OutOfMemory,
error.SymLinkLoop,
error.NameTooLong,
error.SystemResources,
error.ReadOnlyFileSystem,
error.NotDir,
error.FileSystem,
error.FileBusy,
error.Unexpected,
=> return err,
}
{
var dir = Dir.open(allocator, full_path) catch |err| switch (err) {
error.NotDir => {
if (got_access_denied) {
return error.AccessDenied;
}
continue :start_over;
},
error.OutOfMemory,
error.AccessDenied,
error.FileTooBig,
error.IsDir,
error.SymLinkLoop,
error.ProcessFdQuotaExceeded,
error.NameTooLong,
error.SystemFdQuotaExceeded,
error.NoDevice,
error.PathNotFound,
error.SystemResources,
error.NoSpaceLeft,
error.PathAlreadyExists,
error.Unexpected,
=> return err,
};
defer dir.close();
var full_entry_buf = ArrayList(u8).init(allocator);
defer full_entry_buf.deinit();
while (try dir.next()) |entry| {
try full_entry_buf.resize(full_path.len + entry.name.len + 1);
const full_entry_path = full_entry_buf.toSlice();
mem.copy(u8, full_entry_path, full_path);
full_entry_path[full_path.len] = path.sep;
mem.copy(u8, full_entry_path[full_path.len + 1 ..], entry.name);
try deleteTree(allocator, full_entry_path);
}
}
return deleteDir(allocator, full_path);
}
}
pub const Dir = struct {
handle: Handle,
allocator: *Allocator,
pub const Handle = switch (builtin.os) {
Os.macosx, Os.ios => struct {
fd: i32,
seek: i64,
buf: []u8,
index: usize,
end_index: usize,
},
Os.linux => struct {
fd: i32,
buf: []u8,
index: usize,
end_index: usize,
},
Os.windows => struct {
handle: windows.HANDLE,
find_file_data: windows.WIN32_FIND_DATAA,
first: bool,
},
else => @compileError("unimplemented"),
};
pub const Entry = struct {
name: []const u8,
kind: Kind,
pub const Kind = enum {
BlockDevice,
CharacterDevice,
Directory,
NamedPipe,
SymLink,
File,
UnixDomainSocket,
Whiteout,
Unknown,
};
};
pub const OpenError = error{
PathNotFound,
NotDir,
AccessDenied,
FileTooBig,
IsDir,
SymLinkLoop,
ProcessFdQuotaExceeded,
NameTooLong,
SystemFdQuotaExceeded,
NoDevice,
SystemResources,
NoSpaceLeft,
PathAlreadyExists,
OutOfMemory,
Unexpected,
};
pub fn open(allocator: *Allocator, dir_path: []const u8) OpenError!Dir {
return Dir{
.allocator = allocator,
.handle = switch (builtin.os) {
Os.windows => blk: {
var find_file_data: windows.WIN32_FIND_DATAA = undefined;
const handle = try windows_util.windowsFindFirstFile(allocator, dir_path, &find_file_data);
break :blk Handle{
.handle = handle,
.find_file_data = find_file_data, // TODO guaranteed copy elision
.first = true,
};
},
Os.macosx, Os.ios => Handle{
.fd = try posixOpen(
allocator,
dir_path,
posix.O_RDONLY | posix.O_NONBLOCK | posix.O_DIRECTORY | posix.O_CLOEXEC,
0,
),
.seek = 0,
.index = 0,
.end_index = 0,
.buf = []u8{},
},
Os.linux => Handle{
.fd = try posixOpen(
allocator,
dir_path,
posix.O_RDONLY | posix.O_DIRECTORY | posix.O_CLOEXEC,
0,
),
.index = 0,
.end_index = 0,
.buf = []u8{},
},
else => @compileError("unimplemented"),
},
};
}
pub fn close(self: *Dir) void {
switch (builtin.os) {
Os.windows => {
_ = windows.FindClose(self.handle.handle);
},
Os.macosx, Os.ios, Os.linux => {
self.allocator.free(self.handle.buf);
os.close(self.handle.fd);
},
else => @compileError("unimplemented"),
}
}
/// Memory such as file names referenced in this returned entry becomes invalid
/// with subsequent calls to next, as well as when this `Dir` is deinitialized.
pub fn next(self: *Dir) !?Entry {
switch (builtin.os) {
Os.linux => return self.nextLinux(),
Os.macosx, Os.ios => return self.nextDarwin(),
Os.windows => return self.nextWindows(),
else => @compileError("unimplemented"),
}
}
fn nextDarwin(self: *Dir) !?Entry {
start_over: while (true) {
if (self.handle.index >= self.handle.end_index) {
if (self.handle.buf.len == 0) {
self.handle.buf = try self.allocator.alloc(u8, page_size);
}
while (true) {
const result = posix.getdirentries64(self.handle.fd, self.handle.buf.ptr, self.handle.buf.len, &self.handle.seek);
const err = posix.getErrno(result);
if (err > 0) {
switch (err) {
posix.EBADF, posix.EFAULT, posix.ENOTDIR => unreachable,
posix.EINVAL => {
self.handle.buf = try self.allocator.realloc(u8, self.handle.buf, self.handle.buf.len * 2);
continue;
},
else => return unexpectedErrorPosix(err),
}
}
if (result == 0) return null;
self.handle.index = 0;
self.handle.end_index = result;
break;
}
}
const darwin_entry = @ptrCast(*align(1) posix.dirent, &self.handle.buf[self.handle.index]);
const next_index = self.handle.index + darwin_entry.d_reclen;
self.handle.index = next_index;
const name = @ptrCast([*]u8, &darwin_entry.d_name)[0..darwin_entry.d_namlen];
if (mem.eql(u8, name, ".") or mem.eql(u8, name, "..")) {
continue :start_over;
}
const entry_kind = switch (darwin_entry.d_type) {
posix.DT_BLK => Entry.Kind.BlockDevice,
posix.DT_CHR => Entry.Kind.CharacterDevice,
posix.DT_DIR => Entry.Kind.Directory,
posix.DT_FIFO => Entry.Kind.NamedPipe,
posix.DT_LNK => Entry.Kind.SymLink,
posix.DT_REG => Entry.Kind.File,
posix.DT_SOCK => Entry.Kind.UnixDomainSocket,
posix.DT_WHT => Entry.Kind.Whiteout,
else => Entry.Kind.Unknown,
};
return Entry{
.name = name,
.kind = entry_kind,
};
}
}
fn nextWindows(self: *Dir) !?Entry {
while (true) {
if (self.handle.first) {
self.handle.first = false;
} else {
if (!try windows_util.windowsFindNextFile(self.handle.handle, &self.handle.find_file_data))
return null;
}
const name = std.cstr.toSlice(self.handle.find_file_data.cFileName[0..].ptr);
if (mem.eql(u8, name, ".") or mem.eql(u8, name, ".."))
continue;
const kind = blk: {
const attrs = self.handle.find_file_data.dwFileAttributes;
if (attrs & windows.FILE_ATTRIBUTE_DIRECTORY != 0) break :blk Entry.Kind.Directory;
if (attrs & windows.FILE_ATTRIBUTE_REPARSE_POINT != 0) break :blk Entry.Kind.SymLink;
if (attrs & windows.FILE_ATTRIBUTE_NORMAL != 0) break :blk Entry.Kind.File;
break :blk Entry.Kind.Unknown;
};
return Entry{
.name = name,
.kind = kind,
};
}
}
fn nextLinux(self: *Dir) !?Entry {
start_over: while (true) {
if (self.handle.index >= self.handle.end_index) {
if (self.handle.buf.len == 0) {
self.handle.buf = try self.allocator.alloc(u8, page_size);
}
while (true) {
const result = posix.getdents(self.handle.fd, self.handle.buf.ptr, self.handle.buf.len);
const err = posix.getErrno(result);
if (err > 0) {
switch (err) {
posix.EBADF, posix.EFAULT, posix.ENOTDIR => unreachable,
posix.EINVAL => {
self.handle.buf = try self.allocator.realloc(u8, self.handle.buf, self.handle.buf.len * 2);
continue;
},
else => return unexpectedErrorPosix(err),
}
}
if (result == 0) return null;
self.handle.index = 0;
self.handle.end_index = result;
break;
}
}
const linux_entry = @ptrCast(*align(1) posix.dirent, &self.handle.buf[self.handle.index]);
const next_index = self.handle.index + linux_entry.d_reclen;
self.handle.index = next_index;
const name = cstr.toSlice(@ptrCast([*]u8, &linux_entry.d_name));
// skip . and .. entries
if (mem.eql(u8, name, ".") or mem.eql(u8, name, "..")) {
continue :start_over;
}
const type_char = self.handle.buf[next_index - 1];
const entry_kind = switch (type_char) {
posix.DT_BLK => Entry.Kind.BlockDevice,
posix.DT_CHR => Entry.Kind.CharacterDevice,
posix.DT_DIR => Entry.Kind.Directory,
posix.DT_FIFO => Entry.Kind.NamedPipe,
posix.DT_LNK => Entry.Kind.SymLink,
posix.DT_REG => Entry.Kind.File,
posix.DT_SOCK => Entry.Kind.UnixDomainSocket,
else => Entry.Kind.Unknown,
};
return Entry{
.name = name,
.kind = entry_kind,
};
}
}
};
pub fn changeCurDir(allocator: *Allocator, dir_path: []const u8) !void {
const path_buf = try allocator.alloc(u8, dir_path.len + 1);
defer allocator.free(path_buf);
mem.copy(u8, path_buf, dir_path);
path_buf[dir_path.len] = 0;
const err = posix.getErrno(posix.chdir(path_buf.ptr));
if (err > 0) {
return switch (err) {
posix.EACCES => error.AccessDenied,
posix.EFAULT => unreachable,
posix.EIO => error.FileSystem,
posix.ELOOP => error.SymLinkLoop,
posix.ENAMETOOLONG => error.NameTooLong,
posix.ENOENT => error.FileNotFound,
posix.ENOMEM => error.SystemResources,
posix.ENOTDIR => error.NotDir,
else => unexpectedErrorPosix(err),
};
}
}
/// Read value of a symbolic link.
pub fn readLink(allocator: *Allocator, pathname: []const u8) ![]u8 {
const path_buf = try allocator.alloc(u8, pathname.len + 1);
defer allocator.free(path_buf);
mem.copy(u8, path_buf, pathname);
path_buf[pathname.len] = 0;
var result_buf = try allocator.alloc(u8, 1024);
errdefer allocator.free(result_buf);
while (true) {
const ret_val = posix.readlink(path_buf.ptr, result_buf.ptr, result_buf.len);
const err = posix.getErrno(ret_val);
if (err > 0) {
return switch (err) {
posix.EACCES => error.AccessDenied,
posix.EFAULT, posix.EINVAL => unreachable,
posix.EIO => error.FileSystem,
posix.ELOOP => error.SymLinkLoop,
posix.ENAMETOOLONG => error.NameTooLong,
posix.ENOENT => error.FileNotFound,
posix.ENOMEM => error.SystemResources,
posix.ENOTDIR => error.NotDir,
else => unexpectedErrorPosix(err),
};
}
if (ret_val == result_buf.len) {
result_buf = try allocator.realloc(u8, result_buf, result_buf.len * 2);
continue;
}
return allocator.shrink(u8, result_buf, ret_val);
}
}
pub fn posix_setuid(uid: u32) !void {
const err = posix.getErrno(posix.setuid(uid));
if (err == 0) return;
return switch (err) {
posix.EAGAIN => error.ResourceLimitReached,
posix.EINVAL => error.InvalidUserId,
posix.EPERM => error.PermissionDenied,
else => unexpectedErrorPosix(err),
};
}
pub fn posix_setreuid(ruid: u32, euid: u32) !void {
const err = posix.getErrno(posix.setreuid(ruid, euid));
if (err == 0) return;
return switch (err) {
posix.EAGAIN => error.ResourceLimitReached,
posix.EINVAL => error.InvalidUserId,
posix.EPERM => error.PermissionDenied,
else => unexpectedErrorPosix(err),
};
}
pub fn posix_setgid(gid: u32) !void {
const err = posix.getErrno(posix.setgid(gid));
if (err == 0) return;
return switch (err) {
posix.EAGAIN => error.ResourceLimitReached,
posix.EINVAL => error.InvalidUserId,
posix.EPERM => error.PermissionDenied,
else => unexpectedErrorPosix(err),
};
}
pub fn posix_setregid(rgid: u32, egid: u32) !void {
const err = posix.getErrno(posix.setregid(rgid, egid));
if (err == 0) return;
return switch (err) {
posix.EAGAIN => error.ResourceLimitReached,
posix.EINVAL => error.InvalidUserId,
posix.EPERM => error.PermissionDenied,
else => unexpectedErrorPosix(err),
};
}
pub const WindowsGetStdHandleErrs = error{
NoStdHandles,
Unexpected,
};
pub fn windowsGetStdHandle(handle_id: windows.DWORD) WindowsGetStdHandleErrs!windows.HANDLE {
if (windows.GetStdHandle(handle_id)) |handle| {
if (handle == windows.INVALID_HANDLE_VALUE) {
const err = windows.GetLastError();
return switch (err) {
else => os.unexpectedErrorWindows(err),
};
}
return handle;
} else {
return error.NoStdHandles;
}
}
pub const ArgIteratorPosix = struct {
index: usize,
count: usize,
pub fn init() ArgIteratorPosix {
return ArgIteratorPosix{
.index = 0,
.count = raw.len,
};
}
pub fn next(self: *ArgIteratorPosix) ?[]const u8 {
if (self.index == self.count) return null;
const s = raw[self.index];
self.index += 1;
return cstr.toSlice(s);
}
pub fn skip(self: *ArgIteratorPosix) bool {
if (self.index == self.count) return false;
self.index += 1;
return true;
}
/// This is marked as public but actually it's only meant to be used
/// internally by zig's startup code.
pub var raw: [][*]u8 = undefined;
};
pub const ArgIteratorWindows = struct {
index: usize,
cmd_line: [*]const u8,
in_quote: bool,
quote_count: usize,
seen_quote_count: usize,
pub const NextError = error{OutOfMemory};
pub fn init() ArgIteratorWindows {
return initWithCmdLine(windows.GetCommandLineA());
}
pub fn initWithCmdLine(cmd_line: [*]const u8) ArgIteratorWindows {
return ArgIteratorWindows{
.index = 0,
.cmd_line = cmd_line,
.in_quote = false,
.quote_count = countQuotes(cmd_line),
.seen_quote_count = 0,
};
}
/// You must free the returned memory when done.
pub fn next(self: *ArgIteratorWindows, allocator: *Allocator) ?(NextError![]u8) {
// march forward over whitespace
while (true) : (self.index += 1) {
const byte = self.cmd_line[self.index];
switch (byte) {
0 => return null,
' ', '\t' => continue,
else => break,
}
}
return self.internalNext(allocator);
}
pub fn skip(self: *ArgIteratorWindows) bool {
// march forward over whitespace
while (true) : (self.index += 1) {
const byte = self.cmd_line[self.index];
switch (byte) {
0 => return false,
' ', '\t' => continue,
else => break,
}
}
var backslash_count: usize = 0;
while (true) : (self.index += 1) {
const byte = self.cmd_line[self.index];
switch (byte) {
0 => return true,
'"' => {
const quote_is_real = backslash_count % 2 == 0;
if (quote_is_real) {
self.seen_quote_count += 1;
}
},
'\\' => {
backslash_count += 1;
},
' ', '\t' => {
if (self.seen_quote_count % 2 == 0 or self.seen_quote_count == self.quote_count) {
return true;
}
backslash_count = 0;
},
else => {
backslash_count = 0;
continue;
},
}
}
}
fn internalNext(self: *ArgIteratorWindows, allocator: *Allocator) NextError![]u8 {
var buf = try Buffer.initSize(allocator, 0);
defer buf.deinit();
var backslash_count: usize = 0;
while (true) : (self.index += 1) {
const byte = self.cmd_line[self.index];
switch (byte) {
0 => return buf.toOwnedSlice(),
'"' => {
const quote_is_real = backslash_count % 2 == 0;
try self.emitBackslashes(&buf, backslash_count / 2);
backslash_count = 0;
if (quote_is_real) {
self.seen_quote_count += 1;
if (self.seen_quote_count == self.quote_count and self.seen_quote_count % 2 == 1) {
try buf.appendByte('"');
}
} else {
try buf.appendByte('"');
}
},
'\\' => {
backslash_count += 1;
},
' ', '\t' => {
try self.emitBackslashes(&buf, backslash_count);
backslash_count = 0;
if (self.seen_quote_count % 2 == 1 and self.seen_quote_count != self.quote_count) {
try buf.appendByte(byte);
} else {
return buf.toOwnedSlice();
}
},
else => {
try self.emitBackslashes(&buf, backslash_count);
backslash_count = 0;
try buf.appendByte(byte);
},
}
}
}
fn emitBackslashes(self: *ArgIteratorWindows, buf: *Buffer, emit_count: usize) !void {
var i: usize = 0;
while (i < emit_count) : (i += 1) {
try buf.appendByte('\\');
}
}
fn countQuotes(cmd_line: [*]const u8) usize {
var result: usize = 0;
var backslash_count: usize = 0;
var index: usize = 0;
while (true) : (index += 1) {
const byte = cmd_line[index];
switch (byte) {
0 => return result,
'\\' => backslash_count += 1,
'"' => {
result += 1 - (backslash_count % 2);
backslash_count = 0;
},
else => {
backslash_count = 0;
},
}
}
}
};
pub const ArgIterator = struct {
const InnerType = if (builtin.os == Os.windows) ArgIteratorWindows else ArgIteratorPosix;
inner: InnerType,
pub fn init() ArgIterator {
return ArgIterator{ .inner = InnerType.init() };
}
pub const NextError = ArgIteratorWindows.NextError;
/// You must free the returned memory when done.
pub fn next(self: *ArgIterator, allocator: *Allocator) ?(NextError![]u8) {
if (builtin.os == Os.windows) {
return self.inner.next(allocator);
} else {
return mem.dupe(allocator, u8, self.inner.next() orelse return null);
}
}
/// If you only are targeting posix you can call this and not need an allocator.
pub fn nextPosix(self: *ArgIterator) ?[]const u8 {
return self.inner.next();
}
/// Parse past 1 argument without capturing it.
/// Returns `true` if skipped an arg, `false` if we are at the end.
pub fn skip(self: *ArgIterator) bool {
return self.inner.skip();
}
};
pub fn args() ArgIterator {
return ArgIterator.init();
}
/// Caller must call freeArgs on result.
pub fn argsAlloc(allocator: *mem.Allocator) ![]const []u8 {
// TODO refactor to only make 1 allocation.
var it = args();
var contents = try Buffer.initSize(allocator, 0);
defer contents.deinit();
var slice_list = ArrayList(usize).init(allocator);
defer slice_list.deinit();
while (it.next(allocator)) |arg_or_err| {
const arg = try arg_or_err;
defer allocator.free(arg);
try contents.append(arg);
try slice_list.append(arg.len);
}
const contents_slice = contents.toSliceConst();
const slice_sizes = slice_list.toSliceConst();
const slice_list_bytes = try math.mul(usize, @sizeOf([]u8), slice_sizes.len);
const total_bytes = try math.add(usize, slice_list_bytes, contents_slice.len);
const buf = try allocator.alignedAlloc(u8, @alignOf([]u8), total_bytes);
errdefer allocator.free(buf);
const result_slice_list = @bytesToSlice([]u8, buf[0..slice_list_bytes]);
const result_contents = buf[slice_list_bytes..];
mem.copy(u8, result_contents, contents_slice);
var contents_index: usize = 0;
for (slice_sizes) |len, i| {
const new_index = contents_index + len;
result_slice_list[i] = result_contents[contents_index..new_index];
contents_index = new_index;
}
return result_slice_list;
}
pub fn argsFree(allocator: *mem.Allocator, args_alloc: []const []u8) void {
var total_bytes: usize = 0;
for (args_alloc) |arg| {
total_bytes += @sizeOf([]u8) + arg.len;
}
const unaligned_allocated_buf = @ptrCast([*]const u8, args_alloc.ptr)[0..total_bytes];
const aligned_allocated_buf = @alignCast(@alignOf([]u8), unaligned_allocated_buf);
return allocator.free(aligned_allocated_buf);
}
test "windows arg parsing" {
testWindowsCmdLine(c"a b\tc d", [][]const u8{ "a", "b", "c", "d" });
testWindowsCmdLine(c"\"abc\" d e", [][]const u8{ "abc", "d", "e" });
testWindowsCmdLine(c"a\\\\\\b d\"e f\"g h", [][]const u8{ "a\\\\\\b", "de fg", "h" });
testWindowsCmdLine(c"a\\\\\\\"b c d", [][]const u8{ "a\\\"b", "c", "d" });
testWindowsCmdLine(c"a\\\\\\\\\"b c\" d e", [][]const u8{ "a\\\\b c", "d", "e" });
testWindowsCmdLine(c"a b\tc \"d f", [][]const u8{ "a", "b", "c", "\"d", "f" });
testWindowsCmdLine(c"\".\\..\\zig-cache\\build\" \"bin\\zig.exe\" \".\\..\" \".\\..\\zig-cache\" \"--help\"", [][]const u8{
".\\..\\zig-cache\\build",
"bin\\zig.exe",
".\\..",
".\\..\\zig-cache",
"--help",
});
}
fn testWindowsCmdLine(input_cmd_line: [*]const u8, expected_args: []const []const u8) void {
var it = ArgIteratorWindows.initWithCmdLine(input_cmd_line);
for (expected_args) |expected_arg| {
const arg = it.next(debug.global_allocator).? catch unreachable;
assert(mem.eql(u8, arg, expected_arg));
}
assert(it.next(debug.global_allocator) == null);
}
// TODO make this a build variable that you can set
const unexpected_error_tracing = false;
const UnexpectedError = error{
/// The Operating System returned an undocumented error code.
Unexpected,
};
/// Call this when you made a syscall or something that sets errno
/// and you get an unexpected error.
pub fn unexpectedErrorPosix(errno: usize) UnexpectedError {
if (unexpected_error_tracing) {
debug.warn("unexpected errno: {}\n", errno);
debug.dumpCurrentStackTrace(null);
}
return error.Unexpected;
}
/// Call this when you made a windows DLL call or something that does SetLastError
/// and you get an unexpected error.
pub fn unexpectedErrorWindows(err: windows.DWORD) UnexpectedError {
if (unexpected_error_tracing) {
debug.warn("unexpected GetLastError(): {}\n", err);
debug.dumpCurrentStackTrace(null);
}
return error.Unexpected;
}
pub fn openSelfExe() !os.File {
switch (builtin.os) {
Os.linux => {
const proc_file_path = "/proc/self/exe";
var fixed_buffer_mem: [proc_file_path.len + 1]u8 = undefined;
var fixed_allocator = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]);
return os.File.openRead(&fixed_allocator.allocator, proc_file_path);
},
Os.macosx, Os.ios => {
var fixed_buffer_mem: [darwin.PATH_MAX * 2]u8 = undefined;
var fixed_allocator = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]);
const self_exe_path = try selfExePath(&fixed_allocator.allocator);
return os.File.openRead(&fixed_allocator.allocator, self_exe_path);
},
else => @compileError("Unsupported OS"),
}
}
test "openSelfExe" {
switch (builtin.os) {
Os.linux, Os.macosx, Os.ios => (try openSelfExe()).close(),
else => return, // Unsupported OS.
}
}
/// Get the path to the current executable.
/// If you only need the directory, use selfExeDirPath.
/// If you only want an open file handle, use openSelfExe.
/// This function may return an error if the current executable
/// was deleted after spawning.
/// Caller owns returned memory.
pub fn selfExePath(allocator: *mem.Allocator) ![]u8 {
switch (builtin.os) {
Os.linux => {
// If the currently executing binary has been deleted,
// the file path looks something like `/a/b/c/exe (deleted)`
return readLink(allocator, "/proc/self/exe");
},
Os.windows => {
var out_path = try Buffer.initSize(allocator, 0xff);
errdefer out_path.deinit();
while (true) {
const dword_len = try math.cast(windows.DWORD, out_path.len());
const copied_amt = windows.GetModuleFileNameA(null, out_path.ptr(), dword_len);
if (copied_amt <= 0) {
const err = windows.GetLastError();
return switch (err) {
else => unexpectedErrorWindows(err),
};
}
if (copied_amt < out_path.len()) {
out_path.shrink(copied_amt);
return out_path.toOwnedSlice();
}
const new_len = (out_path.len() << 1) | 0b1;
try out_path.resize(new_len);
}
},
Os.macosx, Os.ios => {
var u32_len: u32 = 0;
const ret1 = c._NSGetExecutablePath(undefined, &u32_len);
assert(ret1 != 0);
const bytes = try allocator.alloc(u8, u32_len);
errdefer allocator.free(bytes);
const ret2 = c._NSGetExecutablePath(bytes.ptr, &u32_len);
assert(ret2 == 0);
return bytes;
},
else => @compileError("Unsupported OS"),
}
}
/// Get the directory path that contains the current executable.
/// Caller owns returned memory.
pub fn selfExeDirPath(allocator: *mem.Allocator) ![]u8 {
switch (builtin.os) {
Os.linux => {
// If the currently executing binary has been deleted,
// the file path looks something like `/a/b/c/exe (deleted)`
// This path cannot be opened, but it's valid for determining the directory
// the executable was in when it was run.
const full_exe_path = try readLink(allocator, "/proc/self/exe");
errdefer allocator.free(full_exe_path);
const dir = path.dirname(full_exe_path) orelse ".";
return allocator.shrink(u8, full_exe_path, dir.len);
},
Os.windows, Os.macosx, Os.ios => {
const self_exe_path = try selfExePath(allocator);
errdefer allocator.free(self_exe_path);
const dirname = os.path.dirname(self_exe_path) orelse ".";
return allocator.shrink(u8, self_exe_path, dirname.len);
},
else => @compileError("unimplemented: std.os.selfExeDirPath for " ++ @tagName(builtin.os)),
}
}
pub fn isTty(handle: FileHandle) bool {
if (is_windows) {
return windows_util.windowsIsTty(handle);
} else {
if (builtin.link_libc) {
return c.isatty(handle) != 0;
} else {
return posix.isatty(handle);
}
}
}
pub const PosixSocketError = error{
/// Permission to create a socket of the specified type and/or
/// pro‐tocol is denied.
PermissionDenied,
/// The implementation does not support the specified address family.
AddressFamilyNotSupported,
/// Unknown protocol, or protocol family not available.
ProtocolFamilyNotAvailable,
/// The per-process limit on the number of open file descriptors has been reached.
ProcessFdQuotaExceeded,
/// The system-wide limit on the total number of open files has been reached.
SystemFdQuotaExceeded,
/// Insufficient memory is available. The socket cannot be created until sufficient
/// resources are freed.
SystemResources,
/// The protocol type or the specified protocol is not supported within this domain.
ProtocolNotSupported,
};
pub fn posixSocket(domain: u32, socket_type: u32, protocol: u32) !i32 {
const rc = posix.socket(domain, socket_type, protocol);
const err = posix.getErrno(rc);
switch (err) {
0 => return @intCast(i32, rc),
posix.EACCES => return PosixSocketError.PermissionDenied,
posix.EAFNOSUPPORT => return PosixSocketError.AddressFamilyNotSupported,
posix.EINVAL => return PosixSocketError.ProtocolFamilyNotAvailable,
posix.EMFILE => return PosixSocketError.ProcessFdQuotaExceeded,
posix.ENFILE => return PosixSocketError.SystemFdQuotaExceeded,
posix.ENOBUFS, posix.ENOMEM => return PosixSocketError.SystemResources,
posix.EPROTONOSUPPORT => return PosixSocketError.ProtocolNotSupported,
else => return unexpectedErrorPosix(err),
}
}
pub const PosixBindError = error{
/// The address is protected, and the user is not the superuser.
/// For UNIX domain sockets: Search permission is denied on a component
/// of the path prefix.
AccessDenied,
/// The given address is already in use, or in the case of Internet domain sockets,
/// The port number was specified as zero in the socket
/// address structure, but, upon attempting to bind to an ephemeral port, it was
/// determined that all port numbers in the ephemeral port range are currently in
/// use. See the discussion of /proc/sys/net/ipv4/ip_local_port_range ip(7).
AddressInUse,
/// sockfd is not a valid file descriptor.
InvalidFileDescriptor,
/// The socket is already bound to an address, or addrlen is wrong, or addr is not
/// a valid address for this socket's domain.
InvalidSocketOrAddress,
/// The file descriptor sockfd does not refer to a socket.
FileDescriptorNotASocket,
/// A nonexistent interface was requested or the requested address was not local.
AddressNotAvailable,
/// addr points outside the user's accessible address space.
PageFault,
/// Too many symbolic links were encountered in resolving addr.
SymLinkLoop,
/// addr is too long.
NameTooLong,
/// A component in the directory prefix of the socket pathname does not exist.
FileNotFound,
/// Insufficient kernel memory was available.
SystemResources,
/// A component of the path prefix is not a directory.
NotDir,
/// The socket inode would reside on a read-only filesystem.
ReadOnlyFileSystem,
Unexpected,
};
/// addr is `&const T` where T is one of the sockaddr
pub fn posixBind(fd: i32, addr: *const posix.sockaddr) PosixBindError!void {
const rc = posix.bind(fd, addr, @sizeOf(posix.sockaddr));
const err = posix.getErrno(rc);
switch (err) {
0 => return,
posix.EACCES => return PosixBindError.AccessDenied,
posix.EADDRINUSE => return PosixBindError.AddressInUse,
posix.EBADF => return PosixBindError.InvalidFileDescriptor,
posix.EINVAL => return PosixBindError.InvalidSocketOrAddress,
posix.ENOTSOCK => return PosixBindError.FileDescriptorNotASocket,
posix.EADDRNOTAVAIL => return PosixBindError.AddressNotAvailable,
posix.EFAULT => return PosixBindError.PageFault,
posix.ELOOP => return PosixBindError.SymLinkLoop,
posix.ENAMETOOLONG => return PosixBindError.NameTooLong,
posix.ENOENT => return PosixBindError.FileNotFound,
posix.ENOMEM => return PosixBindError.SystemResources,
posix.ENOTDIR => return PosixBindError.NotDir,
posix.EROFS => return PosixBindError.ReadOnlyFileSystem,
else => return unexpectedErrorPosix(err),
}
}
const PosixListenError = error{
/// Another socket is already listening on the same port.
/// For Internet domain sockets, the socket referred to by sockfd had not previously
/// been bound to an address and, upon attempting to bind it to an ephemeral port, it
/// was determined that all port numbers in the ephemeral port range are currently in
/// use. See the discussion of /proc/sys/net/ipv4/ip_local_port_range in ip(7).
AddressInUse,
/// The argument sockfd is not a valid file descriptor.
InvalidFileDescriptor,
/// The file descriptor sockfd does not refer to a socket.
FileDescriptorNotASocket,
/// The socket is not of a type that supports the listen() operation.
OperationNotSupported,
Unexpected,
};
pub fn posixListen(sockfd: i32, backlog: u32) PosixListenError!void {
const rc = posix.listen(sockfd, backlog);
const err = posix.getErrno(rc);
switch (err) {
0 => return,
posix.EADDRINUSE => return PosixListenError.AddressInUse,
posix.EBADF => return PosixListenError.InvalidFileDescriptor,
posix.ENOTSOCK => return PosixListenError.FileDescriptorNotASocket,
posix.EOPNOTSUPP => return PosixListenError.OperationNotSupported,
else => return unexpectedErrorPosix(err),
}
}
pub const PosixAcceptError = error{
/// The socket is marked nonblocking and no connections are present to be accepted.
WouldBlock,
/// sockfd is not an open file descriptor.
FileDescriptorClosed,
ConnectionAborted,
/// The addr argument is not in a writable part of the user address space.
PageFault,
/// Socket is not listening for connections, or addrlen is invalid (e.g., is negative),
/// or invalid value in flags.
InvalidSyscall,
/// The per-process limit on the number of open file descriptors has been reached.
ProcessFdQuotaExceeded,
/// The system-wide limit on the total number of open files has been reached.
SystemFdQuotaExceeded,
/// Not enough free memory. This often means that the memory allocation is limited
/// by the socket buffer limits, not by the system memory.
SystemResources,
/// The file descriptor sockfd does not refer to a socket.
FileDescriptorNotASocket,
/// The referenced socket is not of type SOCK_STREAM.
OperationNotSupported,
ProtocolFailure,
/// Firewall rules forbid connection.
BlockedByFirewall,
Unexpected,
};
pub fn posixAccept(fd: i32, addr: *posix.sockaddr, flags: u32) PosixAcceptError!i32 {
while (true) {
var sockaddr_size = u32(@sizeOf(posix.sockaddr));
const rc = posix.accept4(fd, addr, &sockaddr_size, flags);
const err = posix.getErrno(rc);
switch (err) {
0 => return @intCast(i32, rc),
posix.EINTR => continue,
else => return unexpectedErrorPosix(err),
posix.EAGAIN => return PosixAcceptError.WouldBlock,
posix.EBADF => return PosixAcceptError.FileDescriptorClosed,
posix.ECONNABORTED => return PosixAcceptError.ConnectionAborted,
posix.EFAULT => return PosixAcceptError.PageFault,
posix.EINVAL => return PosixAcceptError.InvalidSyscall,
posix.EMFILE => return PosixAcceptError.ProcessFdQuotaExceeded,
posix.ENFILE => return PosixAcceptError.SystemFdQuotaExceeded,
posix.ENOBUFS, posix.ENOMEM => return PosixAcceptError.SystemResources,
posix.ENOTSOCK => return PosixAcceptError.FileDescriptorNotASocket,
posix.EOPNOTSUPP => return PosixAcceptError.OperationNotSupported,
posix.EPROTO => return PosixAcceptError.ProtocolFailure,
posix.EPERM => return PosixAcceptError.BlockedByFirewall,
}
}
}
pub const LinuxEpollCreateError = error{
/// Invalid value specified in flags.
InvalidSyscall,
/// The per-user limit on the number of epoll instances imposed by
/// /proc/sys/fs/epoll/max_user_instances was encountered. See epoll(7) for further
/// details.
/// Or, The per-process limit on the number of open file descriptors has been reached.
ProcessFdQuotaExceeded,
/// The system-wide limit on the total number of open files has been reached.
SystemFdQuotaExceeded,
/// There was insufficient memory to create the kernel object.
SystemResources,
Unexpected,
};
pub fn linuxEpollCreate(flags: u32) LinuxEpollCreateError!i32 {
const rc = posix.epoll_create1(flags);
const err = posix.getErrno(rc);
switch (err) {
0 => return @intCast(i32, rc),
else => return unexpectedErrorPosix(err),
posix.EINVAL => return LinuxEpollCreateError.InvalidSyscall,
posix.EMFILE => return LinuxEpollCreateError.ProcessFdQuotaExceeded,
posix.ENFILE => return LinuxEpollCreateError.SystemFdQuotaExceeded,
posix.ENOMEM => return LinuxEpollCreateError.SystemResources,
}
}
pub const LinuxEpollCtlError = error{
/// epfd or fd is not a valid file descriptor.
InvalidFileDescriptor,
/// op was EPOLL_CTL_ADD, and the supplied file descriptor fd is already registered
/// with this epoll instance.
FileDescriptorAlreadyPresentInSet,
/// epfd is not an epoll file descriptor, or fd is the same as epfd, or the requested
/// operation op is not supported by this interface, or
/// An invalid event type was specified along with EPOLLEXCLUSIVE in events, or
/// op was EPOLL_CTL_MOD and events included EPOLLEXCLUSIVE, or
/// op was EPOLL_CTL_MOD and the EPOLLEXCLUSIVE flag has previously been applied to
/// this epfd, fd pair, or
/// EPOLLEXCLUSIVE was specified in event and fd refers to an epoll instance.
InvalidSyscall,
/// fd refers to an epoll instance and this EPOLL_CTL_ADD operation would result in a
/// circular loop of epoll instances monitoring one another.
OperationCausesCircularLoop,
/// op was EPOLL_CTL_MOD or EPOLL_CTL_DEL, and fd is not registered with this epoll
/// instance.
FileDescriptorNotRegistered,
/// There was insufficient memory to handle the requested op control operation.
SystemResources,
/// The limit imposed by /proc/sys/fs/epoll/max_user_watches was encountered while
/// trying to register (EPOLL_CTL_ADD) a new file descriptor on an epoll instance.
/// See epoll(7) for further details.
UserResourceLimitReached,
/// The target file fd does not support epoll. This error can occur if fd refers to,
/// for example, a regular file or a directory.
FileDescriptorIncompatibleWithEpoll,
Unexpected,
};
pub fn linuxEpollCtl(epfd: i32, op: u32, fd: i32, event: *linux.epoll_event) LinuxEpollCtlError!void {
const rc = posix.epoll_ctl(epfd, op, fd, event);
const err = posix.getErrno(rc);
switch (err) {
0 => return,
else => return unexpectedErrorPosix(err),
posix.EBADF => return LinuxEpollCtlError.InvalidFileDescriptor,
posix.EEXIST => return LinuxEpollCtlError.FileDescriptorAlreadyPresentInSet,
posix.EINVAL => return LinuxEpollCtlError.InvalidSyscall,
posix.ELOOP => return LinuxEpollCtlError.OperationCausesCircularLoop,
posix.ENOENT => return LinuxEpollCtlError.FileDescriptorNotRegistered,
posix.ENOMEM => return LinuxEpollCtlError.SystemResources,
posix.ENOSPC => return LinuxEpollCtlError.UserResourceLimitReached,
posix.EPERM => return LinuxEpollCtlError.FileDescriptorIncompatibleWithEpoll,
}
}
pub fn linuxEpollWait(epfd: i32, events: []linux.epoll_event, timeout: i32) usize {
while (true) {
const rc = posix.epoll_wait(epfd, events.ptr, @intCast(u32, events.len), timeout);
const err = posix.getErrno(rc);
switch (err) {
0 => return rc,
posix.EINTR => continue,
posix.EBADF => unreachable,
posix.EFAULT => unreachable,
posix.EINVAL => unreachable,
else => unreachable,
}
}
}
pub const PosixGetSockNameError = error{
/// Insufficient resources were available in the system to perform the operation.
SystemResources,
Unexpected,
};
pub fn posixGetSockName(sockfd: i32) PosixGetSockNameError!posix.sockaddr {
var addr: posix.sockaddr = undefined;
var addrlen: posix.socklen_t = @sizeOf(posix.sockaddr);
const rc = posix.getsockname(sockfd, &addr, &addrlen);
const err = posix.getErrno(rc);
switch (err) {
0 => return addr,
else => return unexpectedErrorPosix(err),
posix.EBADF => unreachable,
posix.EFAULT => unreachable,
posix.EINVAL => unreachable,
posix.ENOTSOCK => unreachable,
posix.ENOBUFS => return PosixGetSockNameError.SystemResources,
}
}
pub const PosixConnectError = error{
/// For UNIX domain sockets, which are identified by pathname: Write permission is denied on the socket
/// file, or search permission is denied for one of the directories in the path prefix.
/// or
/// The user tried to connect to a broadcast address without having the socket broadcast flag enabled or
/// the connection request failed because of a local firewall rule.
PermissionDenied,
/// Local address is already in use.
AddressInUse,
/// (Internet domain sockets) The socket referred to by sockfd had not previously been bound to an
/// address and, upon attempting to bind it to an ephemeral port, it was determined that all port numbers
/// in the ephemeral port range are currently in use. See the discussion of
/// /proc/sys/net/ipv4/ip_local_port_range in ip(7).
AddressNotAvailable,
/// The passed address didn't have the correct address family in its sa_family field.
AddressFamilyNotSupported,
/// Insufficient entries in the routing cache.
SystemResources,
/// A connect() on a stream socket found no one listening on the remote address.
ConnectionRefused,
/// Network is unreachable.
NetworkUnreachable,
/// Timeout while attempting connection. The server may be too busy to accept new connections. Note
/// that for IP sockets the timeout may be very long when syncookies are enabled on the server.
ConnectionTimedOut,
Unexpected,
};
pub fn posixConnect(sockfd: i32, sockaddr: *const posix.sockaddr) PosixConnectError!void {
while (true) {
const rc = posix.connect(sockfd, sockaddr, @sizeOf(posix.sockaddr));
const err = posix.getErrno(rc);
switch (err) {
0 => return,
else => return unexpectedErrorPosix(err),
posix.EACCES => return PosixConnectError.PermissionDenied,
posix.EPERM => return PosixConnectError.PermissionDenied,
posix.EADDRINUSE => return PosixConnectError.AddressInUse,
posix.EADDRNOTAVAIL => return PosixConnectError.AddressNotAvailable,
posix.EAFNOSUPPORT => return PosixConnectError.AddressFamilyNotSupported,
posix.EAGAIN => return PosixConnectError.SystemResources,
posix.EALREADY => unreachable, // The socket is nonblocking and a previous connection attempt has not yet been completed.
posix.EBADF => unreachable, // sockfd is not a valid open file descriptor.
posix.ECONNREFUSED => return PosixConnectError.ConnectionRefused,
posix.EFAULT => unreachable, // The socket structure address is outside the user's address space.
posix.EINPROGRESS => unreachable, // The socket is nonblocking and the connection cannot be completed immediately.
posix.EINTR => continue,
posix.EISCONN => unreachable, // The socket is already connected.
posix.ENETUNREACH => return PosixConnectError.NetworkUnreachable,
posix.ENOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
posix.EPROTOTYPE => unreachable, // The socket type does not support the requested communications protocol.
posix.ETIMEDOUT => return PosixConnectError.ConnectionTimedOut,
}
}
}
/// Same as posixConnect except it is for blocking socket file descriptors.
/// It expects to receive EINPROGRESS.
pub fn posixConnectAsync(sockfd: i32, sockaddr: *const posix.sockaddr) PosixConnectError!void {
while (true) {
const rc = posix.connect(sockfd, sockaddr, @sizeOf(posix.sockaddr));
const err = posix.getErrno(rc);
switch (err) {
0, posix.EINPROGRESS => return,
else => return unexpectedErrorPosix(err),
posix.EACCES => return PosixConnectError.PermissionDenied,
posix.EPERM => return PosixConnectError.PermissionDenied,
posix.EADDRINUSE => return PosixConnectError.AddressInUse,
posix.EADDRNOTAVAIL => return PosixConnectError.AddressNotAvailable,
posix.EAFNOSUPPORT => return PosixConnectError.AddressFamilyNotSupported,
posix.EAGAIN => return PosixConnectError.SystemResources,
posix.EALREADY => unreachable, // The socket is nonblocking and a previous connection attempt has not yet been completed.
posix.EBADF => unreachable, // sockfd is not a valid open file descriptor.
posix.ECONNREFUSED => return PosixConnectError.ConnectionRefused,
posix.EFAULT => unreachable, // The socket structure address is outside the user's address space.
posix.EINTR => continue,
posix.EISCONN => unreachable, // The socket is already connected.
posix.ENETUNREACH => return PosixConnectError.NetworkUnreachable,
posix.ENOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
posix.EPROTOTYPE => unreachable, // The socket type does not support the requested communications protocol.
posix.ETIMEDOUT => return PosixConnectError.ConnectionTimedOut,
}
}
}
pub fn posixGetSockOptConnectError(sockfd: i32) PosixConnectError!void {
var err_code: i32 = undefined;
var size: u32 = @sizeOf(i32);
const rc = posix.getsockopt(sockfd, posix.SOL_SOCKET, posix.SO_ERROR, @ptrCast([*]u8, &err_code), &size);
assert(size == 4);
const err = posix.getErrno(rc);
switch (err) {
0 => switch (err_code) {
0 => return,
else => return unexpectedErrorPosix(err),
posix.EACCES => return PosixConnectError.PermissionDenied,
posix.EPERM => return PosixConnectError.PermissionDenied,
posix.EADDRINUSE => return PosixConnectError.AddressInUse,
posix.EADDRNOTAVAIL => return PosixConnectError.AddressNotAvailable,
posix.EAFNOSUPPORT => return PosixConnectError.AddressFamilyNotSupported,
posix.EAGAIN => return PosixConnectError.SystemResources,
posix.EALREADY => unreachable, // The socket is nonblocking and a previous connection attempt has not yet been completed.
posix.EBADF => unreachable, // sockfd is not a valid open file descriptor.
posix.ECONNREFUSED => return PosixConnectError.ConnectionRefused,
posix.EFAULT => unreachable, // The socket structure address is outside the user's address space.
posix.EISCONN => unreachable, // The socket is already connected.
posix.ENETUNREACH => return PosixConnectError.NetworkUnreachable,
posix.ENOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
posix.EPROTOTYPE => unreachable, // The socket type does not support the requested communications protocol.
posix.ETIMEDOUT => return PosixConnectError.ConnectionTimedOut,
},
else => return unexpectedErrorPosix(err),
posix.EBADF => unreachable, // The argument sockfd is not a valid file descriptor.
posix.EFAULT => unreachable, // The address pointed to by optval or optlen is not in a valid part of the process address space.
posix.EINVAL => unreachable,
posix.ENOPROTOOPT => unreachable, // The option is unknown at the level indicated.
posix.ENOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
}
}
pub const Thread = struct {
data: Data,
pub const use_pthreads = is_posix and builtin.link_libc;
pub const Data = if (use_pthreads)
struct {
handle: c.pthread_t,
stack_addr: usize,
stack_len: usize,
}
else switch (builtin.os) {
builtin.Os.linux => struct {
pid: i32,
stack_addr: usize,
stack_len: usize,
},
builtin.Os.windows => struct {
handle: windows.HANDLE,
alloc_start: *c_void,
heap_handle: windows.HANDLE,
},
else => @compileError("Unsupported OS"),
};
pub fn wait(self: *const Thread) void {
if (use_pthreads) {
const err = c.pthread_join(self.data.handle, null);
switch (err) {
0 => {},
posix.EINVAL => unreachable,
posix.ESRCH => unreachable,
posix.EDEADLK => unreachable,
else => unreachable,
}
assert(posix.munmap(self.data.stack_addr, self.data.stack_len) == 0);
} else switch (builtin.os) {
builtin.Os.linux => {
while (true) {
const pid_value = @atomicLoad(i32, &self.data.pid, builtin.AtomicOrder.SeqCst);
if (pid_value == 0) break;
const rc = linux.futex_wait(@ptrToInt(&self.data.pid), linux.FUTEX_WAIT, pid_value, null);
switch (linux.getErrno(rc)) {
0 => continue,
posix.EINTR => continue,
posix.EAGAIN => continue,
else => unreachable,
}
}
assert(posix.munmap(self.data.stack_addr, self.data.stack_len) == 0);
},
builtin.Os.windows => {
assert(windows.WaitForSingleObject(self.data.handle, windows.INFINITE) == windows.WAIT_OBJECT_0);
assert(windows.CloseHandle(self.data.handle) != 0);
assert(windows.HeapFree(self.data.heap_handle, 0, self.data.alloc_start) != 0);
},
else => @compileError("Unsupported OS"),
}
}
};
pub const SpawnThreadError = error{
/// A system-imposed limit on the number of threads was encountered.
/// There are a number of limits that may trigger this error:
/// * the RLIMIT_NPROC soft resource limit (set via setrlimit(2)),
/// which limits the number of processes and threads for a real
/// user ID, was reached;
/// * the kernel's system-wide limit on the number of processes and
/// threads, /proc/sys/kernel/threads-max, was reached (see
/// proc(5));
/// * the maximum number of PIDs, /proc/sys/kernel/pid_max, was
/// reached (see proc(5)); or
/// * the PID limit (pids.max) imposed by the cgroup "process num‐
/// ber" (PIDs) controller was reached.
ThreadQuotaExceeded,
/// The kernel cannot allocate sufficient memory to allocate a task structure
/// for the child, or to copy those parts of the caller's context that need to
/// be copied.
SystemResources,
/// Not enough userland memory to spawn the thread.
OutOfMemory,
Unexpected,
};
/// caller must call wait on the returned thread
/// fn startFn(@typeOf(context)) T
/// where T is u8, noreturn, void, or !void
/// caller must call wait on the returned thread
pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!*Thread {
// TODO compile-time call graph analysis to determine stack upper bound
// https://github.com/ziglang/zig/issues/157
const default_stack_size = 8 * 1024 * 1024;
const Context = @typeOf(context);
comptime assert(@ArgType(@typeOf(startFn), 0) == Context);
if (builtin.os == builtin.Os.windows) {
const WinThread = struct {
const OuterContext = struct {
thread: Thread,
inner: Context,
};
extern fn threadMain(arg: windows.LPVOID) windows.DWORD {
if (@sizeOf(Context) == 0) {
return startFn({});
} else {
return startFn(@ptrCast(*Context, @alignCast(@alignOf(Context), arg)).*);
}
}
};
const heap_handle = windows.GetProcessHeap() orelse return SpawnThreadError.OutOfMemory;
const byte_count = @alignOf(WinThread.OuterContext) + @sizeOf(WinThread.OuterContext);
const bytes_ptr = windows.HeapAlloc(heap_handle, 0, byte_count) orelse return SpawnThreadError.OutOfMemory;
errdefer assert(windows.HeapFree(heap_handle, 0, bytes_ptr) != 0);
const bytes = @ptrCast([*]u8, bytes_ptr)[0..byte_count];
const outer_context = std.heap.FixedBufferAllocator.init(bytes).allocator.create(WinThread.OuterContext{
.thread = Thread{
.data = Thread.Data{
.heap_handle = heap_handle,
.alloc_start = bytes_ptr,
.handle = undefined,
},
},
.inner = context,
}) catch unreachable;
const parameter = if (@sizeOf(Context) == 0) null else @ptrCast(*c_void, &outer_context.inner);
outer_context.thread.data.handle = windows.CreateThread(null, default_stack_size, WinThread.threadMain, parameter, 0, null) orelse {
const err = windows.GetLastError();
return switch (err) {
else => os.unexpectedErrorWindows(err),
};
};
return &outer_context.thread;
}
const MainFuncs = struct {
extern fn linuxThreadMain(ctx_addr: usize) u8 {
if (@sizeOf(Context) == 0) {
return startFn({});
} else {
return startFn(@intToPtr(*const Context, ctx_addr).*);
}
}
extern fn posixThreadMain(ctx: ?*c_void) ?*c_void {
if (@sizeOf(Context) == 0) {
_ = startFn({});
return null;
} else {
_ = startFn(@ptrCast(*const Context, @alignCast(@alignOf(Context), ctx)).*);
return null;
}
}
};
const MAP_GROWSDOWN = if (builtin.os == builtin.Os.linux) linux.MAP_GROWSDOWN else 0;
const mmap_len = default_stack_size;
const stack_addr = posix.mmap(null, mmap_len, posix.PROT_READ | posix.PROT_WRITE, posix.MAP_PRIVATE | posix.MAP_ANONYMOUS | MAP_GROWSDOWN, -1, 0);
if (stack_addr == posix.MAP_FAILED) return error.OutOfMemory;
errdefer assert(posix.munmap(stack_addr, mmap_len) == 0);
var stack_end: usize = stack_addr + mmap_len;
var arg: usize = undefined;
if (@sizeOf(Context) != 0) {
stack_end -= @sizeOf(Context);
stack_end -= stack_end % @alignOf(Context);
assert(stack_end >= stack_addr);
const context_ptr = @alignCast(@alignOf(Context), @intToPtr(*Context, stack_end));
context_ptr.* = context;
arg = stack_end;
}
stack_end -= @sizeOf(Thread);
stack_end -= stack_end % @alignOf(Thread);
assert(stack_end >= stack_addr);
const thread_ptr = @alignCast(@alignOf(Thread), @intToPtr(*Thread, stack_end));
thread_ptr.data.stack_addr = stack_addr;
thread_ptr.data.stack_len = mmap_len;
if (builtin.os == builtin.Os.windows) {
// use windows API directly
@compileError("TODO support spawnThread for Windows");
} else if (Thread.use_pthreads) {
// use pthreads
var attr: c.pthread_attr_t = undefined;
if (c.pthread_attr_init(&attr) != 0) return SpawnThreadError.SystemResources;
defer assert(c.pthread_attr_destroy(&attr) == 0);
// align to page
stack_end -= stack_end % os.page_size;
assert(c.pthread_attr_setstack(&attr, @intToPtr(*c_void, stack_addr), stack_end - stack_addr) == 0);
const err = c.pthread_create(&thread_ptr.data.handle, &attr, MainFuncs.posixThreadMain, @intToPtr(*c_void, arg));
switch (err) {
0 => return thread_ptr,
posix.EAGAIN => return SpawnThreadError.SystemResources,
posix.EPERM => unreachable,
posix.EINVAL => unreachable,
else => return unexpectedErrorPosix(@intCast(usize, err)),
}
} else if (builtin.os == builtin.Os.linux) {
// use linux API directly. TODO use posix.CLONE_SETTLS and initialize thread local storage correctly
const flags = posix.CLONE_VM | posix.CLONE_FS | posix.CLONE_FILES | posix.CLONE_SIGHAND | posix.CLONE_THREAD | posix.CLONE_SYSVSEM | posix.CLONE_PARENT_SETTID | posix.CLONE_CHILD_CLEARTID | posix.CLONE_DETACHED;
const newtls: usize = 0;
const rc = posix.clone(MainFuncs.linuxThreadMain, stack_end, flags, arg, &thread_ptr.data.pid, newtls, &thread_ptr.data.pid);
const err = posix.getErrno(rc);
switch (err) {
0 => return thread_ptr,
posix.EAGAIN => return SpawnThreadError.ThreadQuotaExceeded,
posix.EINVAL => unreachable,
posix.ENOMEM => return SpawnThreadError.SystemResources,
posix.ENOSPC => unreachable,
posix.EPERM => unreachable,
posix.EUSERS => unreachable,
else => return unexpectedErrorPosix(err),
}
} else {
@compileError("Unsupported OS");
}
}
pub fn posixWait(pid: i32) i32 {
var status: i32 = undefined;
while (true) {
const err = posix.getErrno(posix.waitpid(pid, &status, 0));
switch (err) {
0 => return status,
posix.EINTR => continue,
posix.ECHILD => unreachable, // The process specified does not exist. It would be a race condition to handle this error.
posix.EINVAL => unreachable, // The options argument was invalid
else => unreachable,
}
}
}
pub fn posixFStat(fd: i32) !posix.Stat {
var stat: posix.Stat = undefined;
const err = posix.getErrno(posix.fstat(fd, &stat));
if (err > 0) {
return switch (err) {
posix.EBADF => error.BadFd,
posix.ENOMEM => error.SystemResources,
else => os.unexpectedErrorPosix(err),
};
}
return stat;
} | std/os/index.zig |
const std = @import("std");
const App = @import("app");
const Engine = @import("../Engine.zig");
const structs = @import("../structs.zig");
const enums = @import("../enums.zig");
const js = struct {
extern fn machCanvasInit(width: u32, height: u32, selector_id: *u8) CanvasId;
extern fn machCanvasDeinit(canvas: CanvasId) void;
extern fn machCanvasSetTitle(canvas: CanvasId, title: [*]const u8, len: u32) void;
extern fn machCanvasSetSize(canvas: CanvasId, width: u32, height: u32) void;
extern fn machCanvasGetWindowWidth(canvas: CanvasId) u32;
extern fn machCanvasGetWindowHeight(canvas: CanvasId) u32;
extern fn machCanvasGetFramebufferWidth(canvas: CanvasId) u32;
extern fn machCanvasGetFramebufferHeight(canvas: CanvasId) u32;
extern fn machEventShift() u32;
extern fn machPerfNow() f64;
extern fn machLog(str: [*]const u8, len: u32) void;
extern fn machLogWrite(str: [*]const u8, len: u32) void;
extern fn machLogFlush() void;
extern fn machPanic(str: [*]const u8, len: u32) void;
};
pub const CanvasId = u32;
pub const Core = struct {
id: CanvasId,
selector_id: []const u8,
pub fn init(allocator: std.mem.Allocator, eng: *Engine) !Core {
const options = eng.options;
var selector = [1]u8{0} ** 15;
const id = js.machCanvasInit(options.width, options.height, &selector[0]);
const title = std.mem.span(options.title);
js.machCanvasSetTitle(id, title.ptr, title.len);
return Core{
.id = id,
.selector_id = try allocator.dupe(u8, selector[0 .. selector.len - @as(u32, if (selector[selector.len - 1] == 0) 1 else 0)]),
};
}
pub fn setShouldClose(_: *Core, _: bool) void {}
pub fn getFramebufferSize(core: *Core) structs.Size {
return structs.Size{
.width = js.machCanvasGetFramebufferWidth(core.id),
.height = js.machCanvasGetFramebufferHeight(core.id),
};
}
pub fn getWindowSize(core: *Core) structs.Size {
return structs.Size{
.width = js.machCanvasGetWindowWidth(core.id),
.height = js.machCanvasGetWindowHeight(core.id),
};
}
pub fn setSizeLimits(_: *Core, _: structs.SizeOptional, _: structs.SizeOptional) !void {}
pub fn pollEvent(_: *Core) ?structs.Event {
const event_type = js.machEventShift();
return switch (event_type) {
1 => structs.Event{
.key_press = .{ .key = @intToEnum(enums.Key, js.machEventShift()) },
},
2 => structs.Event{
.key_release = .{ .key = @intToEnum(enums.Key, js.machEventShift()) },
},
else => null,
};
}
};
pub const GpuDriver = struct {
pub fn init(_: std.mem.Allocator, _: *Engine) !GpuDriver {
return GpuDriver{};
}
};
pub const BackingTimer = struct {
initial: f64 = undefined,
const WasmTimer = @This();
pub fn start() !WasmTimer {
return WasmTimer{ .initial = js.machPerfNow() };
}
pub fn read(timer: *WasmTimer) u64 {
return timeToNs(js.machPerfNow() - timer.initial);
}
pub fn reset(timer: *WasmTimer) void {
timer.initial = js.machPerfNow();
}
pub fn lap(timer: *WasmTimer) u64 {
const now = js.machPerfNow();
const initial = timer.initial;
timer.initial = now;
return timeToNs(now - initial);
}
fn timeToNs(t: f64) u64 {
return @floatToInt(u64, t) * 1000000;
}
};
const common = @import("common.zig");
comptime {
common.checkApplication(App);
}
var app: App = undefined;
var engine: Engine = undefined;
export fn wasmInit() void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
// NOTE: On wasm, vsync is double by default and cannot be changed.
// Hence options.vsync is not used anywhere.
const options = if (@hasDecl(App, "options")) App.options else structs.Options{};
engine = Engine.init(allocator, options) catch unreachable;
app.init(&engine) catch {};
}
export fn wasmUpdate() bool {
engine.delta_time_ns = engine.timer.lapPrecise();
engine.delta_time = @intToFloat(f32, engine.delta_time_ns) / @intToFloat(f32, std.time.ns_per_s);
return app.update(&engine) catch false;
}
export fn wasmDeinit() void {
app.deinit(&engine);
}
pub const log_level = .info;
const LogError = error{};
const LogWriter = std.io.Writer(void, LogError, writeLog);
fn writeLog(_: void, msg: []const u8) LogError!usize {
js.machLogWrite(msg.ptr, msg.len);
return msg.len;
}
pub fn log(
comptime message_level: std.log.Level,
comptime scope: @Type(.EnumLiteral),
comptime format: []const u8,
args: anytype,
) void {
const prefix = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): ";
const writer = LogWriter{ .context = {} };
writer.print(message_level.asText() ++ prefix ++ format ++ "\n", args) catch return;
js.machLogFlush();
}
pub fn panic(msg: []const u8, _: ?*std.builtin.StackTrace) noreturn {
js.machPanic(msg.ptr, msg.len);
unreachable;
} | src/platform/wasm.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const zupnp = @import("../../lib.zig");
const xml = @import("xml");
const ActionRequest = zupnp.upnp.device.ActionRequest;
const ActionResult = zupnp.upnp.device.ActionResult;
const DeviceServiceDefinition = zupnp.upnp.definition.DeviceServiceDefinition;
const MediaServer = @This();
const ms_logger = std.log.scoped(.@"zupnp.upnp.device.MediaServer");
pub const device_type = "urn:schemas-upnp-org:device:MediaServer:1";
content_directory: ContentDirectory,
connection_manager: ConnectionManager,
pub fn prepare(self: *MediaServer, allocator: Allocator, _: void, service_list: *std.ArrayList(DeviceServiceDefinition)) !void {
self.content_directory = ContentDirectory.init(allocator);
self.connection_manager = ConnectionManager.init();
try service_list.append(ContentDirectory.service_definition);
try service_list.append(ConnectionManager.service_definition);
}
pub fn deinit(self: *MediaServer) void {
self.content_directory.deinit();
}
pub usingnamespace zupnp.upnp.device.AbstractDevice(MediaServer, ms_logger, .{
"content_directory",
"connection_manager",
});
pub const ContentDirectory = struct {
pub const service_definition = DeviceServiceDefinition {
.service_type = "urn:schemas-upnp-org:service:ContentDirectory:1",
.service_id = "urn:upnp-org:serviceId:ContentDirectory",
.scpd_xml = @embedFile("../definition/content_directory.xml"),
};
const cd_logger = std.log.scoped(.@"zupnp.upnp.device.MediaServer.ContentDirectory");
const cd = zupnp.upnp.definition.content_directory;
pub usingnamespace zupnp.upnp.device.AbstractService(ContentDirectory, cd_logger, .{
.{ cd.GetSearchCapabilitiesOutput, getSearchCapabilities },
.{ cd.GetSortCapabilitiesOutput, getSortCapabilities },
.{ cd.GetSystemUpdateIdOutput, getSystemUpdateID },
.{ cd.BrowseOutput, browse },
});
pub const Contents = struct {
containers: std.ArrayList(cd.Container),
items: std.ArrayList(cd.Item),
};
state: cd.ContentDirectoryState,
containers: std.ArrayList(cd.Container),
items: std.ArrayList(cd.Item),
pub fn init(allocator: Allocator) ContentDirectory {
return .{
.state = .{
.SystemUpdateID = "0",
},
.containers = std.ArrayList(cd.Container).init(allocator),
.items = std.ArrayList(cd.Item).init(allocator),
};
}
pub fn deinit(self: *ContentDirectory) void {
self.containers.deinit();
self.items.deinit();
}
fn getSearchCapabilities(_: *ContentDirectory, _: ActionRequest) !ActionResult {
return ActionResult.createResult(service_definition.service_type, cd.GetSearchCapabilitiesOutput {
.SearchCaps = "",
});
}
fn getSortCapabilities(_: *ContentDirectory, _: ActionRequest) !ActionResult {
return ActionResult.createResult(service_definition.service_type, cd.GetSortCapabilitiesOutput {
.SortCaps = "",
});
}
fn getSystemUpdateID(self: *ContentDirectory, _: ActionRequest) !ActionResult {
return ActionResult.createResult(service_definition.service_type, cd.GetSystemUpdateIdOutput {
.Id = self.state.SystemUpdateID,
});
}
fn browse(self: *ContentDirectory, request: ActionRequest) !ActionResult {
var str = try request.getActionRequest().toString();
defer str.deinit();
var browse_input = xml.decode(
request.allocator,
zupnp.upnp.definition.content_directory.BrowseInput,
request.getActionRequest()
) catch |err| {
cd_logger.warn("Failed to parse browse request: {s}", .{err});
return ActionResult.createError(zupnp.upnp.definition.ActionError.InvalidArgs.toErrorCode());
};
defer browse_input.deinit();
const objectId = browse_input.result.@"u:Browse".ObjectID;
var containers = std.ArrayList(cd.Container).init(request.allocator);
defer containers.deinit();
for (self.containers.items) |c| {
if (std.mem.eql(u8, objectId, c.__attributes__.parentID)) {
try containers.append(c);
}
}
var items = std.ArrayList(cd.Item).init(request.allocator);
defer items.deinit();
for (self.items.items) |i| {
if (std.mem.eql(u8, objectId, i.__attributes__.parentID)) {
try items.append(i);
}
}
const count = containers.items.len + items.items.len;
var count_buf: [8]u8 = undefined;
var count_str = try std.fmt.bufPrintZ(&count_buf, "{d}", .{count});
var didl = try xml.encode(request.allocator, cd.DIDLLite {
.@"DIDL-Lite" = .{
.container = containers.items,
.item = items.items,
}
});
defer didl.deinit();
var didl_str = try didl.toString();
defer didl_str.deinit();
return ActionResult.createResult(service_definition.service_type, cd.BrowseOutput {
.Result = didl_str.string,
.NumberReturned = count_str,
.TotalMatches = count_str,
.UpdateID = "0",
});
}
};
pub const ConnectionManager = struct {
pub const service_definition = DeviceServiceDefinition {
.service_type = "urn:schemas-upnp-org:service:ConnectionManager:1",
.service_id = "urn:upnp-org:serviceId:ConnectionManager",
.scpd_xml = @embedFile("../definition/connection_manager.xml"),
};
const cm_logger = std.log.scoped(.@"zupnp.upnp.device.MediaServer.ConnectionManager");
const cm = zupnp.upnp.definition.connection_manager;
pub usingnamespace zupnp.upnp.device.AbstractService(ConnectionManager, cm_logger, .{
.{ cm.GetProtocolInfoOutput, getProtocolInfo },
.{ cm.GetCurrentConnectionIdsOutput, getCurrentConnectionIDs },
.{ cm.GetCurrentConnectionInfoOutput, getCurrentConnectionInfo },
});
state: cm.ConnectionManagerState,
pub fn init() ConnectionManager {
return .{
.state = .{
.SourceProtocolInfo = "",
.SinkProtocolInfo = "",
.CurrentConnectionIDs = "0",
},
};
}
fn getProtocolInfo(self: *ConnectionManager, _: ActionRequest) !ActionResult {
return ActionResult.createResult(service_definition.service_type, cm.GetProtocolInfoOutput {
.Source = self.state.SourceProtocolInfo,
.Sink = self.state.SinkProtocolInfo,
});
}
fn getCurrentConnectionIDs(self: *ConnectionManager, _: ActionRequest) !ActionResult {
return ActionResult.createResult(service_definition.service_type, cm.GetCurrentConnectionIdsOutput {
.ConnectionIDs = self.state.CurrentConnectionIDs,
});
}
fn getCurrentConnectionInfo(_: *ConnectionManager, _: ActionRequest) !ActionResult {
return ActionResult.createResult(service_definition.service_type, cm.GetCurrentConnectionInfoOutput {
.RcsID = "0",
.AVTransportID = "0",
.ProtocolInfo = "",
.PeerConnectionManager = "",
.PeerConnectionID = "-1",
.Direction = "Input",
.Status = "Unknown",
});
}
}; | src/upnp/device/media_server.zig |
const std = @import("std");
const Assembunny = @This();
const Register = u2;
const Operand = union(enum) {
Immediate: i8,
Register: Register,
fn detect(str: []const u8) !Operand {
return if (str[0] <= '9')
Operand{ .Immediate = try std.fmt.parseInt(i8, str, 10) }
else
Operand{ .Register = convertRegister(str) }
;
}
fn fetch(self: Operand, registers: []isize) isize {
return switch (self) {
.Immediate => |i| i,
.Register => |r| registers[r],
};
}
};
const DualArgument = struct {
op1: Operand, op2: Operand
};
const Instruction = union(enum) {
Copy: DualArgument,
Increment: Operand,
Decrement: Operand,
JumpNotZero: DualArgument,
Toggle: Operand,
};
const Instructions = std.ArrayList(Instruction);
registers: [4]isize,
instructions: Instructions,
pub fn init(allocator: std.mem.Allocator) Assembunny {
var computer: Assembunny = undefined;
_ = computer.reset();
computer.instructions = Instructions.init(allocator);
return computer;
}
pub fn deinit(self: *Assembunny) void {
self.instructions.deinit();
}
pub fn reset(self: *Assembunny) *Assembunny {
self.registers = [_]isize {0} ** 4;
return self;
}
pub fn feed(self: *Assembunny, line: []const u8) !void {
var tokens = std.mem.tokenize(u8, line, " ");
const opcode = tokens.next().?;
const x = tokens.next().?;
const y = tokens.next();
const instruction = switch (opcode[0]) {
'c' => Instruction{ .Copy = .{ .op1 = try Operand.detect(x), .op2 = try Operand.detect(y.?) } },
'i' => Instruction{ .Increment = try Operand.detect(x) },
'd' => Instruction{ .Decrement = try Operand.detect(x) },
'j' => Instruction{ .JumpNotZero = .{ .op1 = try Operand.detect(x), .op2 = try Operand.detect(y.?) } },
't' => Instruction{ .Toggle = try Operand.detect(x) },
else => unreachable
};
try self.instructions.append(instruction);
}
pub fn runAndFetchRegisterA(self: *Assembunny) !isize {
var instructions = try self.instructions.allocator.dupe(Instruction, self.instructions.items);
defer self.instructions.allocator.free(instructions);
var pc: isize = 0;
while (pc < instructions.len) : (pc += 1) {
switch (instructions[@intCast(u7, pc)]) {
.Copy => |c| switch (c.op2) {
.Register => |dest| self.registers[dest] = c.op1.fetch(&self.registers),
else => {}
},
.Increment => |op| switch (op) {
.Register => |dest| self.registers[dest] += 1,
else => {}
},
.Decrement => |op| switch (op) {
.Register => |dest| self.registers[dest] -= 1,
else => {}
},
.JumpNotZero => |j| if (j.op1.fetch(&self.registers) != 0) { pc += j.op2.fetch(&self.registers) - 1; },
.Toggle => |op| blk: {
const targetPcMaybe = pc + op.fetch(&self.registers);
if (targetPcMaybe < 0 or targetPcMaybe >= instructions.len) {
break :blk;
}
const targetPc = @intCast(usize, targetPcMaybe);
instructions[targetPc] = switch (instructions[targetPc]) {
.Copy => |c| Instruction{ .JumpNotZero = c },
.Increment => |i| Instruction{ .Decrement = i },
.Decrement => |d| Instruction{ .Increment = d },
.JumpNotZero => |j| Instruction{ .Copy = j },
.Toggle => |t| Instruction{ .Increment = t },
};
},
}
}
return self.registers[convertRegister("a")];
}
pub inline fn setRegister(self: *Assembunny, reg: []const u8, value: isize) *Assembunny {
self.registers[convertRegister(reg)] = value;
return self;
}
inline fn convertRegister(str: []const u8) Register {
return @intCast(Register, str[0] - 'a');
} | src/main/zig/2016/assembunny.zig |
const c = @cImport({
@cInclude("SDL.h");
});
const m = @cImport({
@cInclude("SDL_mixer.h");
});
const assert = @import("std").debug.assert;
const warn = @import("std").log.warn;
const SdlError = error{
InitializationFailed,
CreateWindowFailed,
CreateRendererFailed,
LoadWavFailed,
OpenAudioFailed,
};
pub const EventKind = enum {
KeyDown,
KeyUp,
Quit,
None,
};
pub const Event = struct {
kind: EventKind,
data: u32 = 0,
pub fn quitEvent() Event {
return Event{
.kind = .Quit,
};
}
pub fn noneEvent() Event {
return Event{
.kind = .None,
};
}
pub fn keyEvent(event: u32, key: u32) Event {
_ = event;
var kind: EventKind = undefined;
if (event == c.SDL_KEYDOWN) {
kind = .KeyDown;
} else {
kind = .KeyUp;
}
return Event{
.kind = kind,
.data = key,
};
}
};
pub const Key = enum {
Key_0,
Key_1,
Key_2,
Key_3,
Key_4,
Key_5,
Key_6,
Key_7,
Key_8,
Key_9,
Key_A,
Key_B,
Key_C,
Key_D,
Key_E,
Key_F,
};
const SdlAudio = struct {
beep: *m.Mix_Chunk,
};
pub const Sdl = struct {
screen: *c.SDL_Window,
renderer: *c.SDL_Renderer,
audio: ?SdlAudio,
pub fn init() SdlError!Sdl {
if (c.SDL_Init(c.SDL_INIT_VIDEO | c.SDL_INIT_AUDIO) != 0) {
c.SDL_Log("Unable to initialize SDL: %s", c.SDL_GetError());
return SdlError.InitializationFailed;
}
const screen = c.SDL_CreateWindow("My Game Window", c.SDL_WINDOWPOS_UNDEFINED, c.SDL_WINDOWPOS_UNDEFINED, 640, 320, c.SDL_WINDOW_SHOWN) orelse
{
c.SDL_Log("Unable to create window: %s", c.SDL_GetError());
return SdlError.CreateWindowFailed;
};
const renderer = c.SDL_CreateRenderer(screen, -1, 0) orelse {
c.SDL_Log("Unable to create renderer: %s", c.SDL_GetError());
return SdlError.CreateRendererFailed;
};
_ = c.SDL_RenderSetLogicalSize(renderer, 64, 32);
const audio = try initSound();
return Sdl{
.screen = screen,
.renderer = renderer,
.audio = audio,
};
}
fn initSound() SdlError!SdlAudio {
if (m.Mix_OpenAudio(44100, m.MIX_DEFAULT_FORMAT, 2, 2048) < 0) {
c.SDL_Log("Unable to open audio device: %s", c.SDL_GetError());
return SdlError.OpenAudioFailed;
}
const beep = m.Mix_LoadWAV("res/beep.wav") orelse
{
c.SDL_Log("Failed to load beep sound effect: %s", m.Mix_GetError());
return SdlError.LoadWavFailed;
};
return SdlAudio{
.beep = beep,
};
}
pub fn playBeep(self: *Sdl) void {
if (self.audio) |audio| {
_ = m.Mix_PlayChannel(-1, audio.beep, 0);
}
}
pub fn updateScreen(self: *Sdl, screen: *[32][64]u8) void {
_ = c.SDL_SetRenderDrawColor(self.renderer, 0, 0, 0, 0xFF);
_ = c.SDL_RenderClear(self.renderer);
_ = c.SDL_SetRenderDrawColor(self.renderer, 0xFF, 0xFF, 0xFF, 0xFF);
for (screen) |line, y| {
for (line) |pixel, x| {
if (pixel == 1) {
_ = c.SDL_RenderDrawPoint(self.renderer, @intCast(c_int, x), @intCast(c_int, y));
}
}
}
c.SDL_RenderPresent(self.renderer);
}
fn getKeyFromScancode(self: *Sdl, scancode: u32) ?u32 {
_ = self;
var key: u32 = undefined;
switch (scancode) {
0x1e => key = 0x1,
0x1f => key = 0x2,
0x20 => key = 0x3,
0x21 => key = 0xc,
0x14 => key = 0x4,
0x1a => key = 0x5,
0x08 => key = 0x6,
0x15 => key = 0xd,
0x04 => key = 0x7,
0x16 => key = 0x8,
0x07 => key = 0x9,
0x09 => key = 0xe,
0x1d => key = 0xa,
0x1b => key = 0x0,
0x06 => key = 0xb,
0x19 => key = 0xf,
else => return null,
}
return key;
}
pub fn getEvent(self: *Sdl) Event {
_ = self;
var event: c.SDL_Event = undefined;
if (c.SDL_PollEvent(&event) != 0) {
switch (event.@"type") {
c.SDL_QUIT => return Event.quitEvent(),
c.SDL_KEYDOWN, c.SDL_KEYUP => {
const key: c.SDL_KeyboardEvent = event.key;
var keynum: u32 = self.getKeyFromScancode(key.keysym.scancode) orelse {
return Event.noneEvent();
};
return Event.keyEvent(event.@"type", keynum);
},
else => {},
}
}
return Event.noneEvent();
}
}; | src/sdl.zig |
const std = @import("std");
const fmt = std.fmt;
const io = std.io;
const codes = @import("./codes.zig");
pub const Error = std.os.WriteError || std.fmt.BufPrintError;
// TODO Is it ok to use global stdout (thread-safety)?
// TODO consider passing a writer as argument (various possible sinks: stdout, stderr, membufs, etc)
const stdout = io.getStdOut();
pub fn move(buf: []u8, row: u32, col: u32) Error!void {
// TODO assert min buf len?
std.debug.assert(row <= 9999);
std.debug.assert(col <= 9999);
const escapeSequence = try fmt.bufPrint(buf, "{s}{s};{s}{s}", .{
codes.EscapePrefix,
row,
col,
codes.cursor.PositionSuffix1, // TODO Suffix1 or 2? what is the difference?!
});
_ = try stdout.write(escapeSequence);
}
pub fn up(buf: []u8, offset: u32) Error!void {
// TODO assert min buf len?
std.debug.assert(offset <= 9999);
const escapeSequence = try fmt.bufPrint(buf, "{s}{s}{s}", .{
codes.EscapePrefix,
offset,
codes.cursor.UpSuffix,
});
_ = try stdout.write(escapeSequence);
}
pub fn down(buf: []u8, offset: u32) Error!void {
// TODO assert min buf len?
std.debug.assert(offset <= 9999);
const escapeSequence = try fmt.bufPrint(buf, "{s}{s}{s}", .{
codes.EscapePrefix,
offset,
codes.cursor.DownSuffix,
});
_ = try stdout.write(escapeSequence);
}
pub fn forward(buf: []u8, offset: u32) Error!void {
// TODO assert min buf len?
std.debug.assert(offset <= 9999);
const escapeSequence = try fmt.bufPrint(buf, "{s}{s}{s}", .{
codes.EscapePrefix,
offset,
codes.cursor.ForwardSuffix,
});
_ = try stdout.write(escapeSequence);
}
pub fn backward(buf: []u8, offset: u32) Error!void {
// TODO assert min buf len?
std.debug.assert(offset <= 9999);
const escapeSequence = try fmt.bufPrint(buf, "{s}{s}{s}", .{
codes.EscapePrefix,
offset,
codes.cursor.BackwardSuffix,
});
_ = try stdout.write(escapeSequence);
}
pub fn savePosition(buf: []u8) Error!void {
// TODO assert min buf len?
const escapeSequence = try fmt.bufPrint(buf, "{s}{s}", .{
codes.EscapePrefix,
codes.cursor.SavePositionSuffix,
});
_ = try stdout.write(escapeSequence);
}
pub fn restorePosition(buf: []u8) Error!void {
// TODO assert min buf len?
const escapeSequence = try fmt.bufPrint(buf, "{s}{s}", .{
codes.EscapePrefix,
codes.cursor.RestorePositionSuffix,
});
_ = try stdout.write(escapeSequence);
}
pub fn eraseDisplay(buf: []u8) Error!void {
// TODO assert min buf len?
const escapeSequence = try fmt.bufPrint(buf, "{s}{s}", .{
codes.EscapePrefix,
codes.cursor.EraseDisplaySuffix,
});
_ = try stdout.write(escapeSequence);
}
pub fn eraseLine(buf: []u8) Error!void {
// TODO assert min buf len?
const escapeSequence = try fmt.bufPrint(buf, "{s}{s}", .{
codes.EscapePrefix,
codes.cursor.EraseLineSuffix,
});
_ = try stdout.write(escapeSequence);
}
// TODO add tests | src/cursor.zig |
// ┌───────────────────────────────────────────────────────────────────────────┐
// │ │
// │ Platform Constants │
// │ │
// └───────────────────────────────────────────────────────────────────────────┘
pub const SCREEN_SIZE: u32 = 160;
// ┌───────────────────────────────────────────────────────────────────────────┐
// │ │
// │ Memory Addresses │
// │ │
// └───────────────────────────────────────────────────────────────────────────┘
pub const PALETTE: *[4]u32 = @intToPtr(*[4]u32, 0x04);
pub const DRAW_COLORS: *u16 = @intToPtr(*u16, 0x14);
pub const GAMEPAD1: *const u8 = @intToPtr(*const u8, 0x16);
pub const GAMEPAD2: *const u8 = @intToPtr(*const u8, 0x17);
pub const GAMEPAD3: *const u8 = @intToPtr(*const u8, 0x18);
pub const GAMEPAD4: *const u8 = @intToPtr(*const u8, 0x19);
pub const MOUSE_X: *const i16 = @intToPtr(*const i16, 0x1a);
pub const MOUSE_Y: *const i16 = @intToPtr(*const i16, 0x1c);
pub const MOUSE_BUTTONS: *const u8 = @intToPtr(*const u8, 0x1e);
pub const SYSTEM_FLAGS: *u8 = @intToPtr(*u8, 0x1f);
pub const FRAMEBUFFER: *[6400]u8 = @intToPtr(*[6400]u8, 0xA0);
pub const BUTTON_1: u8 = 1;
pub const BUTTON_2: u8 = 2;
pub const BUTTON_LEFT: u8 = 16;
pub const BUTTON_RIGHT: u8 = 32;
pub const BUTTON_UP: u8 = 64;
pub const BUTTON_DOWN: u8 = 128;
pub const MOUSE_LEFT: u8 = 1;
pub const MOUSE_RIGHT: u8 = 2;
pub const MOUSE_MIDDLE: u8 = 4;
pub const SYSTEM_PRESERVE_FRAMEBUFFER: u8 = 1;
pub const SYSTEM_HIDE_GAMEPAD_OVERLAY: u8 = 2;
// ┌───────────────────────────────────────────────────────────────────────────┐
// │ │
// │ Drawing Functions │
// │ │
// └───────────────────────────────────────────────────────────────────────────┘
/// Copies pixels to the framebuffer.
pub extern fn blit(sprite: [*]const u8, x: i32, y: i32, width: i32, height: i32, flags: u32) void;
/// Copies a subregion within a larger sprite atlas to the framebuffer.
pub extern fn blitSub(sprite: [*]const u8, x: i32, y: i32, width: i32, height: i32, src_x: u32, src_y: u32, stride: i32, flags: u32) void;
pub const BLIT_2BPP: u32 = 1;
pub const BLIT_1BPP: u32 = 0;
pub const BLIT_FLIP_X: u32 = 2;
pub const BLIT_FLIP_Y: u32 = 4;
pub const BLIT_ROTATE: u32 = 8;
/// Draws a line between two points.
pub extern fn line(x1: i32, y1: i32, x2: i32, y2: i32) void;
/// Draws an oval (or circle).
pub extern fn oval(x: i32, y: i32, width: i32, height: i32) void;
/// Draws a rectangle.
pub extern fn rect(x: i32, y: i32, width: u32, height: u32) void;
/// Draws text using the built-in system font.
pub fn text(str: []const u8, x: i32, y: i32) void {
textUtf8(str.ptr, str.len, x, y);
}
extern fn textUtf8(strPtr: [*]const u8, strLen: usize, x: i32, y: i32) void;
/// Draws a vertical line
pub extern fn vline(x: i32, y: i32, len: u32) void;
/// Draws a horizontal line
pub extern fn hline(x: i32, y: i32, len: u32) void;
// ┌───────────────────────────────────────────────────────────────────────────┐
// │ │
// │ Sound Functions │
// │ │
// └───────────────────────────────────────────────────────────────────────────┘
/// Plays a sound tone.
pub extern fn tone(frequency: u32, duration: u32, volume: u32, flags: u32) void;
pub const TONE_PULSE1: u32 = 0;
pub const TONE_PULSE2: u32 = 1;
pub const TONE_TRIANGLE: u32 = 2;
pub const TONE_NOISE: u32 = 3;
pub const TONE_MODE1: u32 = 0;
pub const TONE_MODE2: u32 = 4;
pub const TONE_MODE3: u32 = 8;
pub const TONE_MODE4: u32 = 12;
pub const TONE_PAN_LEFT: u32 = 16;
pub const TONE_PAN_RIGHT: u32 = 32;
// ┌───────────────────────────────────────────────────────────────────────────┐
// │ │
// │ Storage Functions │
// │ │
// └───────────────────────────────────────────────────────────────────────────┘
/// Reads up to `size` bytes from persistent storage into the pointer `dest`.
pub extern fn diskr(dest: [*]u8, size: u32) u32;
/// Writes up to `size` bytes from the pointer `src` into persistent storage.
pub extern fn diskw(src: [*]const u8, size: u32) u32;
// ┌───────────────────────────────────────────────────────────────────────────┐
// │ │
// │ Other Functions │
// │ │
// └───────────────────────────────────────────────────────────────────────────┘
/// Prints a message to the debug console.
pub fn trace(x: []const u8) void {
traceUtf8(x.ptr, x.len);
}
extern fn traceUtf8(strPtr: [*]const u8, strLen: usize) void;
/// Use with caution, as there's no compile-time type checking.
///
/// * %c, %d, and %x expect 32-bit integers.
/// * %f expects 64-bit floats.
/// * %s expects a *zero-terminated* string pointer.
///
/// See https://github.com/aduros/wasm4/issues/244 for discussion and type-safe
/// alternatives.
pub extern fn tracef(x: [*:0]const u8, ...) void; | cli/assets/templates/zig/src/wasm4.zig |
const Allocator = std.mem.Allocator;
const h11 = @import("h11");
const Method = @import("http").Method;
const Socket = @import("socket.zig").Socket;
const Request = @import("request.zig").Request;
const Response = @import("response.zig").Response;
const std = @import("std");
const StreamingResponse = @import("response.zig").StreamingResponse;
const Uri = @import("http").Uri;
pub const TcpConnection = Connection(Socket);
pub fn Connection(comptime SocketType: type) type {
return struct {
const Self = @This();
allocator: *Allocator,
state: h11.Client,
socket: SocketType,
pub fn init(allocator: *Allocator, socket: SocketType) Self {
return Self {
.allocator = allocator,
.socket = socket,
.state = h11.Client.init(allocator),
};
}
pub fn connect(allocator: *Allocator, uri: Uri) !Self {
var socket = try SocketType.connect(allocator, uri);
return Self.init(allocator, socket);
}
pub fn deinit(self: *Self) void {
self.state.deinit();
self.socket.close();
}
pub fn request(self: *Self, method: Method, uri: Uri, options: anytype) !Response {
var _request = try Request.init(self.allocator, method, uri, options);
defer _request.deinit();
try self.sendRequest(_request);
var response = try self.readResponse();
var body = try self.readResponseBody();
return Response {
.allocator = self.allocator,
.buffer = response.raw_bytes,
.status = response.statusCode,
.version = response.version,
.headers = response.headers,
.body = body,
};
}
pub fn stream(self: *Self, method: Method, uri: Uri, options: anytype) !StreamingResponse(Self) {
var _request = try Request.init(self.allocator, method, uri, options);
defer _request.deinit();
try self.sendRequest(_request);
var response = try self.readResponse();
return StreamingResponse(Self) {
.allocator = self.allocator,
.buffer = response.raw_bytes,
.connection = self,
.status = response.statusCode,
.version = response.version,
.headers = response.headers,
};
}
fn sendRequest(self: *Self, _request: Request) !void {
var request_event = try h11.Request.init(_request.method, _request.path, _request.version, _request.headers);
var bytes = try self.state.send(h11.Event {.Request = request_event });
try self.socket.write(bytes);
self.allocator.free(bytes);
switch(_request.body) {
.Empty => return,
.ContentLength => |body| {
var data_event = h11.Data.to_event(null, body.content);
bytes = try self.state.send(data_event);
try self.socket.write(bytes);
}
}
}
fn readResponse(self: *Self) !h11.Response {
var event = try self.nextEvent();
switch (event) {
.Response => |response| {
return response;
},
else => unreachable,
}
}
fn readResponseBody(self: *Self) ![]const u8 {
var event = try self.nextEvent();
return switch (event) {
.Data => |data| data.content,
.EndOfMessage => "",
else => unreachable,
};
}
pub fn nextEvent(self: *Self) !h11.Event {
while (true) {
var event = self.state.nextEvent() catch |err| switch (err) {
error.NeedData => {
var buffer: [1024]u8 = undefined;
const bytesReceived = try self.socket.receive(&buffer);
var content = buffer[0..bytesReceived];
try self.state.receive(content);
continue;
},
else => {
return err;
}
};
return event;
}
}
};
}
const ConnectionMock = Connection(SocketMock);
const expect = std.testing.expect;
const Headers = @import("http").Headers;
const SocketMock = @import("socket.zig").SocketMock;
test "Get" {
const uri = try Uri.parse("http://httpbin.org/get", false);
var connection = try ConnectionMock.connect(std.testing.allocator, uri);
defer connection.deinit();
try connection.socket.have_received(
"HTTP/1.1 200 OK\r\nContent-Length: 14\r\nServer: gunicorn/19.9.0\r\n\r\n"
++ "Gotta Go Fast!"
);
var response = try connection.request(.Get, uri, .{});
defer response.deinit();
expect(response.status == .Ok);
expect(response.version == .Http11);
var headers = response.headers.items();
expect(std.mem.eql(u8, headers[0].name.raw(), "Content-Length"));
expect(std.mem.eql(u8, headers[1].name.raw(), "Server"));
expect(response.body.len == 14);
}
test "Get with headers" {
const uri = try Uri.parse("http://httpbin.org/get", false);
var connection = try ConnectionMock.connect(std.testing.allocator, uri);
defer connection.deinit();
try connection.socket.have_received(
"HTTP/1.1 200 OK\r\nContent-Length: 14\r\nServer: gunicorn/19.9.0\r\n\r\n"
++ "Gotta Go Fast!"
);
var headers = Headers.init(std.testing.allocator);
defer headers.deinit();
try headers.append("Gotta-go", "Fast!");
var response = try connection.request(.Get, uri, .{ .headers = headers.items()});
defer response.deinit();
expect(connection.socket.have_sent("GET /get HTTP/1.1\r\nHost: httpbin.org\r\nGotta-go: Fast!\r\n\r\n"));
}
test "Get with compile-time headers" {
const uri = try Uri.parse("http://httpbin.org/get", false);
var connection = try ConnectionMock.connect(std.testing.allocator, uri);
defer connection.deinit();
try connection.socket.have_received(
"HTTP/1.1 200 OK\r\nContent-Length: 14\r\nServer: gunicorn/19.9.0\r\n\r\n"
++ "Gotta Go Fast!"
);
var headers = .{
.{"Gotta-go", "Fast!"}
};
var response = try connection.request(.Get, uri, .{ .headers = headers});
defer response.deinit();
expect(connection.socket.have_sent("GET /get HTTP/1.1\r\nHost: httpbin.org\r\nGotta-go: Fast!\r\n\r\n"));
}
test "Post binary data" {
const uri = try Uri.parse("http://httpbin.org/post", false);
var connection = try ConnectionMock.connect(std.testing.allocator, uri);
defer connection.deinit();
try connection.socket.have_received(
"HTTP/1.1 200 OK\r\nContent-Length: 14\r\nServer: gunicorn/19.9.0\r\n\r\n"
++ "Gotta Go Fast!"
);
var response = try connection.request(.Post, uri, .{ .content = "Gotta go fast!"});
defer response.deinit();
expect(connection.socket.have_sent("POST /post HTTP/1.1\r\nHost: httpbin.org\r\nContent-Length: 14\r\n\r\nGotta go fast!"));
}
test "Head request has no message body" {
const uri = try Uri.parse("http://httpbin.org/head", false);
var connection = try ConnectionMock.connect(std.testing.allocator, uri);
defer connection.deinit();
try connection.socket.have_received("HTTP/1.1 200 OK\r\nContent-Length: 14\r\nServer: gunicorn/19.9.0\r\n\r\n");
var response = try connection.request(.Head, uri, .{});
defer response.deinit();
expect(response.body.len == 0);
}
test "Requesting an IP address and a port should be in HOST headers" {
const uri = try Uri.parse("http://127.0.0.1:8080/", false);
var connection = try ConnectionMock.connect(std.testing.allocator, uri);
defer connection.deinit();
try connection.socket.have_received("HTTP/1.1 200 OK\r\n\r\n");
var response = try connection.request(.Get, uri, .{});
defer response.deinit();
expect(connection.socket.have_sent("GET / HTTP/1.1\r\nHost: 127.0.0.1:8080\r\n\r\n"));
}
test "Request a URI without path defaults to /" {
const uri = try Uri.parse("http://httpbin.org", false);
var connection = try ConnectionMock.connect(std.testing.allocator, uri);
defer connection.deinit();
try connection.socket.have_received("HTTP/1.1 200 OK\r\n\r\n");
var response = try connection.request(.Get, uri, .{});
defer response.deinit();
expect(connection.socket.have_sent("GET / HTTP/1.1\r\nHost: httpbin.org\r\n\r\n"));
}
test "Get a response in multiple socket read" {
const uri = try Uri.parse("http://httpbin.org", false);
var connection = try ConnectionMock.connect(std.heap.page_allocator, uri);
defer connection.deinit();
try connection.socket.have_received("HTTP/1.1 200 OK\r\nContent-Length: 14\r\n\r\n");
try connection.socket.have_received("Gotta go fast!");
var response = try connection.request(.Get, uri, .{});
defer response.deinit();
expect(response.status == .Ok);
expect(response.version == .Http11);
var headers = response.headers.items();
expect(std.mem.eql(u8, headers[0].name.raw(), "Content-Length"));
expect(std.mem.eql(u8, headers[0].value, "14"));
expect(response.body.len == 14);
}
test "Get a streaming response" {
const uri = try Uri.parse("http://httpbin.org", false);
var connection = try ConnectionMock.connect(std.heap.page_allocator, uri);
try connection.socket.have_received("HTTP/1.1 200 OK\r\nContent-Length: 3072\r\n\r\n");
var data = [_]u8{'a'} ** 1024;
try connection.socket.have_received(&data);
try connection.socket.have_received(&data);
try connection.socket.have_received(&data);
var response = try connection.stream(.Get, uri, .{});
defer response.deinit();
expect(response.status == .Ok);
expect(response.version == .Http11);
var headers = response.headers.items();
expect(std.mem.eql(u8, headers[0].name.raw(), "Content-Length"));
expect(std.mem.eql(u8, headers[0].value, "3072"));
while(true) {
var chunk = try response.next_chunk();
if (chunk == null) {
break;
}
expect(std.mem.eql(u8, chunk.?, &data));
}
} | src/connection.zig |
pub const NLM_MAX_ADDRESS_LIST_SIZE = @as(u32, 10);
pub const NLM_UNKNOWN_DATAPLAN_STATUS = @as(u32, 4294967295);
//--------------------------------------------------------------------------------
// Section: Types (26)
//--------------------------------------------------------------------------------
const CLSID_NetworkListManager_Value = Guid.initString("dcb00c01-570f-4a9b-8d69-199fdba5723b");
pub const CLSID_NetworkListManager = &CLSID_NetworkListManager_Value;
pub const NLM_CONNECTION_COST = enum(i32) {
UNKNOWN = 0,
UNRESTRICTED = 1,
FIXED = 2,
VARIABLE = 4,
OVERDATALIMIT = 65536,
CONGESTED = 131072,
ROAMING = 262144,
APPROACHINGDATALIMIT = 524288,
};
pub const NLM_CONNECTION_COST_UNKNOWN = NLM_CONNECTION_COST.UNKNOWN;
pub const NLM_CONNECTION_COST_UNRESTRICTED = NLM_CONNECTION_COST.UNRESTRICTED;
pub const NLM_CONNECTION_COST_FIXED = NLM_CONNECTION_COST.FIXED;
pub const NLM_CONNECTION_COST_VARIABLE = NLM_CONNECTION_COST.VARIABLE;
pub const NLM_CONNECTION_COST_OVERDATALIMIT = NLM_CONNECTION_COST.OVERDATALIMIT;
pub const NLM_CONNECTION_COST_CONGESTED = NLM_CONNECTION_COST.CONGESTED;
pub const NLM_CONNECTION_COST_ROAMING = NLM_CONNECTION_COST.ROAMING;
pub const NLM_CONNECTION_COST_APPROACHINGDATALIMIT = NLM_CONNECTION_COST.APPROACHINGDATALIMIT;
pub const NLM_USAGE_DATA = extern struct {
UsageInMegabytes: u32,
LastSyncTime: FILETIME,
};
pub const NLM_DATAPLAN_STATUS = extern struct {
InterfaceGuid: Guid,
UsageData: NLM_USAGE_DATA,
DataLimitInMegabytes: u32,
InboundBandwidthInKbps: u32,
OutboundBandwidthInKbps: u32,
NextBillingCycle: FILETIME,
MaxTransferSizeInMegabytes: u32,
Reserved: u32,
};
pub const NLM_SOCKADDR = extern struct {
data: [128]u8,
};
pub const NLM_NETWORK_CLASS = enum(i32) {
IDENTIFYING = 1,
IDENTIFIED = 2,
UNIDENTIFIED = 3,
};
pub const NLM_NETWORK_IDENTIFYING = NLM_NETWORK_CLASS.IDENTIFYING;
pub const NLM_NETWORK_IDENTIFIED = NLM_NETWORK_CLASS.IDENTIFIED;
pub const NLM_NETWORK_UNIDENTIFIED = NLM_NETWORK_CLASS.UNIDENTIFIED;
pub const NLM_SIMULATED_PROFILE_INFO = extern struct {
ProfileName: [256]u16,
cost: NLM_CONNECTION_COST,
UsageInMegabytes: u32,
DataLimitInMegabytes: u32,
};
pub const NLM_INTERNET_CONNECTIVITY = enum(i32) {
WEBHIJACK = 1,
PROXIED = 2,
CORPORATE = 4,
};
pub const NLM_INTERNET_CONNECTIVITY_WEBHIJACK = NLM_INTERNET_CONNECTIVITY.WEBHIJACK;
pub const NLM_INTERNET_CONNECTIVITY_PROXIED = NLM_INTERNET_CONNECTIVITY.PROXIED;
pub const NLM_INTERNET_CONNECTIVITY_CORPORATE = NLM_INTERNET_CONNECTIVITY.CORPORATE;
pub const NLM_CONNECTIVITY = enum(i32) {
DISCONNECTED = 0,
IPV4_NOTRAFFIC = 1,
IPV6_NOTRAFFIC = 2,
IPV4_SUBNET = 16,
IPV4_LOCALNETWORK = 32,
IPV4_INTERNET = 64,
IPV6_SUBNET = 256,
IPV6_LOCALNETWORK = 512,
IPV6_INTERNET = 1024,
};
pub const NLM_CONNECTIVITY_DISCONNECTED = NLM_CONNECTIVITY.DISCONNECTED;
pub const NLM_CONNECTIVITY_IPV4_NOTRAFFIC = NLM_CONNECTIVITY.IPV4_NOTRAFFIC;
pub const NLM_CONNECTIVITY_IPV6_NOTRAFFIC = NLM_CONNECTIVITY.IPV6_NOTRAFFIC;
pub const NLM_CONNECTIVITY_IPV4_SUBNET = NLM_CONNECTIVITY.IPV4_SUBNET;
pub const NLM_CONNECTIVITY_IPV4_LOCALNETWORK = NLM_CONNECTIVITY.IPV4_LOCALNETWORK;
pub const NLM_CONNECTIVITY_IPV4_INTERNET = NLM_CONNECTIVITY.IPV4_INTERNET;
pub const NLM_CONNECTIVITY_IPV6_SUBNET = NLM_CONNECTIVITY.IPV6_SUBNET;
pub const NLM_CONNECTIVITY_IPV6_LOCALNETWORK = NLM_CONNECTIVITY.IPV6_LOCALNETWORK;
pub const NLM_CONNECTIVITY_IPV6_INTERNET = NLM_CONNECTIVITY.IPV6_INTERNET;
pub const NLM_DOMAIN_TYPE = enum(i32) {
NON_DOMAIN_NETWORK = 0,
DOMAIN_NETWORK = 1,
DOMAIN_AUTHENTICATED = 2,
};
pub const NLM_DOMAIN_TYPE_NON_DOMAIN_NETWORK = NLM_DOMAIN_TYPE.NON_DOMAIN_NETWORK;
pub const NLM_DOMAIN_TYPE_DOMAIN_NETWORK = NLM_DOMAIN_TYPE.DOMAIN_NETWORK;
pub const NLM_DOMAIN_TYPE_DOMAIN_AUTHENTICATED = NLM_DOMAIN_TYPE.DOMAIN_AUTHENTICATED;
pub const NLM_ENUM_NETWORK = enum(i32) {
CONNECTED = 1,
DISCONNECTED = 2,
ALL = 3,
};
pub const NLM_ENUM_NETWORK_CONNECTED = NLM_ENUM_NETWORK.CONNECTED;
pub const NLM_ENUM_NETWORK_DISCONNECTED = NLM_ENUM_NETWORK.DISCONNECTED;
pub const NLM_ENUM_NETWORK_ALL = NLM_ENUM_NETWORK.ALL;
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_INetworkListManager_Value = Guid.initString("dcb00000-570f-4a9b-8d69-199fdba5723b");
pub const IID_INetworkListManager = &IID_INetworkListManager_Value;
pub const INetworkListManager = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
GetNetworks: fn(
self: *const INetworkListManager,
Flags: NLM_ENUM_NETWORK,
ppEnumNetwork: ?*?*IEnumNetworks,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNetwork: fn(
self: *const INetworkListManager,
gdNetworkId: Guid,
ppNetwork: ?*?*INetwork,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNetworkConnections: fn(
self: *const INetworkListManager,
ppEnum: ?*?*IEnumNetworkConnections,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNetworkConnection: fn(
self: *const INetworkListManager,
gdNetworkConnectionId: Guid,
ppNetworkConnection: ?*?*INetworkConnection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_IsConnectedToInternet: fn(
self: *const INetworkListManager,
pbIsConnected: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_IsConnected: fn(
self: *const INetworkListManager,
pbIsConnected: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetConnectivity: fn(
self: *const INetworkListManager,
pConnectivity: ?*NLM_CONNECTIVITY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetSimulatedProfileInfo: fn(
self: *const INetworkListManager,
pSimulatedInfo: ?*NLM_SIMULATED_PROFILE_INFO,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ClearSimulatedProfileInfo: fn(
self: *const INetworkListManager,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkListManager_GetNetworks(self: *const T, Flags: NLM_ENUM_NETWORK, ppEnumNetwork: ?*?*IEnumNetworks) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkListManager.VTable, self.vtable).GetNetworks(@ptrCast(*const INetworkListManager, self), Flags, ppEnumNetwork);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkListManager_GetNetwork(self: *const T, gdNetworkId: Guid, ppNetwork: ?*?*INetwork) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkListManager.VTable, self.vtable).GetNetwork(@ptrCast(*const INetworkListManager, self), gdNetworkId, ppNetwork);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkListManager_GetNetworkConnections(self: *const T, ppEnum: ?*?*IEnumNetworkConnections) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkListManager.VTable, self.vtable).GetNetworkConnections(@ptrCast(*const INetworkListManager, self), ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkListManager_GetNetworkConnection(self: *const T, gdNetworkConnectionId: Guid, ppNetworkConnection: ?*?*INetworkConnection) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkListManager.VTable, self.vtable).GetNetworkConnection(@ptrCast(*const INetworkListManager, self), gdNetworkConnectionId, ppNetworkConnection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkListManager_get_IsConnectedToInternet(self: *const T, pbIsConnected: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkListManager.VTable, self.vtable).get_IsConnectedToInternet(@ptrCast(*const INetworkListManager, self), pbIsConnected);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkListManager_get_IsConnected(self: *const T, pbIsConnected: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkListManager.VTable, self.vtable).get_IsConnected(@ptrCast(*const INetworkListManager, self), pbIsConnected);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkListManager_GetConnectivity(self: *const T, pConnectivity: ?*NLM_CONNECTIVITY) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkListManager.VTable, self.vtable).GetConnectivity(@ptrCast(*const INetworkListManager, self), pConnectivity);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkListManager_SetSimulatedProfileInfo(self: *const T, pSimulatedInfo: ?*NLM_SIMULATED_PROFILE_INFO) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkListManager.VTable, self.vtable).SetSimulatedProfileInfo(@ptrCast(*const INetworkListManager, self), pSimulatedInfo);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkListManager_ClearSimulatedProfileInfo(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkListManager.VTable, self.vtable).ClearSimulatedProfileInfo(@ptrCast(*const INetworkListManager, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_INetworkListManagerEvents_Value = Guid.initString("dcb00001-570f-4a9b-8d69-199fdba5723b");
pub const IID_INetworkListManagerEvents = &IID_INetworkListManagerEvents_Value;
pub const INetworkListManagerEvents = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
ConnectivityChanged: fn(
self: *const INetworkListManagerEvents,
newConnectivity: NLM_CONNECTIVITY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkListManagerEvents_ConnectivityChanged(self: *const T, newConnectivity: NLM_CONNECTIVITY) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkListManagerEvents.VTable, self.vtable).ConnectivityChanged(@ptrCast(*const INetworkListManagerEvents, self), newConnectivity);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const NLM_NETWORK_CATEGORY = enum(i32) {
PUBLIC = 0,
PRIVATE = 1,
DOMAIN_AUTHENTICATED = 2,
};
pub const NLM_NETWORK_CATEGORY_PUBLIC = NLM_NETWORK_CATEGORY.PUBLIC;
pub const NLM_NETWORK_CATEGORY_PRIVATE = NLM_NETWORK_CATEGORY.PRIVATE;
pub const NLM_NETWORK_CATEGORY_DOMAIN_AUTHENTICATED = NLM_NETWORK_CATEGORY.DOMAIN_AUTHENTICATED;
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_INetwork_Value = Guid.initString("dcb00002-570f-4a9b-8d69-199fdba5723b");
pub const IID_INetwork = &IID_INetwork_Value;
pub const INetwork = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
GetName: fn(
self: *const INetwork,
pszNetworkName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetName: fn(
self: *const INetwork,
szNetworkNewName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDescription: fn(
self: *const INetwork,
pszDescription: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetDescription: fn(
self: *const INetwork,
szDescription: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNetworkId: fn(
self: *const INetwork,
pgdGuidNetworkId: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDomainType: fn(
self: *const INetwork,
pNetworkType: ?*NLM_DOMAIN_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNetworkConnections: fn(
self: *const INetwork,
ppEnumNetworkConnection: ?*?*IEnumNetworkConnections,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTimeCreatedAndConnected: fn(
self: *const INetwork,
pdwLowDateTimeCreated: ?*u32,
pdwHighDateTimeCreated: ?*u32,
pdwLowDateTimeConnected: ?*u32,
pdwHighDateTimeConnected: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_IsConnectedToInternet: fn(
self: *const INetwork,
pbIsConnected: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_IsConnected: fn(
self: *const INetwork,
pbIsConnected: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetConnectivity: fn(
self: *const INetwork,
pConnectivity: ?*NLM_CONNECTIVITY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCategory: fn(
self: *const INetwork,
pCategory: ?*NLM_NETWORK_CATEGORY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCategory: fn(
self: *const INetwork,
NewCategory: NLM_NETWORK_CATEGORY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetwork_GetName(self: *const T, pszNetworkName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const INetwork.VTable, self.vtable).GetName(@ptrCast(*const INetwork, self), pszNetworkName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetwork_SetName(self: *const T, szNetworkNewName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const INetwork.VTable, self.vtable).SetName(@ptrCast(*const INetwork, self), szNetworkNewName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetwork_GetDescription(self: *const T, pszDescription: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const INetwork.VTable, self.vtable).GetDescription(@ptrCast(*const INetwork, self), pszDescription);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetwork_SetDescription(self: *const T, szDescription: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const INetwork.VTable, self.vtable).SetDescription(@ptrCast(*const INetwork, self), szDescription);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetwork_GetNetworkId(self: *const T, pgdGuidNetworkId: ?*Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const INetwork.VTable, self.vtable).GetNetworkId(@ptrCast(*const INetwork, self), pgdGuidNetworkId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetwork_GetDomainType(self: *const T, pNetworkType: ?*NLM_DOMAIN_TYPE) callconv(.Inline) HRESULT {
return @ptrCast(*const INetwork.VTable, self.vtable).GetDomainType(@ptrCast(*const INetwork, self), pNetworkType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetwork_GetNetworkConnections(self: *const T, ppEnumNetworkConnection: ?*?*IEnumNetworkConnections) callconv(.Inline) HRESULT {
return @ptrCast(*const INetwork.VTable, self.vtable).GetNetworkConnections(@ptrCast(*const INetwork, self), ppEnumNetworkConnection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetwork_GetTimeCreatedAndConnected(self: *const T, pdwLowDateTimeCreated: ?*u32, pdwHighDateTimeCreated: ?*u32, pdwLowDateTimeConnected: ?*u32, pdwHighDateTimeConnected: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const INetwork.VTable, self.vtable).GetTimeCreatedAndConnected(@ptrCast(*const INetwork, self), pdwLowDateTimeCreated, pdwHighDateTimeCreated, pdwLowDateTimeConnected, pdwHighDateTimeConnected);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetwork_get_IsConnectedToInternet(self: *const T, pbIsConnected: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const INetwork.VTable, self.vtable).get_IsConnectedToInternet(@ptrCast(*const INetwork, self), pbIsConnected);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetwork_get_IsConnected(self: *const T, pbIsConnected: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const INetwork.VTable, self.vtable).get_IsConnected(@ptrCast(*const INetwork, self), pbIsConnected);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetwork_GetConnectivity(self: *const T, pConnectivity: ?*NLM_CONNECTIVITY) callconv(.Inline) HRESULT {
return @ptrCast(*const INetwork.VTable, self.vtable).GetConnectivity(@ptrCast(*const INetwork, self), pConnectivity);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetwork_GetCategory(self: *const T, pCategory: ?*NLM_NETWORK_CATEGORY) callconv(.Inline) HRESULT {
return @ptrCast(*const INetwork.VTable, self.vtable).GetCategory(@ptrCast(*const INetwork, self), pCategory);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetwork_SetCategory(self: *const T, NewCategory: NLM_NETWORK_CATEGORY) callconv(.Inline) HRESULT {
return @ptrCast(*const INetwork.VTable, self.vtable).SetCategory(@ptrCast(*const INetwork, self), NewCategory);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IEnumNetworks_Value = Guid.initString("dcb00003-570f-4a9b-8d69-199fdba5723b");
pub const IID_IEnumNetworks = &IID_IEnumNetworks_Value;
pub const IEnumNetworks = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get__NewEnum: fn(
self: *const IEnumNetworks,
ppEnumVar: ?*?*IEnumVARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Next: fn(
self: *const IEnumNetworks,
celt: u32,
rgelt: [*]?*INetwork,
pceltFetched: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Skip: fn(
self: *const IEnumNetworks,
celt: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const IEnumNetworks,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clone: fn(
self: *const IEnumNetworks,
ppEnumNetwork: ?*?*IEnumNetworks,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumNetworks_get__NewEnum(self: *const T, ppEnumVar: ?*?*IEnumVARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumNetworks.VTable, self.vtable).get__NewEnum(@ptrCast(*const IEnumNetworks, self), ppEnumVar);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumNetworks_Next(self: *const T, celt: u32, rgelt: [*]?*INetwork, pceltFetched: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumNetworks.VTable, self.vtable).Next(@ptrCast(*const IEnumNetworks, self), celt, rgelt, pceltFetched);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumNetworks_Skip(self: *const T, celt: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumNetworks.VTable, self.vtable).Skip(@ptrCast(*const IEnumNetworks, self), celt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumNetworks_Reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumNetworks.VTable, self.vtable).Reset(@ptrCast(*const IEnumNetworks, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumNetworks_Clone(self: *const T, ppEnumNetwork: ?*?*IEnumNetworks) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumNetworks.VTable, self.vtable).Clone(@ptrCast(*const IEnumNetworks, self), ppEnumNetwork);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const NLM_NETWORK_PROPERTY_CHANGE = enum(i32) {
CONNECTION = 1,
DESCRIPTION = 2,
NAME = 4,
ICON = 8,
CATEGORY_VALUE = 16,
};
pub const NLM_NETWORK_PROPERTY_CHANGE_CONNECTION = NLM_NETWORK_PROPERTY_CHANGE.CONNECTION;
pub const NLM_NETWORK_PROPERTY_CHANGE_DESCRIPTION = NLM_NETWORK_PROPERTY_CHANGE.DESCRIPTION;
pub const NLM_NETWORK_PROPERTY_CHANGE_NAME = NLM_NETWORK_PROPERTY_CHANGE.NAME;
pub const NLM_NETWORK_PROPERTY_CHANGE_ICON = NLM_NETWORK_PROPERTY_CHANGE.ICON;
pub const NLM_NETWORK_PROPERTY_CHANGE_CATEGORY_VALUE = NLM_NETWORK_PROPERTY_CHANGE.CATEGORY_VALUE;
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_INetworkEvents_Value = Guid.initString("dcb00004-570f-4a9b-8d69-199fdba5723b");
pub const IID_INetworkEvents = &IID_INetworkEvents_Value;
pub const INetworkEvents = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
NetworkAdded: fn(
self: *const INetworkEvents,
networkId: Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
NetworkDeleted: fn(
self: *const INetworkEvents,
networkId: Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
NetworkConnectivityChanged: fn(
self: *const INetworkEvents,
networkId: Guid,
newConnectivity: NLM_CONNECTIVITY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
NetworkPropertyChanged: fn(
self: *const INetworkEvents,
networkId: Guid,
flags: NLM_NETWORK_PROPERTY_CHANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkEvents_NetworkAdded(self: *const T, networkId: Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkEvents.VTable, self.vtable).NetworkAdded(@ptrCast(*const INetworkEvents, self), networkId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkEvents_NetworkDeleted(self: *const T, networkId: Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkEvents.VTable, self.vtable).NetworkDeleted(@ptrCast(*const INetworkEvents, self), networkId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkEvents_NetworkConnectivityChanged(self: *const T, networkId: Guid, newConnectivity: NLM_CONNECTIVITY) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkEvents.VTable, self.vtable).NetworkConnectivityChanged(@ptrCast(*const INetworkEvents, self), networkId, newConnectivity);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkEvents_NetworkPropertyChanged(self: *const T, networkId: Guid, flags: NLM_NETWORK_PROPERTY_CHANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkEvents.VTable, self.vtable).NetworkPropertyChanged(@ptrCast(*const INetworkEvents, self), networkId, flags);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_INetworkConnection_Value = Guid.initString("dcb00005-570f-4a9b-8d69-199fdba5723b");
pub const IID_INetworkConnection = &IID_INetworkConnection_Value;
pub const INetworkConnection = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
GetNetwork: fn(
self: *const INetworkConnection,
ppNetwork: ?*?*INetwork,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_IsConnectedToInternet: fn(
self: *const INetworkConnection,
pbIsConnected: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_IsConnected: fn(
self: *const INetworkConnection,
pbIsConnected: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetConnectivity: fn(
self: *const INetworkConnection,
pConnectivity: ?*NLM_CONNECTIVITY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetConnectionId: fn(
self: *const INetworkConnection,
pgdConnectionId: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAdapterId: fn(
self: *const INetworkConnection,
pgdAdapterId: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDomainType: fn(
self: *const INetworkConnection,
pDomainType: ?*NLM_DOMAIN_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkConnection_GetNetwork(self: *const T, ppNetwork: ?*?*INetwork) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkConnection.VTable, self.vtable).GetNetwork(@ptrCast(*const INetworkConnection, self), ppNetwork);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkConnection_get_IsConnectedToInternet(self: *const T, pbIsConnected: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkConnection.VTable, self.vtable).get_IsConnectedToInternet(@ptrCast(*const INetworkConnection, self), pbIsConnected);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkConnection_get_IsConnected(self: *const T, pbIsConnected: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkConnection.VTable, self.vtable).get_IsConnected(@ptrCast(*const INetworkConnection, self), pbIsConnected);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkConnection_GetConnectivity(self: *const T, pConnectivity: ?*NLM_CONNECTIVITY) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkConnection.VTable, self.vtable).GetConnectivity(@ptrCast(*const INetworkConnection, self), pConnectivity);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkConnection_GetConnectionId(self: *const T, pgdConnectionId: ?*Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkConnection.VTable, self.vtable).GetConnectionId(@ptrCast(*const INetworkConnection, self), pgdConnectionId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkConnection_GetAdapterId(self: *const T, pgdAdapterId: ?*Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkConnection.VTable, self.vtable).GetAdapterId(@ptrCast(*const INetworkConnection, self), pgdAdapterId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkConnection_GetDomainType(self: *const T, pDomainType: ?*NLM_DOMAIN_TYPE) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkConnection.VTable, self.vtable).GetDomainType(@ptrCast(*const INetworkConnection, self), pDomainType);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IEnumNetworkConnections_Value = Guid.initString("dcb00006-570f-4a9b-8d69-199fdba5723b");
pub const IID_IEnumNetworkConnections = &IID_IEnumNetworkConnections_Value;
pub const IEnumNetworkConnections = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get__NewEnum: fn(
self: *const IEnumNetworkConnections,
ppEnumVar: ?*?*IEnumVARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Next: fn(
self: *const IEnumNetworkConnections,
celt: u32,
rgelt: [*]?*INetworkConnection,
pceltFetched: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Skip: fn(
self: *const IEnumNetworkConnections,
celt: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const IEnumNetworkConnections,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clone: fn(
self: *const IEnumNetworkConnections,
ppEnumNetwork: ?*?*IEnumNetworkConnections,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumNetworkConnections_get__NewEnum(self: *const T, ppEnumVar: ?*?*IEnumVARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumNetworkConnections.VTable, self.vtable).get__NewEnum(@ptrCast(*const IEnumNetworkConnections, self), ppEnumVar);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumNetworkConnections_Next(self: *const T, celt: u32, rgelt: [*]?*INetworkConnection, pceltFetched: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumNetworkConnections.VTable, self.vtable).Next(@ptrCast(*const IEnumNetworkConnections, self), celt, rgelt, pceltFetched);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumNetworkConnections_Skip(self: *const T, celt: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumNetworkConnections.VTable, self.vtable).Skip(@ptrCast(*const IEnumNetworkConnections, self), celt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumNetworkConnections_Reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumNetworkConnections.VTable, self.vtable).Reset(@ptrCast(*const IEnumNetworkConnections, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumNetworkConnections_Clone(self: *const T, ppEnumNetwork: ?*?*IEnumNetworkConnections) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumNetworkConnections.VTable, self.vtable).Clone(@ptrCast(*const IEnumNetworkConnections, self), ppEnumNetwork);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const NLM_CONNECTION_PROPERTY_CHANGE = enum(i32) {
N = 1,
};
pub const NLM_CONNECTION_PROPERTY_CHANGE_AUTHENTICATION = NLM_CONNECTION_PROPERTY_CHANGE.N;
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_INetworkConnectionEvents_Value = Guid.initString("dcb00007-570f-4a9b-8d69-199fdba5723b");
pub const IID_INetworkConnectionEvents = &IID_INetworkConnectionEvents_Value;
pub const INetworkConnectionEvents = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
NetworkConnectionConnectivityChanged: fn(
self: *const INetworkConnectionEvents,
connectionId: Guid,
newConnectivity: NLM_CONNECTIVITY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
NetworkConnectionPropertyChanged: fn(
self: *const INetworkConnectionEvents,
connectionId: Guid,
flags: NLM_CONNECTION_PROPERTY_CHANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkConnectionEvents_NetworkConnectionConnectivityChanged(self: *const T, connectionId: Guid, newConnectivity: NLM_CONNECTIVITY) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkConnectionEvents.VTable, self.vtable).NetworkConnectionConnectivityChanged(@ptrCast(*const INetworkConnectionEvents, self), connectionId, newConnectivity);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkConnectionEvents_NetworkConnectionPropertyChanged(self: *const T, connectionId: Guid, flags: NLM_CONNECTION_PROPERTY_CHANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkConnectionEvents.VTable, self.vtable).NetworkConnectionPropertyChanged(@ptrCast(*const INetworkConnectionEvents, self), connectionId, flags);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_INetworkCostManager_Value = Guid.initString("dcb00008-570f-4a9b-8d69-199fdba5723b");
pub const IID_INetworkCostManager = &IID_INetworkCostManager_Value;
pub const INetworkCostManager = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetCost: fn(
self: *const INetworkCostManager,
pCost: ?*u32,
pDestIPAddr: ?*NLM_SOCKADDR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDataPlanStatus: fn(
self: *const INetworkCostManager,
pDataPlanStatus: ?*NLM_DATAPLAN_STATUS,
pDestIPAddr: ?*NLM_SOCKADDR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetDestinationAddresses: fn(
self: *const INetworkCostManager,
length: u32,
pDestIPAddrList: [*]NLM_SOCKADDR,
bAppend: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkCostManager_GetCost(self: *const T, pCost: ?*u32, pDestIPAddr: ?*NLM_SOCKADDR) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkCostManager.VTable, self.vtable).GetCost(@ptrCast(*const INetworkCostManager, self), pCost, pDestIPAddr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkCostManager_GetDataPlanStatus(self: *const T, pDataPlanStatus: ?*NLM_DATAPLAN_STATUS, pDestIPAddr: ?*NLM_SOCKADDR) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkCostManager.VTable, self.vtable).GetDataPlanStatus(@ptrCast(*const INetworkCostManager, self), pDataPlanStatus, pDestIPAddr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkCostManager_SetDestinationAddresses(self: *const T, length: u32, pDestIPAddrList: [*]NLM_SOCKADDR, bAppend: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkCostManager.VTable, self.vtable).SetDestinationAddresses(@ptrCast(*const INetworkCostManager, self), length, pDestIPAddrList, bAppend);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_INetworkCostManagerEvents_Value = Guid.initString("dcb00009-570f-4a9b-8d69-199fdba5723b");
pub const IID_INetworkCostManagerEvents = &IID_INetworkCostManagerEvents_Value;
pub const INetworkCostManagerEvents = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CostChanged: fn(
self: *const INetworkCostManagerEvents,
newCost: u32,
pDestAddr: ?*NLM_SOCKADDR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DataPlanStatusChanged: fn(
self: *const INetworkCostManagerEvents,
pDestAddr: ?*NLM_SOCKADDR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkCostManagerEvents_CostChanged(self: *const T, newCost: u32, pDestAddr: ?*NLM_SOCKADDR) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkCostManagerEvents.VTable, self.vtable).CostChanged(@ptrCast(*const INetworkCostManagerEvents, self), newCost, pDestAddr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkCostManagerEvents_DataPlanStatusChanged(self: *const T, pDestAddr: ?*NLM_SOCKADDR) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkCostManagerEvents.VTable, self.vtable).DataPlanStatusChanged(@ptrCast(*const INetworkCostManagerEvents, self), pDestAddr);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_INetworkConnectionCost_Value = Guid.initString("dcb0000a-570f-4a9b-8d69-199fdba5723b");
pub const IID_INetworkConnectionCost = &IID_INetworkConnectionCost_Value;
pub const INetworkConnectionCost = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetCost: fn(
self: *const INetworkConnectionCost,
pCost: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDataPlanStatus: fn(
self: *const INetworkConnectionCost,
pDataPlanStatus: ?*NLM_DATAPLAN_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkConnectionCost_GetCost(self: *const T, pCost: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkConnectionCost.VTable, self.vtable).GetCost(@ptrCast(*const INetworkConnectionCost, self), pCost);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkConnectionCost_GetDataPlanStatus(self: *const T, pDataPlanStatus: ?*NLM_DATAPLAN_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkConnectionCost.VTable, self.vtable).GetDataPlanStatus(@ptrCast(*const INetworkConnectionCost, self), pDataPlanStatus);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_INetworkConnectionCostEvents_Value = Guid.initString("dcb0000b-570f-4a9b-8d69-199fdba5723b");
pub const IID_INetworkConnectionCostEvents = &IID_INetworkConnectionCostEvents_Value;
pub const INetworkConnectionCostEvents = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
ConnectionCostChanged: fn(
self: *const INetworkConnectionCostEvents,
connectionId: Guid,
newCost: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ConnectionDataPlanStatusChanged: fn(
self: *const INetworkConnectionCostEvents,
connectionId: Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkConnectionCostEvents_ConnectionCostChanged(self: *const T, connectionId: Guid, newCost: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkConnectionCostEvents.VTable, self.vtable).ConnectionCostChanged(@ptrCast(*const INetworkConnectionCostEvents, self), connectionId, newCost);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkConnectionCostEvents_ConnectionDataPlanStatusChanged(self: *const T, connectionId: Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkConnectionCostEvents.VTable, self.vtable).ConnectionDataPlanStatusChanged(@ptrCast(*const INetworkConnectionCostEvents, self), connectionId);
}
};}
pub usingnamespace MethodMixin(@This());
};
//--------------------------------------------------------------------------------
// Section: Functions (0)
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (0)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
},
.wide => struct {
},
.unspecified => if (@import("builtin").is_test) struct {
} else struct {
},
};
//--------------------------------------------------------------------------------
// Section: Imports (7)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BSTR = @import("../foundation.zig").BSTR;
const FILETIME = @import("../foundation.zig").FILETIME;
const HRESULT = @import("../foundation.zig").HRESULT;
const IDispatch = @import("../system/com.zig").IDispatch;
const IEnumVARIANT = @import("../system/ole.zig").IEnumVARIANT;
const IUnknown = @import("../system/com.zig").IUnknown;
test {
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
} | win32/networking/network_list_manager.zig |
const std = @import("std");
const zzz = @import("zzz");
const version = @import("version");
const Package = @import("Package.zig");
const Dependency = @import("Dependency.zig");
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
usingnamespace @import("common.zig");
const Self = @This();
allocator: *Allocator,
text: []const u8,
packages: std.StringHashMap(Package),
deps: std.ArrayList(Dependency),
build_deps: std.ArrayList(Dependency),
pub const Iterator = struct {
inner: std.StringHashMap(Package).Iterator,
pub fn next(self: *Iterator) ?*Package {
return if (self.inner.next()) |entry| &entry.value_ptr.* else null;
}
};
fn init(allocator: *Allocator, file: std.fs.File) !Self {
return Self{
.allocator = allocator,
.text = try file.readToEndAlloc(allocator, std.math.maxInt(usize)),
.packages = std.StringHashMap(Package).init(allocator),
.deps = std.ArrayList(Dependency).init(allocator),
.build_deps = std.ArrayList(Dependency).init(allocator),
};
}
fn deinit(self: *Self) void {
var it = self.packages.iterator();
while (it.next()) |entry| {
entry.value_ptr.deinit();
_ = self.packages.remove(entry.key_ptr.*);
}
self.deps.deinit();
self.build_deps.deinit();
self.packages.deinit();
self.allocator.free(self.text);
}
pub fn destroy(self: *Self) void {
self.deinit();
self.allocator.destroy(self);
}
pub fn contains(self: Self, name: []const u8) bool {
return self.packages.contains(name);
}
pub fn get(self: Self, name: []const u8) ?*Package {
return if (self.packages.getEntry(name)) |entry| &entry.value_ptr.* else null;
}
pub fn iterator(self: Self) Iterator {
return Iterator{ .inner = self.packages.iterator() };
}
pub fn fromText(allocator: *Allocator, text: []const u8) !*Self {
var ret = try allocator.create(Self);
ret.* = Self{
.allocator = allocator,
.text = text,
.packages = std.StringHashMap(Package).init(allocator),
.deps = std.ArrayList(Dependency).init(allocator),
.build_deps = std.ArrayList(Dependency).init(allocator),
};
errdefer {
ret.deinit();
allocator.destroy(ret);
}
if (std.mem.indexOf(u8, ret.text, "\r\n") != null) {
std.log.err("gyro.zzz requires LF line endings, not CRLF", .{});
return error.Explained;
}
var tree = zzz.ZTree(1, 1000){};
var root = try tree.appendText(ret.text);
if (zFindChild(root, "pkgs")) |pkgs| {
var it = ZChildIterator.init(pkgs);
while (it.next()) |node| {
const name = try zGetString(node);
const ver_str = (try zFindString(node, "version")) orelse {
std.log.err("missing version string in package", .{});
return error.Explained;
};
const ver = version.Semver.parse(allocator, ver_str) catch |err| {
std.log.err("failed to parse version string '{s}', must be <major>.<minor>.<patch>: {}", .{ ver_str, err });
return error.Explained;
};
const res = try ret.packages.getOrPut(name);
if (res.found_existing) {
std.log.err("duplicate exported packages {s}", .{name});
return error.Explained;
}
res.value_ptr.* = try Package.init(
allocator,
name,
ver,
ret,
ret.build_deps.items,
);
try res.value_ptr.fillFromZNode(node);
}
}
if (zFindChild(root, "deps")) |deps| {
var it = ZChildIterator.init(deps);
while (it.next()) |dep_node| {
const dep = try Dependency.fromZNode(allocator, dep_node);
for (ret.deps.items) |other| {
if (std.mem.eql(u8, dep.alias, other.alias)) {
std.log.err("'{s}' alias in 'deps' is declared multiple times", .{dep.alias});
return error.Explained;
}
} else {
try ret.deps.append(dep);
}
}
}
if (zFindChild(root, "build_deps")) |build_deps| {
var it = ZChildIterator.init(build_deps);
while (it.next()) |dep_node| {
const dep = try Dependency.fromZNode(allocator, dep_node);
for (ret.build_deps.items) |other| {
if (std.mem.eql(u8, dep.alias, other.alias)) {
std.log.err("'{s}' alias in 'build_deps' is declared multiple times", .{dep.alias});
return error.Explained;
}
} else {
try ret.build_deps.append(dep);
}
}
}
return ret;
}
pub fn fromFile(allocator: *Allocator, file: std.fs.File) !*Self {
return fromText(allocator, try file.reader().readAllAlloc(allocator, std.math.maxInt(usize)));
}
pub fn toFile(self: *Self, file: std.fs.File) !void {
var tree = zzz.ZTree(1, 1000){};
var root = try tree.addNode(null, .Null);
var arena = ArenaAllocator.init(self.allocator);
defer arena.deinit();
try file.setEndPos(0);
try file.seekTo(0);
if (self.packages.count() > 0) {
var pkgs = try tree.addNode(root, .{ .String = "pkgs" });
var it = self.packages.iterator();
while (it.next()) |entry| _ = try entry.value_ptr.addToZNode(&arena, &tree, pkgs, false);
}
if (self.deps.items.len > 0) {
var deps = try tree.addNode(root, .{ .String = "deps" });
for (self.deps.items) |dep| try dep.addToZNode(&arena, &tree, deps, false);
}
if (self.build_deps.items.len > 0) {
var build_deps = try tree.addNode(root, .{ .String = "build_deps" });
for (self.build_deps.items) |dep| try dep.addToZNode(&arena, &tree, build_deps, false);
}
try root.stringifyPretty(file.writer());
} | src/Project.zig |
const std = @import("std");
const mdct = @import("mdct.zig");
fn bench() !void {
var timer = try std.time.Timer.start();
var n: usize = 0;
while (n < 1) : (n += 1) {
const data_1 = [_]f32{ 0, 0, 1, 2 };
const processed_1 = [_]f32{ mdct.mdct(f32, &data_1, 0), mdct.mdct(f32, &data_1, 1) };
const de_1 = [_]f32{ mdct.imdct(f32, &processed_1, 0), mdct.imdct(f32, &processed_1, 1), mdct.imdct(f32, &processed_1, 2), mdct.imdct(f32, &processed_1, 3) };
const data_2 = [_]f32{ 1, 2, 3, 4 };
const processed_2 = [_]f32{ mdct.mdct(f32, &data_2, 0), mdct.mdct(f32, &data_2, 1) };
const de_2 = [_]f32{ mdct.imdct(f32, &processed_2, 0), mdct.imdct(f32, &processed_2, 1), mdct.imdct(f32, &processed_2, 2), mdct.imdct(f32, &processed_2, 3) };
// std.log.info("{d}", .{de_1});
std.log.info("{d} {d}", .{ processed_2, mdct.imdct(f32, &processed_2, 0) });
std.mem.doNotOptimizeAway(de_1);
std.mem.doNotOptimizeAway(de_2);
}
std.log.err("{d}ms", .{@intToFloat(f32, timer.read()) / @intToFloat(f32, std.time.ns_per_ms)});
}
pub fn main() !void {
try bench();
const block_size: usize = 4;
// NOTE: Pad data with block_size/2 0s at the start and end
const data = [_]f32{ 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 0 };
var out: [mdct.calcBlockMdctOutputSize(block_size, data.len)]f32 = undefined;
var outout: [mdct.calcBlockMdctOutputSize(block_size, out.len)]f32 = undefined;
mdct.naiveBlockMdct(f32, block_size, &data, &out);
mdct.naiveBlockImdct(f32, block_size, &out, &outout);
// var i: usize = 0;
// var block: usize = 0;
// while (block <= out.len / (block_size / 2) - (block_size / 2)) : (block += 1) {
// var s: usize = 0;
// while (s < block_size / 2) : (s += 1) {
// outout[i] = mdct.imdct(f32, out[(block_size / 2) * block .. (block_size / 2) * (block + 1)], block_size / 2 + s) + mdct.imdct(f32, out[(block_size / 2) * (block + 1) .. (block_size / 2) * (block + 2)], s);
// i += 1;
// }
// }
// std.log.info("{d} {d}", .{ mdct.mdct(f32, data[0..4], 0), mdct.mdct(f32, data[0..4], 1) });
// std.log.info("{d} {d}", .{ mdct.mdct(f32, data[2..6], 0), mdct.mdct(f32, data[2..6], 1) });
std.log.info("{d}", .{outout});
// const z = [_]f32{ out[2], out[3] };
// std.log.info("{d}", .{mdct.imdct(f32, out[2..4], 2) + mdct.imdct(f32, out[4..6], 0)});
// std.log.info("{d} {d}", .{ de_1[2] + de_2[0], de_1[3] + de_2[1] });
} | src/main.zig |
const wlr = @import("wlroots.zig");
const os = @import("std").os;
const wayland = @import("wayland");
const wl = wayland.server.wl;
// Only bind enough to make binding wlr/xwayland.h possible
// Consider full xcb bindings in the future if needed
const xcb = struct {
const GenericEvent = opaque {};
const Pixmap = u32;
const Window = u32;
const Atom = u32;
};
pub const Xwm = opaque {};
pub const XwaylandCursor = opaque {};
pub const XwaylandServer = extern struct {
pub const Options = extern struct {
lazy: bool,
enable_wm: bool,
};
pub const event = struct {
pub const Ready = extern struct {
server: *XwaylandServer,
wm_fd: c_int,
};
};
pid: os.pid_t,
client: ?*wl.Client,
sigusr1_source: ?*wl.EventSource,
wm_fd: [2]c_int,
wl_fd: [2]c_int,
server_start: os.time_t,
display: c_int,
display_name: [16]u8,
x_fd: [2]c_int,
x_fd_read_event: [2]?*wl.EventSource,
lazy: bool,
enable_wm: bool,
wl_server: *wl.Server,
events: extern struct {
ready: wl.Signal(*event.Ready),
destroy: wl.Signal(void),
},
client_destroy: wl.Listener(*wl.Client),
display_destroy: wl.Listener(*wl.Server),
data: usize,
extern fn wlr_xwayland_server_create(wl_server: *wl.Server, options: *Options) ?*XwaylandServer;
pub const create = wlr_xwayland_server_create;
extern fn wlr_xwayland_server_destroy(server: *XwaylandServer) void;
pub const destroy = wlr_xwayland_server_destroy;
};
pub const Xwayland = extern struct {
server: *XwaylandServer,
xwm: ?*Xwm,
cursor: ?*XwaylandCursor,
display_name: [*:0]const u8,
wl_server: *wl.Server,
compositor: *wlr.Compositor,
seat: ?*wlr.Seat,
events: extern struct {
ready: wl.Signal(void),
new_surface: wl.Signal(*XwaylandSurface),
},
user_event_handler: ?fn (*Xwm, *xcb.GenericEvent) callconv(.C) c_int,
server_ready: wl.Listener(*XwaylandServer.event.Ready),
server_destroy: wl.Listener(void),
seat_destroy: wl.Listener(*wlr.Seat),
data: usize,
extern fn wlr_xwayland_create(wl_server: *wl.Server, compositor: *wlr.Compositor, lazy: bool) ?*Xwayland;
pub const create = wlr_xwayland_create;
extern fn wlr_xwayland_destroy(wlr_xwayland: *Xwayland) void;
pub const destroy = wlr_xwayland_destroy;
extern fn wlr_xwayland_set_cursor(wlr_xwayland: *Xwayland, pixels: [*]u8, stride: u32, width: u32, height: u32, hotspot_x: i32, hotspot_y: i32) void;
pub const setCursor = wlr_xwayland_set_cursor;
extern fn wlr_xwayland_set_seat(xwayland: *Xwayland, seat: *wlr.Seat) void;
pub const setSeat = wlr_xwayland_set_seat;
};
pub const XwaylandSurface = extern struct {
/// Bitfield with the size/alignment of a u32
pub const Decorations = packed struct {
no_border: bool align(@alignOf(u32)) = false,
no_title: bool = false,
_: u30 = 0,
};
pub const Hints = extern struct {
flags: u32,
input: u32,
initial_state: i32,
icon_pixmap: xcb.Pixmap,
icon_window: xcb.Window,
icon_x: i32,
icon_y: i32,
icon_mask: xcb.Pixmap,
window_group: xcb.Window,
};
pub const SizeHints = extern struct {
flags: u32,
x: i32,
y: i32,
width: i32,
height: i32,
min_width: i32,
min_height: i32,
max_width: i32,
max_height: i32,
width_inc: i32,
height_inc: i32,
base_width: i32,
base_height: i32,
min_aspect_num: i32,
min_aspect_den: i32,
max_aspect_num: i32,
max_aspect_den: i32,
win_gravity: u32,
};
pub const event = struct {
pub const Configure = extern struct {
surface: *XwaylandSurface,
x: i16,
y: i16,
width: u16,
height: u16,
mask: u16,
};
pub const Move = extern struct {
surface: *XwaylandSurface,
};
pub const Resize = extern struct {
surface: *XwaylandSurface,
edges: u32,
};
pub const Minimize = extern struct {
surface: *XwaylandSurface,
minimize: bool,
};
};
window_id: xcb.Window,
xwm: *Xwm,
surface_id: u32,
link: wl.list.Link,
unpaired_link: wl.list.Link,
surface: ?*wlr.Surface,
x: i16,
y: i16,
width: u16,
height: u16,
saved_width: u16,
saved_height: u16,
override_redirect: bool,
mapped: bool,
title: [*:0]u8,
class: [*:0]u8,
instance: [*:0]u8,
role: [*:0]u8,
pid: os.pid_t,
has_utf8_title: bool,
children: wl.list.Head(XwaylandSurface, "parent_link"),
parent: ?*XwaylandSurface,
/// XwaylandSurface.children
parent_link: wl.list.Link,
window_type: ?[*]xcb.Atom,
window_type_len: usize,
protocols: ?[*]xcb.Atom,
protocols_len: usize,
decorations: Decorations,
hints: ?*Hints,
hints_urgency: u32,
size_hints: ?*SizeHints,
pinging: bool,
ping_timer: *wl.EventSource,
modal: bool,
fullscreen: bool,
maximized_vert: bool,
maximized_horz: bool,
minimized: bool,
has_alpha: bool,
events: extern struct {
destroy: wl.Signal(*XwaylandSurface),
request_configure: wl.Signal(*event.Configure),
request_move: wl.Signal(*event.Move),
request_resize: wl.Signal(*event.Resize),
request_minimize: wl.Signal(*event.Minimize),
request_maximize: wl.Signal(*XwaylandSurface),
request_fullscreen: wl.Signal(*XwaylandSurface),
request_activate: wl.Signal(*XwaylandSurface),
map: wl.Signal(*XwaylandSurface),
unmap: wl.Signal(*XwaylandSurface),
set_title: wl.Signal(*XwaylandSurface),
set_class: wl.Signal(*XwaylandSurface),
set_role: wl.Signal(*XwaylandSurface),
set_parent: wl.Signal(*XwaylandSurface),
set_pid: wl.Signal(*XwaylandSurface),
set_window_type: wl.Signal(*XwaylandSurface),
set_hints: wl.Signal(*XwaylandSurface),
set_decorations: wl.Signal(*XwaylandSurface),
set_override_redirect: wl.Signal(*XwaylandSurface),
set_geometry: wl.Signal(*XwaylandSurface),
ping_timeout: wl.Signal(*XwaylandSurface),
},
surface_destroy: wl.Listener(*wlr.Surface),
data: usize,
extern fn wlr_xwayland_surface_activate(surface: *XwaylandSurface, activated: bool) void;
pub const activate = wlr_xwayland_surface_activate;
extern fn wlr_xwayland_surface_configure(surface: *XwaylandSurface, x: i16, y: i16, width: u16, height: u16) void;
pub const configure = wlr_xwayland_surface_configure;
extern fn wlr_xwayland_surface_close(surface: *XwaylandSurface) void;
pub const close = wlr_xwayland_surface_close;
extern fn wlr_xwayland_surface_set_minimized(surface: *XwaylandSurface, minimized: bool) void;
pub const setMinimized = wlr_xwayland_surface_set_minimized;
extern fn wlr_xwayland_surface_set_maximized(surface: *XwaylandSurface, maximized: bool) void;
pub const setMaximized = wlr_xwayland_surface_set_maximized;
extern fn wlr_xwayland_surface_set_fullscreen(surface: *XwaylandSurface, fullscreen: bool) void;
pub const setFullscreen = wlr_xwayland_surface_set_fullscreen;
extern fn wlr_xwayland_surface_from_wlr_surface(surface: *wlr.Surface) *XwaylandSurface;
pub const fromWlrSurface = wlr_xwayland_surface_from_wlr_surface;
extern fn wlr_xwayland_surface_ping(surface: *XwaylandSurface) void;
pub const ping = wlr_xwayland_surface_ping;
extern fn wlr_xwayland_or_surface_wants_focus(surface: *const XwaylandSurface) bool;
pub const overrideRedirectWantsFocus = wlr_xwayland_or_surface_wants_focus;
}; | src/xwayland.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const log = std.log.scoped(.vr);
const config = @import("../config.zig");
const MessageBus = @import("../message_bus.zig").MessageBusReplica;
const Message = @import("../message_bus.zig").Message;
const Storage = @import("../storage.zig").Storage;
const vr = @import("../vr.zig");
const Header = vr.Header;
const ConcurrentRanges = @import("../concurrent_ranges.zig").ConcurrentRanges;
const Range = @import("../concurrent_ranges.zig").Range;
pub const Journal = struct {
allocator: *Allocator,
storage: *Storage,
replica: u16,
size: u64,
size_headers: u64,
size_circular_buffer: u64,
headers: []Header align(config.sector_size),
/// Whether an entry is in memory only and needs to be written or is being written:
/// We use this in the same sense as a dirty bit in the kernel page cache.
/// A dirty bit means that we have not yet prepared the entry, or need to repair a faulty entry.
dirty: BitSet,
/// Whether an entry was written to disk and this write was subsequently lost due to:
/// * corruption,
/// * a misdirected write (or a misdirected read, we do not distinguish), or else
/// * a latent sector error, where the sector can no longer be read.
/// A faulty bit means that we prepared and then lost the entry.
/// A faulty bit requires the dirty bit to also be set so that functions need not check both.
/// A faulty bit is used then only to qualify the severity of the dirty bit.
faulty: BitSet,
/// We copy-on-write to this buffer when writing, as in-memory headers may change concurrently:
write_headers_buffer: []u8 align(config.sector_size),
/// Apart from the header written with the entry, we also store two redundant copies of each
/// header at different locations on disk, and we alternate between these for each append.
/// This tracks which version (0 or 1) should be written to next:
write_headers_version: u1 = 0,
/// These serialize concurrent writes but only for overlapping ranges:
writing_headers: ConcurrentRanges = .{ .name = "write_headers" },
writing_sectors: ConcurrentRanges = .{ .name = "write_sectors" },
pub fn init(
allocator: *Allocator,
storage: *Storage,
replica: u16,
size: u64,
headers_count: u32,
) !Journal {
if (@mod(size, config.sector_size) != 0) return error.SizeMustBeAMultipleOfSectorSize;
if (!std.math.isPowerOfTwo(headers_count)) return error.HeadersCountMustBeAPowerOfTwo;
assert(storage.size == size);
const headers_per_sector = @divExact(config.sector_size, @sizeOf(Header));
assert(headers_per_sector > 0);
assert(headers_count >= headers_per_sector);
var headers = try allocator.allocAdvanced(
Header,
config.sector_size,
headers_count,
.exact,
);
errdefer allocator.free(headers);
std.mem.set(Header, headers, Header.reserved());
var dirty = try BitSet.init(allocator, headers.len);
errdefer dirty.deinit();
var faulty = try BitSet.init(allocator, headers.len);
errdefer faulty.deinit();
var write_headers_buffer = try allocator.allocAdvanced(
u8,
config.sector_size,
@sizeOf(Header) * headers.len,
.exact,
);
errdefer allocator.free(write_headers_buffer);
std.mem.set(u8, write_headers_buffer, 0);
const header_copies = 2;
const size_headers = headers.len * @sizeOf(Header);
const size_headers_copies = size_headers * header_copies;
if (size_headers_copies >= size) return error.SizeTooSmallForHeadersCount;
const size_circular_buffer = size - size_headers_copies;
if (size_circular_buffer < 64 * 1024 * 1024) return error.SizeTooSmallForCircularBuffer;
log.debug("{}: journal: size={} headers_len={} headers={} circular_buffer={}", .{
replica,
std.fmt.fmtIntSizeBin(size),
headers.len,
std.fmt.fmtIntSizeBin(size_headers),
std.fmt.fmtIntSizeBin(size_circular_buffer),
});
var self = Journal{
.allocator = allocator,
.storage = storage,
.replica = replica,
.size = size,
.size_headers = size_headers,
.size_circular_buffer = size_circular_buffer,
.headers = headers,
.dirty = dirty,
.faulty = faulty,
.write_headers_buffer = write_headers_buffer,
};
assert(@mod(self.size_circular_buffer, config.sector_size) == 0);
assert(@mod(@ptrToInt(&self.headers[0]), config.sector_size) == 0);
assert(self.dirty.bits.len == self.headers.len);
assert(self.faulty.bits.len == self.headers.len);
assert(self.write_headers_buffer.len == @sizeOf(Header) * self.headers.len);
return self;
}
pub fn deinit(self: *Journal) void {}
/// Asserts that headers are .reserved (zeroed) from `op_min` (inclusive).
pub fn assert_headers_reserved_from(self: *Journal, op_min: u64) void {
// TODO Snapshots
for (self.headers[op_min..]) |header| assert(header.command == .reserved);
}
/// Returns any existing entry at the location indicated by header.op.
/// This existing entry may have an older or newer op number.
pub fn entry(self: *Journal, header: *const Header) ?*const Header {
assert(header.command == .prepare);
return self.entry_for_op(header.op);
}
/// We use the op number directly to index into the headers array and locate ops without a scan.
/// Op numbers cycle through the headers array and do not wrap when offsets wrap. The reason for
/// this is to prevent variable offsets from impacting the location of an op. Otherwise, the
/// same op number but for different views could exist at multiple locations in the journal.
pub fn entry_for_op(self: *Journal, op: u64) ?*const Header {
// TODO Snapshots
const existing = &self.headers[op];
if (existing.command == .reserved) return null;
assert(existing.command == .prepare);
return existing;
}
/// Returns the entry at `@mod(op)` location, but only if `entry.op == op`, else `null`.
/// Be careful of using this without considering that there may still be an existing op.
pub fn entry_for_op_exact(self: *Journal, op: u64) ?*const Header {
if (self.entry_for_op(op)) |existing| {
if (existing.op == op) return existing;
}
return null;
}
/// As per `entry_for_op_exact()`, but only if there is an optional checksum match.
pub fn entry_for_op_exact_with_checksum(
self: *Journal,
op: u64,
checksum: ?u128,
) ?*const Header {
if (self.entry_for_op_exact(op)) |existing| {
assert(existing.op == op);
if (checksum == null or existing.checksum == checksum.?) return existing;
}
return null;
}
pub fn previous_entry(self: *Journal, header: *const Header) ?*const Header {
// TODO Snapshots
if (header.op == 0) return null;
return self.entry_for_op(header.op - 1);
}
pub fn next_entry(self: *Journal, header: *const Header) ?*const Header {
// TODO Snapshots
if (header.op + 1 == self.headers.len) return null;
return self.entry_for_op(header.op + 1);
}
pub fn next_offset(self: *Journal, header: *const Header) u64 {
// TODO Snapshots
assert(header.command == .prepare);
return header.offset + Journal.sector_ceil(header.size);
}
pub fn has(self: *Journal, header: *const Header) bool {
// TODO Snapshots
const existing = &self.headers[header.op];
if (existing.command == .reserved) {
assert(existing.checksum == 0);
assert(existing.checksum_body == 0);
assert(existing.offset == 0);
assert(existing.size == 0);
return false;
} else {
if (existing.checksum == header.checksum) {
assert(existing.checksum_body == header.checksum_body);
assert(existing.op == header.op);
return true;
} else {
return false;
}
}
}
pub fn has_clean(self: *Journal, header: *const Header) bool {
// TODO Snapshots
return self.has(header) and !self.dirty.bit(header.op);
}
pub fn has_dirty(self: *Journal, header: *const Header) bool {
// TODO Snapshots
return self.has(header) and self.dirty.bit(header.op);
}
/// Copies latest headers between `op_min` and `op_max` (both inclusive) as will fit in `dest`.
/// Reverses the order when copying so that latest headers are copied first, which also protects
/// against the callsite slicing the buffer the wrong way and incorrectly.
/// Skips .reserved headers (gaps between headers).
/// Zeroes the `dest` buffer in case the copy would underflow and leave a buffer bleed.
/// Returns the number of headers actually copied.
pub fn copy_latest_headers_between(
self: *Journal,
op_min: u64,
op_max: u64,
dest: []Header,
) usize {
assert(op_min <= op_max);
assert(dest.len > 0);
var copied: usize = 0;
std.mem.set(Header, dest, Header.reserved());
// We start at op_max + 1 but front-load the decrement to avoid overflow when op_min == 0:
var op = op_max + 1;
while (op > op_min) {
op -= 1;
if (self.entry_for_op_exact(op)) |header| {
dest[copied] = header.*;
assert(dest[copied].invalid() == null);
copied += 1;
}
}
return copied;
}
const HeaderRange = struct { op_min: u64, op_max: u64 };
/// Finds the latest break in headers, searching between `op_min` and `op_max` (both inclusive).
/// A break is a missing header or a header not connected to the next header (by hash chain).
/// Upon finding the highest break, extends the range downwards to cover as much as possible.
///
/// For example: If ops 3, 9 and 10 are missing, returns: `{ .op_min = 9, .op_max = 10 }`.
///
/// Another example: If op 17 is disconnected from op 18, 16 is connected to 17, and 12-15 are
/// missing, returns: `{ .op_min = 12, .op_max = 17 }`.
pub fn find_latest_headers_break_between(
self: *Journal,
op_min: u64,
op_max: u64,
) ?HeaderRange {
assert(op_min <= op_max);
var range: ?HeaderRange = null;
// We set B, the op after op_max, to null because we only examine breaks <= op_max:
// In other words, we may report a missing header for op_max itself but not a broken chain.
var B: ?*const Header = null;
var op = op_max + 1;
while (op > op_min) {
op -= 1;
// Get the entry at @mod(op) location, but only if entry.op == op, else null:
var A = self.entry_for_op_exact(op);
if (A) |a| {
if (B) |b| {
// If A was reordered then A may have a newer op than B (but an older view).
// However, here we use entry_for_op_exact() so we can assert a.op + 1 == b.op:
assert(a.op + 1 == b.op);
// Further, while repair_header() should never put an older view to the right
// of a newer view, it may put a newer view to the left of an older view.
// We therefore do not assert a.view <= b.view unless the hash chain is intact.
// A exists and B exists:
if (range) |*r| {
assert(b.op == r.op_min);
if (a.checksum == b.nonce) {
// A is connected to B, but B is disconnected, add A to range:
assert(a.view <= b.view);
r.op_min = a.op;
} else if (a.view < b.view) {
// A is not connected to B, and A is older than B, add A to range:
r.op_min = a.op;
} else if (a.view > b.view) {
// A is not connected to B, but A is newer than B, close range:
break;
} else {
// Op numbers in the same view must be connected.
unreachable;
}
} else if (a.checksum == b.nonce) {
// A is connected to B, and B is connected or B is op_max.
assert(a.view <= b.view);
} else if (a.view < b.view) {
// A is not connected to B, and A is older than B, open range:
range = .{ .op_min = a.op, .op_max = a.op };
} else if (a.view > b.view) {
// A is not connected to B, but A is newer than B, open and close range:
// TODO Add unit test especially for this.
// This is important if we see `self.op < self.commit_max` then request
// prepares and then later receive a newer view to the left of `self.op`.
// We must then repair `self.op` which was reordered through a view change.
range = .{ .op_min = b.op, .op_max = b.op };
break;
} else {
// Op numbers in the same view must be connected.
unreachable;
}
} else {
// A exists and B does not exist (or B has a lower op number):
if (range) |r| {
// We therefore cannot compare A to B, A may be older/newer, close range:
assert(r.op_min == op + 1);
break;
} else {
// We expect a range if B does not exist, unless:
assert(a.op == op_max);
}
}
} else {
// A does not exist (or A has a lower op number):
if (self.entry_for_op(op)) |wrapped_a| assert(wrapped_a.op < op);
if (range) |*r| {
// Add A to range:
assert(r.op_min == op + 1);
r.op_min = op;
} else {
// Open range:
assert(B != null or op == op_max);
range = .{ .op_min = op, .op_max = op };
}
}
B = A;
}
return range;
}
pub fn read_sectors(self: *Journal, buffer: []u8, offset: u64) void {
// Memory must not be owned by self.headers as self.headers may be modified concurrently:
assert(@ptrToInt(buffer.ptr) < @ptrToInt(self.headers.ptr) or
@ptrToInt(buffer.ptr) > @ptrToInt(self.headers.ptr) + self.size_headers);
log.debug("{}: journal: read_sectors: offset={} len={}", .{
self.replica,
offset,
buffer.len,
});
self.storage.read(buffer, offset);
}
/// A safe way of removing an entry, where the header must match the current entry to succeed.
fn remove_entry(self: *Journal, header: *const Header) void {
// Copy the header.op by value to avoid a reset() followed by undefined header.op usage:
const op = header.op;
log.debug("{}: journal: remove_entry: op={}", .{ self.replica, op });
assert(self.entry(header).?.checksum == header.checksum);
assert(self.headers[op].checksum == header.checksum); // TODO Snapshots
defer self.headers[op] = Header.reserved();
self.dirty.clear(op);
self.faulty.clear(op);
}
/// Removes entries from `op_min` (inclusive) onwards.
/// This is used after a view change to remove uncommitted entries discarded by the new leader.
pub fn remove_entries_from(self: *Journal, op_min: u64) void {
// TODO Snapshots
// TODO Optimize to jump directly to op:
assert(op_min > 0);
log.debug("{}: journal: remove_entries_from: op_min={}", .{ self.replica, op_min });
for (self.headers) |*header| {
if (header.op >= op_min and header.command == .prepare) {
self.remove_entry(header);
}
}
self.assert_headers_reserved_from(op_min);
// TODO At startup we need to handle entries that may have been removed but now reappear.
// This is because we do not call `write_headers_between()` here.
}
pub fn set_entry_as_dirty(self: *Journal, header: *const Header) void {
log.debug("{}: journal: set_entry_as_dirty: op={} checksum={}", .{
self.replica,
header.op,
header.checksum,
});
if (self.entry(header)) |existing| {
if (existing.checksum != header.checksum) {
self.faulty.clear(header.op);
}
}
self.headers[header.op] = header.*;
self.dirty.set(header.op);
// Do not clear any faulty bit for the same entry.
}
pub fn write(self: *Journal, message: *const Message) void {
assert(message.header.command == .prepare);
assert(message.header.size >= @sizeOf(Header));
assert(message.header.size <= message.buffer.len);
// The underlying header memory must be owned by the buffer and not by self.headers:
// Otherwise, concurrent writes may modify the memory of the pointer while we write.
assert(@ptrToInt(message.header) == @ptrToInt(message.buffer.ptr));
// There should be no concurrency between setting an entry as dirty and deciding to write:
assert(self.has_dirty(message.header));
const sectors = message.buffer[0..Journal.sector_ceil(message.header.size)];
assert(message.header.offset + sectors.len <= self.size_circular_buffer);
if (std.builtin.mode == .Debug) {
// Assert that any sector padding has already been zeroed:
var sum_of_sector_padding_bytes: u32 = 0;
for (sectors[message.header.size..]) |byte| sum_of_sector_padding_bytes += byte;
assert(sum_of_sector_padding_bytes == 0);
}
self.write_debug(message.header, "starting");
self.write_sectors(message.buffer, self.offset_in_circular_buffer(message.header.offset));
if (!self.has(message.header)) {
self.write_debug(message.header, "entry changed while writing sectors");
return;
}
// TODO Snapshots
self.write_headers_between(message.header.op, message.header.op);
if (!self.has(message.header)) {
self.write_debug(message.header, "entry changed while writing headers");
return;
}
self.write_debug(message.header, "complete, marking clean");
// TODO Snapshots
self.dirty.clear(message.header.op);
self.faulty.clear(message.header.op);
}
fn write_debug(self: *Journal, header: *const Header, status: []const u8) void {
log.debug("{}: journal: write: view={} op={} offset={} len={}: {} {s}", .{
self.replica,
header.view,
header.op,
header.offset,
header.size,
header.checksum,
status,
});
}
pub fn offset_in_circular_buffer(self: *Journal, offset: u64) u64 {
assert(offset < self.size_circular_buffer);
return self.size_headers + offset;
}
fn offset_in_headers_version(self: *Journal, offset: u64, version: u1) u64 {
assert(offset < self.size_headers);
return switch (version) {
0 => offset,
1 => self.size_headers + self.size_circular_buffer + offset,
};
}
/// Writes headers between `op_min` and `op_max` (both inclusive).
fn write_headers_between(self: *Journal, op_min: u64, op_max: u64) void {
// TODO Snapshots
assert(op_min <= op_max);
const offset = Journal.sector_floor(op_min * @sizeOf(Header));
const len = Journal.sector_ceil((op_max - op_min + 1) * @sizeOf(Header));
assert(len > 0);
// We must acquire the concurrent range using the sector offset and len:
// Different headers may share the same sector without any op_min or op_max overlap.
// TODO Use a callback to acquire the range instead of suspend/resume:
var range = Range{ .offset = offset, .len = len };
self.writing_headers.acquire(&range);
defer self.writing_headers.release(&range);
const source = std.mem.sliceAsBytes(self.headers)[offset .. offset + len];
var slice = self.write_headers_buffer[offset .. offset + len];
assert(slice.len == source.len);
assert(slice.len == len);
std.mem.copy(u8, slice, source);
log.debug("{}: journal: write_headers: op_min={} op_max={} sectors[{}..{}]", .{
self.replica,
op_min,
op_max,
offset,
offset + len,
});
// Versions must be incremented upfront:
// write_headers_to_version() will block while other calls may proceed concurrently.
// If we don't increment upfront we could end up writing to the same copy twice.
// We would then lose the redundancy required to locate headers or overwrite all copies.
// TODO Snapshots
if (self.write_headers_once(self.headers[op_min .. op_max + 1])) {
const version_a = self.write_headers_increment_version();
self.write_headers_to_version(version_a, slice, offset);
} else {
const version_a = self.write_headers_increment_version();
const version_b = self.write_headers_increment_version();
self.write_headers_to_version(version_a, slice, offset);
self.write_headers_to_version(version_b, slice, offset);
}
}
fn write_headers_increment_version(self: *Journal) u1 {
self.write_headers_version +%= 1;
return self.write_headers_version;
}
/// Since we allow gaps in the journal, we may have to write our headers twice.
/// If a dirty header is being written as reserved (empty) then write twice to make this clear.
/// If a dirty header has no previous clean chained entry to give its offset then write twice.
/// Otherwise, we only need to write the headers once because their other copy can be located in
/// the body of the journal (using the previous entry's offset and size).
fn write_headers_once(self: *Journal, headers: []const Header) bool {
for (headers) |*header| {
// TODO Snapshots
// We must use header.op and not the loop index as we are working from a slice:
if (!self.dirty.bit(header.op)) continue;
if (header.command == .reserved) {
log.debug("{}: journal: write_headers_once: dirty reserved header", .{
self.replica,
});
return false;
}
if (self.previous_entry(header)) |previous| {
assert(previous.command == .prepare);
if (previous.checksum != header.nonce) {
log.debug("{}: journal: write_headers_once: no hash chain", .{
self.replica,
});
return false;
}
// TODO Add is_dirty(header)
// TODO Snapshots
if (self.dirty.bit(previous.op)) {
log.debug("{}: journal: write_headers_once: previous entry is dirty", .{
self.replica,
});
return false;
}
} else {
log.debug("{}: journal: write_headers_once: no previous entry", .{
self.replica,
});
return false;
}
}
return true;
}
fn write_headers_to_version(self: *Journal, version: u1, buffer: []const u8, offset: u64) void {
log.debug("{}: journal: write_headers_to_version: version={} offset={} len={}", .{
self.replica,
version,
offset,
buffer.len,
});
assert(offset + buffer.len <= self.size_headers);
self.write_sectors(buffer, self.offset_in_headers_version(offset, version));
}
fn write_sectors(self: *Journal, buffer: []const u8, offset: u64) void {
// Memory must not be owned by self.headers as self.headers may be modified concurrently:
assert(@ptrToInt(buffer.ptr) < @ptrToInt(self.headers.ptr) or
@ptrToInt(buffer.ptr) > @ptrToInt(self.headers.ptr) + self.size_headers);
// TODO We can move this range queuing right into Storage and remove write_sectors entirely.
// Our ConcurrentRange structure would also need to be weaned off of async/await but at
// least then we can manage this all in one place (i.e. in Storage).
var range = Range{ .offset = offset, .len = buffer.len };
self.writing_sectors.acquire(&range);
defer self.writing_sectors.release(&range);
log.debug("{}: journal: write_sectors: offset={} len={}", .{
self.replica,
offset,
buffer.len,
});
self.storage.write(buffer, offset);
}
pub fn sector_floor(offset: u64) u64 {
const sectors = std.math.divFloor(u64, offset, config.sector_size) catch unreachable;
return sectors * config.sector_size;
}
pub fn sector_ceil(offset: u64) u64 {
const sectors = std.math.divCeil(u64, offset, config.sector_size) catch unreachable;
return sectors * config.sector_size;
}
};
// TODO Snapshots
pub const BitSet = struct {
allocator: *Allocator,
bits: []bool,
/// The number of bits set (updated incrementally as bits are set or cleared):
len: u64 = 0,
fn init(allocator: *Allocator, count: u64) !BitSet {
var bits = try allocator.alloc(bool, count);
errdefer allocator.free(bits);
std.mem.set(bool, bits, false);
return BitSet{
.allocator = allocator,
.bits = bits,
};
}
fn deinit(self: *BitSet) void {
self.allocator.free(self.bits);
}
/// Clear the bit for an op (idempotent):
pub fn clear(self: *BitSet, op: u64) void {
if (self.bits[op]) {
self.bits[op] = false;
self.len -= 1;
}
}
/// Whether the bit for an op is set:
pub fn bit(self: *BitSet, op: u64) bool {
return self.bits[op];
}
/// Set the bit for an op (idempotent):
pub fn set(self: *BitSet, op: u64) void {
if (!self.bits[op]) {
self.bits[op] = true;
self.len += 1;
assert(self.len <= self.bits.len);
}
}
}; | src/vr/journal.zig |
const std = @import("std");
const print = std.debug.print;
const Allocator = std.mem.Allocator;
const meta = std.meta;
const Utf8View = std.unicode.Utf8View;
const Self = @This();
allocator: *Allocator,
pub fn init(allocator: *Allocator) Self {
return Self{
.allocator = allocator,
};
}
pub fn parseJson(self: *const Self, comptime T: type, value: []const u8) !T {
return try std.json.parse(T, &std.json.TokenStream.init(value), .{ .allocator = self.allocator });
}
pub fn parseArray(self: *const Self, value: []const u8, break_point: []const u8) ![][]const u8 {
var buffer = std.ArrayList([]const u8).init(self.allocator);
var stop_point: usize = try std.math.divCeil(usize, break_point.len, 2);
for (value) |_, index| {
const one_step = index + break_point.len;
if (one_step == value.len and stop_point < index) {
try buffer.append(value[stop_point..index]);
}
if (one_step == value.len) break;
if (std.mem.eql(u8, value[index..one_step], break_point)) {
try buffer.append(value[stop_point..index]);
stop_point = one_step;
}
}
return buffer.toOwnedSlice();
}
// const testing = std.testing;
// test "Parser" {
// var gpa = std.heap.GeneralPurposeAllocator(.{}){};
// const allocator = &gpa.allocator;
// const test_string =
// \\{Ace,2,Queen}
// ;
// const test_string2 =
// \\{"Test string ?","I am long text!","Finishing words." }
// ;
// const parser = Self.init(allocator);
// var parsed1 = try parser.parseArray(test_string, ",");
// var parsed2 = try parser.parseArray(test_string2, "\x22,\x22");
// var results1 = [3][]const u8{
// "Ace",
// "2",
// "Queen",
// };
// var results2 = [3][]const u8{
// "Test string ?",
// "I am long text!",
// "Finishing words.",
// };
// // Todo finish test
// for (parsed1) |value, index| {
// print("{s} \n", .{value});
// }
// for (parsed2) |value, index| {
// print("{s} \n", .{value});
// }
// defer {
// allocator.free(parsed1);
// allocator.free(parsed2);
// std.debug.assert(!gpa.deinit());
// }
// } | src/parser.zig |
const std = @import("std");
pub fn fmtValueLiteral(w: anytype, value: anytype, print_type_name: bool) !void {
const TO = @TypeOf(value);
const TI = @typeInfo(TO);
if (comptime std.meta.trait.isZigString(TO)) {
try w.print("\"{}\"", .{std.zig.fmtEscapes(value)});
return;
}
if (comptime std.meta.trait.isIndexable(TO)) {
if (comptime std.meta.trait.isSlice(TO)) {
try w.writeAll("&");
}
try w.writeAll(".{");
for (value) |item, i| {
try fmtValueLiteral(w, item, print_type_name);
if (i < value.len - 1) {
try w.writeAll(",");
}
}
try w.writeAll("}");
return;
}
switch (TI) {
.Struct => |v| {
try w.writeAll(if (print_type_name) @typeName(TO) else ".");
try w.writeAll("{");
inline for (v.fields) |sf, j| {
try w.print(".{s} = ", .{sf.name});
try fmtValueLiteral(w, @field(value, sf.name), print_type_name);
if (j < v.fields.len - 1) {
try w.writeAll(", ");
}
}
try w.writeAll("}");
},
.Int => {
try w.print("{d}", .{value});
},
.Union => |v| {
try w.writeAll(if (print_type_name) @typeName(TO) else ".");
const UnionTagType = v.tag_type.?;
try w.writeAll("{.");
try w.writeAll(@tagName(@as(UnionTagType, value)));
try w.writeAll(" = ");
inline for (v.fields) |u_field| {
if (value == @field(UnionTagType, u_field.name)) {
try fmtValueLiteral(w, @field(value, u_field.name), print_type_name);
}
}
try w.writeAll("}");
},
.Void => {
try w.writeAll("void{}");
},
.Optional => |_| {
if (value) |cap| {
try fmtValueLiteral(w, cap, print_type_name);
} else {
try w.writeAll("null");
}
},
.Enum => {
try w.writeAll(".");
try w.writeAll(@tagName(value));
},
else => {
@compileError(@tagName(TI) ++ " " ++ @typeName(TO));
},
}
} | src/lib.zig |
const Builder = @import("std").build.Builder;
const z = @import("std").zig;
const std = @import("std");
const builtin = @import("builtin");
//Optional customizations
const icon0 = "ICON0.png"; //REPLACE WITH PATH TO ICON0.PNG 144 x 80 Thumbnail
const icon1 = "NULL"; //REPLACE WITH PATH TO ICON1.PMF 144 x 80 animation
const pic0 = "NULL"; //REPLACE WITH PATH TO PIC0.PNG 480 x 272 Background
const pic1 = "NULL"; //REPLACE WITH PATH TO PIC1.PMF 480 x 272 Animation
const snd0 = "NULL"; //REPLACE WITH PATH TO SND0.AT3 Music
pub fn build(b: *Builder) void {
var feature_set : std.Target.Cpu.Feature.Set = std.Target.Cpu.Feature.Set.empty;
feature_set.addFeature(@enumToInt(std.Target.mips.Feature.single_float));
//PSP-Specific Build Options
const target = z.CrossTarget{
.cpu_arch = .mipsel,
.os_tag = .freestanding,
.cpu_model = .{ .explicit = &std.Target.mips.cpu.mips2 },
.cpu_features_add = feature_set
};
//All of the release modes work
//Debug Mode can cause issues with trap instructions - use ReleaseSafe for "Debug" builds
const mode = builtin.Mode.ReleaseSafe;
//Build from your main file!
const exe = b.addExecutable("main", "src/main.zig");
//Output to zig cache for now
exe.setOutputDir("zig-cache/");
//Set mode & target
exe.setTarget(target);
exe.setBuildMode(mode);
exe.setLinkerScriptPath("src/Zig-PSP/tools/linkfile.ld");
exe.link_eh_frame_hdr = true;
exe.link_emit_relocs = true;
//Post-build actions
const hostTarget = b.standardTargetOptions(.{});
const prx = b.addExecutable("prxgen", "src/Zig-PSP/tools/prxgen/stub.zig");
prx.setTarget(hostTarget);
prx.addCSourceFile("src/Zig-PSP/tools/prxgen/psp-prxgen.c", &[_][]const u8{"-std=c99", "-Wno-address-of-packed-member", "-D_CRT_SECURE_NO_WARNINGS"});
prx.linkLibC();
prx.setBuildMode(builtin.Mode.ReleaseFast);
prx.setOutputDir("src/Zig-PSP/tools/bin");
prx.install();
prx.step.dependOn(&exe.step);
const append : []const u8 = switch(builtin.os.tag){
.windows => ".exe",
else => "",
};
const generate_prx = b.addSystemCommand(&[_][]const u8{
"src/Zig-PSP/tools/bin/prxgen" ++ append,
"zig-cache/main",
"app.prx"
});
generate_prx.step.dependOn(&prx.step);
//Build SFO
const sfo = b.addExecutable("sfotool", "./src/Zig-PSP/tools/sfo/src/main.zig");
sfo.setTarget(hostTarget);
sfo.setBuildMode(builtin.Mode.ReleaseFast);
sfo.setOutputDir("src/Zig-PSP/tools/bin");
sfo.install();
sfo.step.dependOn(&generate_prx.step);
//Make the SFO file
const mk_sfo = b.addSystemCommand(&[_][]const u8{
"./src/Zig-PSP/tools/bin/sfotool" ++ append, "parse",
"sfo.json",
"PARAM.SFO"
});
mk_sfo.step.dependOn(&sfo.step);
//Build PBP
const PBP = b.addExecutable("pbptool", "./src/Zig-PSP/tools/pbp/src/main.zig");
PBP.setTarget(hostTarget);
PBP.setBuildMode(builtin.Mode.ReleaseFast);
PBP.setOutputDir("src/Zig-PSP/tools/bin");
PBP.install();
PBP.step.dependOn(&mk_sfo.step);
//Pack the PBP executable
const pack_pbp = b.addSystemCommand(&[_][]const u8{
"src/Zig-PSP/tools/bin/pbptool" ++ append, "pack",
"EBOOT.PBP",
"PARAM.SFO",
icon0,
icon1,
pic0,
pic1,
snd0,
"app.prx",
"NULL" //DATA.PSAR not necessary.
});
pack_pbp.step.dependOn(&PBP.step);
//Enable the build
b.default_step.dependOn(&pack_pbp.step);
} | build.zig |
const std = @import("std");
pub const EscapedStringIterator = struct {
slice: []const u8,
position: usize,
pub fn init(slice: []const u8) @This() {
return @This(){
.slice = slice,
.position = 0,
};
}
pub fn next(self: *@This()) error{IncompleteEscapeSequence}!?u8 {
if (self.position >= self.slice.len)
return null;
switch (self.slice[self.position]) {
'\\' => {
self.position += 1;
if (self.position == self.slice.len)
return error.IncompleteEscapeSequence;
const c = self.slice[self.position];
self.position += 1;
return switch (c) {
'a' => 7,
'b' => 8,
't' => 9,
'n' => 10,
'r' => 13,
'e' => 27,
'\"' => 34,
'\'' => 39,
'x' => blk: {
if (self.position + 2 > self.slice.len)
return error.IncompleteEscapeSequence;
const str = self.slice[self.position..][0..2];
self.position += 2;
break :blk std.fmt.parseInt(u8, str, 16) catch return error.IncompleteEscapeSequence;
},
else => c,
};
},
else => {
self.position += 1;
return self.slice[self.position - 1];
},
}
}
};
/// Applies all known string escape codes to the given input string,
/// returning a freshly allocated string.
pub fn escapeString(allocator: std.mem.Allocator, input: []const u8) ![]u8 {
var iterator = EscapedStringIterator{
.slice = input,
.position = 0,
};
var len: usize = 0;
while (try iterator.next()) |_| {
len += 1;
}
iterator.position = 0;
const result = try allocator.alloc(u8, len);
var i: usize = 0;
while (iterator.next() catch unreachable) |c| {
result[i] = c;
i += 1;
}
std.debug.assert(i == len);
return result;
}
test "escape empty string" {
const str = try escapeString(std.testing.allocator, "");
defer std.testing.allocator.free(str);
try std.testing.expectEqualStrings("", str);
}
test "escape string without escape codes" {
const str = try escapeString(std.testing.allocator, "<KEY>");
defer std.testing.allocator.free(str);
try std.testing.expectEqualStrings("<KEY>", str);
}
// \a 7 Alert / Bell
// \b 8 Backspace
// \t 9 Horizontal Tab
// \n 10 Line Feed
// \r 13 Carriage Return
// \e 27 Escape
// \" 34 Double Quotes
// \' 39 Single Quote
test "escape string with predefined escape sequences" {
const str = try escapeString(std.testing.allocator, " \\a \\b \\t \\n \\r \\e \\\" \\' ");
defer std.testing.allocator.free(str);
try std.testing.expectEqualStrings(" \x07 \x08 \x09 \x0A \x0D \x1B \" \' ", str);
}
test "escape string with hexadecimal escape sequences" {
const str = try escapeString(std.testing.allocator, " \\xcA \\x84 \\x2d \\x75 \\xb7 \\xF1 \\xf3 \\x9e ");
defer std.testing.allocator.free(str);
try std.testing.expectEqualStrings(" \xca \x84 \x2d \x75 \xb7 \xf1 \xf3 \x9e ", str);
}
test "incomplete normal escape sequence" {
try std.testing.expectError(error.IncompleteEscapeSequence, escapeString(std.testing.allocator, "\\"));
}
test "incomplete normal hex sequence" {
try std.testing.expectError(error.IncompleteEscapeSequence, escapeString(std.testing.allocator, "\\x"));
try std.testing.expectError(error.IncompleteEscapeSequence, escapeString(std.testing.allocator, "\\xA"));
}
test "invalid hex sequence" {
try std.testing.expectError(error.IncompleteEscapeSequence, escapeString(std.testing.allocator, "\\xXX"));
}
test "escape string with tight predefined escape sequence" {
const str = try escapeString(std.testing.allocator, "\\a");
defer std.testing.allocator.free(str);
try std.testing.expectEqualStrings("\x07", str);
}
test "escape string with tight hexadecimal escape sequence" {
const str = try escapeString(std.testing.allocator, "\\xca");
defer std.testing.allocator.free(str);
try std.testing.expectEqualStrings("\xca", str);
} | src/library/compiler/string-escaping.zig |
const xcb = @import("../xcb.zig");
pub const id = xcb.Extension{ .name = "SYNC", .global_id = 0 };
pub const ALARM = u32;
pub const ALARMSTATE = extern enum(c_uint) {
@"Active" = 0,
@"Inactive" = 1,
@"Destroyed" = 2,
};
pub const COUNTER = u32;
pub const FENCE = u32;
pub const TESTTYPE = extern enum(c_uint) {
@"PositiveTransition" = 0,
@"NegativeTransition" = 1,
@"PositiveComparison" = 2,
@"NegativeComparison" = 3,
};
pub const VALUETYPE = extern enum(c_uint) {
@"Absolute" = 0,
@"Relative" = 1,
};
pub const CA = extern enum(c_uint) {
@"Counter" = 1,
@"ValueType" = 2,
@"Value" = 4,
@"TestType" = 8,
@"Delta" = 16,
@"Events" = 32,
};
/// @brief INT64
pub const INT64 = struct {
@"hi": i32,
@"lo": u32,
};
/// @brief SYSTEMCOUNTER
pub const SYSTEMCOUNTER = struct {
@"counter": xcb.sync.COUNTER,
@"resolution": xcb.sync.INT64,
@"name_len": u16,
@"name": []u8,
};
/// @brief TRIGGER
pub const TRIGGER = struct {
@"counter": xcb.sync.COUNTER,
@"wait_type": u32,
@"wait_value": xcb.sync.INT64,
@"test_type": u32,
};
/// @brief WAITCONDITION
pub const WAITCONDITION = struct {
@"trigger": xcb.sync.TRIGGER,
@"event_threshold": xcb.sync.INT64,
};
/// Opcode for Counter.
pub const CounterOpcode = 0;
/// @brief CounterError
pub const CounterError = struct {
@"response_type": u8,
@"error_code": u8,
@"sequence": u16,
@"bad_counter": u32,
@"minor_opcode": u16,
@"major_opcode": u8,
};
/// Opcode for Alarm.
pub const AlarmOpcode = 1;
/// @brief AlarmError
pub const AlarmError = struct {
@"response_type": u8,
@"error_code": u8,
@"sequence": u16,
@"bad_alarm": u32,
@"minor_opcode": u16,
@"major_opcode": u8,
};
/// @brief Initializecookie
pub const Initializecookie = struct {
sequence: c_uint,
};
/// @brief InitializeRequest
pub const InitializeRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 0,
@"length": u16,
@"desired_major_version": u8,
@"desired_minor_version": u8,
};
/// @brief InitializeReply
pub const InitializeReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"major_version": u8,
@"minor_version": u8,
@"pad1": [22]u8,
};
/// @brief ListSystemCounterscookie
pub const ListSystemCounterscookie = struct {
sequence: c_uint,
};
/// @brief ListSystemCountersRequest
pub const ListSystemCountersRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 1,
@"length": u16,
};
/// @brief ListSystemCountersReply
pub const ListSystemCountersReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"counters_len": u32,
@"pad1": [20]u8,
@"counters": []xcb.sync.SYSTEMCOUNTER,
};
/// @brief CreateCounterRequest
pub const CreateCounterRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 2,
@"length": u16,
@"id": xcb.sync.COUNTER,
@"initial_value": xcb.sync.INT64,
};
/// @brief DestroyCounterRequest
pub const DestroyCounterRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 6,
@"length": u16,
@"counter": xcb.sync.COUNTER,
};
/// @brief QueryCountercookie
pub const QueryCountercookie = struct {
sequence: c_uint,
};
/// @brief QueryCounterRequest
pub const QueryCounterRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 5,
@"length": u16,
@"counter": xcb.sync.COUNTER,
};
/// @brief QueryCounterReply
pub const QueryCounterReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"counter_value": xcb.sync.INT64,
};
/// @brief AwaitRequest
pub const AwaitRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 7,
@"length": u16,
@"wait_list": []const xcb.sync.WAITCONDITION,
};
/// @brief ChangeCounterRequest
pub const ChangeCounterRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 4,
@"length": u16,
@"counter": xcb.sync.COUNTER,
@"amount": xcb.sync.INT64,
};
/// @brief SetCounterRequest
pub const SetCounterRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 3,
@"length": u16,
@"counter": xcb.sync.COUNTER,
@"value": xcb.sync.INT64,
};
/// @brief CreateAlarmRequest
pub const CreateAlarmRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 8,
@"length": u16,
@"id": xcb.sync.ALARM,
@"value_mask": u32,
};
/// @brief ChangeAlarmRequest
pub const ChangeAlarmRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 9,
@"length": u16,
@"id": xcb.sync.ALARM,
@"value_mask": u32,
};
/// @brief DestroyAlarmRequest
pub const DestroyAlarmRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 11,
@"length": u16,
@"alarm": xcb.sync.ALARM,
};
/// @brief QueryAlarmcookie
pub const QueryAlarmcookie = struct {
sequence: c_uint,
};
/// @brief QueryAlarmRequest
pub const QueryAlarmRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 10,
@"length": u16,
@"alarm": xcb.sync.ALARM,
};
/// @brief QueryAlarmReply
pub const QueryAlarmReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"trigger": xcb.sync.TRIGGER,
@"delta": xcb.sync.INT64,
@"events": u8,
@"state": u8,
@"pad1": [2]u8,
};
/// @brief SetPriorityRequest
pub const SetPriorityRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 12,
@"length": u16,
@"id": u32,
@"priority": i32,
};
/// @brief GetPrioritycookie
pub const GetPrioritycookie = struct {
sequence: c_uint,
};
/// @brief GetPriorityRequest
pub const GetPriorityRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 13,
@"length": u16,
@"id": u32,
};
/// @brief GetPriorityReply
pub const GetPriorityReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"priority": i32,
};
/// @brief CreateFenceRequest
pub const CreateFenceRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 14,
@"length": u16,
@"drawable": xcb.DRAWABLE,
@"fence": xcb.sync.FENCE,
@"initially_triggered": u8,
};
/// @brief TriggerFenceRequest
pub const TriggerFenceRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 15,
@"length": u16,
@"fence": xcb.sync.FENCE,
};
/// @brief ResetFenceRequest
pub const ResetFenceRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 16,
@"length": u16,
@"fence": xcb.sync.FENCE,
};
/// @brief DestroyFenceRequest
pub const DestroyFenceRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 17,
@"length": u16,
@"fence": xcb.sync.FENCE,
};
/// @brief QueryFencecookie
pub const QueryFencecookie = struct {
sequence: c_uint,
};
/// @brief QueryFenceRequest
pub const QueryFenceRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 18,
@"length": u16,
@"fence": xcb.sync.FENCE,
};
/// @brief QueryFenceReply
pub const QueryFenceReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"triggered": u8,
@"pad1": [23]u8,
};
/// @brief AwaitFenceRequest
pub const AwaitFenceRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 19,
@"length": u16,
@"fence_list": []const xcb.sync.FENCE,
};
/// Opcode for CounterNotify.
pub const CounterNotifyOpcode = 0;
/// @brief CounterNotifyEvent
pub const CounterNotifyEvent = struct {
@"response_type": u8,
@"kind": u8,
@"sequence": u16,
@"counter": xcb.sync.COUNTER,
@"wait_value": xcb.sync.INT64,
@"counter_value": xcb.sync.INT64,
@"timestamp": xcb.TIMESTAMP,
@"count": u16,
@"destroyed": u8,
@"pad0": u8,
};
/// Opcode for AlarmNotify.
pub const AlarmNotifyOpcode = 1;
/// @brief AlarmNotifyEvent
pub const AlarmNotifyEvent = struct {
@"response_type": u8,
@"kind": u8,
@"sequence": u16,
@"alarm": xcb.sync.ALARM,
@"counter_value": xcb.sync.INT64,
@"alarm_value": xcb.sync.INT64,
@"timestamp": xcb.TIMESTAMP,
@"state": u8,
@"pad0": [3]u8,
};
test "" {
@import("std").testing.refAllDecls(@This());
} | src/auto/sync.zig |
const std = @import("std");
pub const LissajousMode = enum {
Lissajous2D,
Lissajous3D,
Heatmap,
};
pub const FrequencyMode = enum {
Flat,
Waterfall,
};
pub const OscilloscopeMode = enum {
Combined,
};
pub const Element = struct {
id: []const u8,
pane: Pane = Pane.identity,
relative: ?struct {
id: []const u8,
self: Pane.Anchor,
parent: Pane.Anchor,
relative_size: bool = true,
} = null,
};
const ResolvedElement = struct {
pane: Pane = Pane.identity,
relative: ?struct {
index: usize,
self: Pane.Anchor,
parent: Pane.Anchor,
relative_size: bool = true,
},
};
pub fn Layout(comptime elements: []const Element) type {
var initial_panes: [elements.len]ResolvedElement = undefined;
const Helper = struct {
fn getIndex(comptime id: []const u8) usize {
return inline for (elements) |elem, i| {
if (comptime std.mem.eql(u8, elem.id, id))
break i;
} else @compileError("No Element with id '" ++ id ++ "'");
}
};
inline for (elements) |elem, i| {
initial_panes[i].pane = elem.pane;
initial_panes[i].relative = null;
if (elem.relative) |relative| {
initial_panes[i].relative = .{
.index = Helper.getIndex(relative.id),
.self = relative.self,
.parent = relative.parent,
.relative_size = relative.relative_size,
};
}
}
return struct {
elems: []ResolvedElement = &initial_panes,
pub fn getPane(self: @This(), comptime id: []const u8) Pane {
var elem = self.elems[comptime Helper.getIndex(id)];
var out = elem.pane;
while (elem.relative) |parent| {
elem = self.elems[parent.index];
out = Pane.translate(
parent.self,
out,
parent.parent,
elem.pane,
parent.relative_size,
);
}
return out;
}
};
}
pub const Pane = struct {
x: f32 = 0,
y: f32 = 0,
width: f32 = 1,
height: f32 = 1,
pub const identity = Pane{};
pub const Anchor = struct {
pub const TopLeft = Anchor{ .x = 0, .y = 0 };
pub const TopCenter = Anchor{ .x = 0.5, .y = 0 };
pub const TopRight = Anchor{ .x = 1, .y = 0 };
pub const Left = Anchor{ .x = 0, .y = 0.5 };
pub const Center = Anchor{ .x = 0.5, .y = 0.5 };
pub const Right = Anchor{ .x = 1, .y = 0.5 };
pub const BottomLeft = Anchor{ .x = 0, .y = 1 };
pub const BottomCenter = Anchor{ .x = 0.5, .y = 1 };
pub const BottomRight = Anchor{ .x = 1, .y = 1 };
x: f32,
y: f32,
};
pub fn translate(src_anchor: Anchor, src: Pane, dst_anchor: Anchor, dst: Pane, resize: bool) Pane {
var out = src;
if (resize) {
out.width *= dst.width;
out.height *= dst.height;
}
out.x -= src_anchor.x * out.width;
out.y -= src_anchor.y * out.height;
out.x = dst.x + dst.width * dst_anchor.x + out.x;
out.y = dst.y + dst.height * dst_anchor.y + out.y;
return out;
}
};
params: *@import("./shared.zig").Parameters,
lissajous_mode: LissajousMode = .Heatmap,
frequency_mode: FrequencyMode = .Waterfall,
oscilloscope_mode: OscilloscopeMode = .Combined,
layout: Layout(&[_]Element{
.{ .id = "viewport" },
.{
.id = "lissajous",
.pane = .{
.width = 0.5,
.height = 0.5,
},
.relative = .{
.id = "viewport",
.self = Pane.Anchor.TopLeft,
.parent = Pane.Anchor.TopLeft,
},
},
.{
.id = "frequency",
.pane = .{
.width = 0.5,
.height = 0.5,
},
.relative = .{
.id = "lissajous",
.self = Pane.Anchor.TopLeft,
.parent = Pane.Anchor.TopRight,
.relative_size = false,
},
},
.{
.id = "oscilloscope",
.pane = .{
.width = 1,
.height = 0.5,
},
.relative = .{
.id = "lissajous",
.self = Pane.Anchor.TopLeft,
.parent = Pane.Anchor.BottomLeft,
.relative_size = false,
},
},
.{
.id = "graph_scale",
.pane = .{
.width = 0.4,
.height = 0.1,
.y = -0.04,
},
.relative = .{
.id = "viewport",
.self = Pane.Anchor.BottomCenter,
.parent = Pane.Anchor.BottomCenter,
.relative_size = false,
},
},
.{
.id = "lissajous_controls",
.pane = .{
.width = 0.2,
.height = 0.1,
.x = -0.04,
.y = 0.04,
},
.relative = .{
.id = "lissajous",
.self = Pane.Anchor.TopRight,
.parent = Pane.Anchor.TopRight,
.relative_size = false,
},
},
}) = .{}, | src/editor.zig |
const std = @import("std");
const pi = std.math.pi;
const cos = std.math.cos;
const sin = std.math.sin;
const glm = @import("glm.zig");
const Mat4 = glm.Mat4;
const Vec3 = glm.Vec3;
const vec3 = glm.vec3;
const lookAt = glm.lookAt;
usingnamespace @import("c.zig");
// Defines several possible options for camera movement. Used as abstraction to stay away from window-system specific input methods
const CameraMovement = enum {
Forward,
Backward,
Left,
Right,
};
// Default camera values
const YAW = -90.0;
const PITCH = 0.0;
const SPEED = 2.5;
const SENSITIVITY = 0.1;
const ZOOM = 45.0;
// An abstract camera class that processes input and calculates the corresponding Euler Angles, Vectors and Matrices for use in OpenGL
pub const Camera = struct {
// Camera Attributes
position: Vec3,
front: Vec3,
up: Vec3,
right: Vec3,
worldUp: Vec3,
// Euler Angles
yaw: f32,
pitch: f32,
// Camera options
movementSpeed: f32,
mouseSensitivity: f32,
zoom: f32,
// Constructor with vectors
pub fn init(position: Vec3, up: Vec3, yaw: f32, pitch: f32) Camera {
var camera = Camera{
.position = position,
.front = vec3(0.0, 0.0, -1.0),
.up = up,
.right = vec3(-1.0, 0.0, 0.0),
.worldUp = up,
.yaw = yaw,
.pitch = pitch,
.movementSpeed = SPEED,
.mouseSensitivity = SENSITIVITY,
.zoom = ZOOM,
};
camera.updateCameraVectors();
return camera;
}
pub fn default() Camera {
var camera = Camera{
.position = vec3(0.0, 0.0, 3.0),
.front = vec3(0.0, 0.0, -1.0),
.up = vec3(0.0, 1.0, 0.0),
.right = vec3(-1.0, 0.0, 0.0),
.worldUp = vec3(0.0, 1.0, 0.0),
.yaw = YAW,
.pitch = PITCH,
.movementSpeed = SPEED,
.mouseSensitivity = SENSITIVITY,
.zoom = ZOOM,
};
camera.updateCameraVectors();
return camera;
}
// Returns the view matrix calculated using Euler Angles and the LookAt Matrix
pub fn getViewMatrix(self: Camera) Mat4 {
return lookAt(self.position, self.position.add(self.front), self.up);
}
// Processes input received from any keyboard-like input system. Accepts input parameter in the form of camera defined ENUM (to abstract it from windowing systems)
pub fn processKeyboard(self: *Camera, direction: CameraMovement, deltaTime: f32) void {
const velocity = self.movementSpeed * deltaTime;
switch (direction) {
.Forward => self.position = self.position.add(self.front.mulScalar(velocity)),
.Backward => self.position = self.position.sub(self.front.mulScalar(velocity)),
.Left => self.position = self.position.sub(self.right.mulScalar(velocity)),
.Right => self.position = self.position.add(self.right.mulScalar(velocity)),
}
}
// Processes input received from a mouse input system. Expects the offset value in both the x and y direction.
pub fn processMouseMovement(self: *Camera, xoffset: f32, yoffset: f32) void {
self.yaw += xoffset * self.mouseSensitivity;
self.pitch += yoffset * self.mouseSensitivity;
// Make sure that when pitch is out of bounds, screen doesn't get flipped
if (self.pitch > 89.0)
self.pitch = 89.0;
if (self.pitch < -89.0)
self.pitch = -89.0;
// Update Front, Right and Up Vectors using the updated Euler angles
self.updateCameraVectors();
}
// Processes input received from a mouse scroll-wheel event. Only requires input on the vertical wheel-axis
pub fn processMouseScroll(self: *Camera, yoffset: f32) void {
if (self.zoom >= 1.0 and self.zoom <= 45.0)
self.zoom -= yoffset;
if (self.zoom <= 1.0)
self.zoom = 1.0;
if (self.zoom >= 45.0)
self.zoom = 45.0;
}
// Calculates the front vector from the Camera's (updated) Euler Angles
fn updateCameraVectors(self: *Camera) void {
// Calculate the new Front vector
var front: Vec3 = undefined;
front.vals[0] = cos(self.yaw / 180.0 * pi) * cos(self.pitch / 180.0 * pi);
front.vals[1] = sin(self.pitch / 180.0 * pi);
front.vals[2] = sin(self.yaw / 180.0 * pi) * cos(self.pitch / 180.0 * pi);
self.front = front.normalize();
// Also re-calculate the Right and Up vector
self.right = self.front.cross(self.worldUp).normalize();
self.up = self.right.cross(self.front).normalize();
}
}; | src/camera.zig |
usingnamespace @import("psptypes.zig");
pub const enum_IOAccessModes = extern enum(c_int) {
FIO_S_IFMT = 61440,
FIO_S_IFLNK = 16384,
FIO_S_IFDIR = 4096,
FIO_S_IFREG = 8192,
FIO_S_ISUID = 2048,
FIO_S_ISGID = 1024,
FIO_S_ISVTX = 512,
FIO_S_IRWXU = 448,
FIO_S_IRUSR = 256,
FIO_S_IWUSR = 128,
FIO_S_IXUSR = 64,
FIO_S_IRWXG = 56,
FIO_S_IRGRP = 32,
FIO_S_IWGRP = 16,
FIO_S_IXGRP = 8,
FIO_S_IRWXO = 7,
FIO_S_IROTH = 4,
FIO_S_IWOTH = 2,
FIO_S_IXOTH = 1,
_,
};
pub const enum_IOFileModes = extern enum(c_int) {
FIO_SO_IFMT = 56,
FIO_SO_IFLNK = 8,
FIO_SO_IFDIR = 16,
FIO_SO_IFREG = 32,
FIO_SO_IROTH = 4,
FIO_SO_IWOTH = 2,
FIO_SO_IXOTH = 1,
_,
};
pub const PSP_O_TRUNC = 0x0400;
pub const PSP_O_RDWR = PSP_O_RDONLY | PSP_O_WRONLY;
pub const PSP_SEEK_END = 2;
pub const PSP_O_EXCL = 0x0800;
pub const PSP_O_RDONLY = 0x0001;
pub const PSP_O_NBLOCK = 0x0004;
pub const PSP_SEEK_CUR = 1;
pub const PSP_O_DIROPEN = 0x0008;
pub const PSP_O_CREAT = 0x0200;
pub const PSP_O_WRONLY = 0x0002;
pub const PSP_O_NOWAIT = 0x8000;
pub const PSP_SEEK_SET = 0;
pub const PSP_O_APPEND = 0x0100;
pub const SceIoStat = extern struct {
st_mode: SceMode,
st_attr: c_uint,
st_size: SceOff,
st_ctime: ScePspDateTime,
st_atime: ScePspDateTime,
st_mtime: ScePspDateTime,
st_private: [6]c_uint,
};
pub const struct_SceIoDirent = extern struct {
d_stat: SceIoStat,
d_name: [256]u8,
d_private: ?*c_void,
dummy: c_int,
};
pub const SceIoDirent = struct_SceIoDirent;
pub const enum_IoAssignPerms = extern enum(c_int) {
IOASSIGN_RDWR = 0,
IOASSIGN_RDONLY = 1,
_,
};
pub extern fn sceIoOpen(file: [*c]const u8, flags: c_int, mode: u32) SceUID;
pub extern fn sceIoOpenAsync(file: [*c]const u8, flags: c_int, mode: u32) SceUID;
pub extern fn sceIoClose(fd: SceUID) c_int;
pub extern fn sceIoCloseAsync(fd: SceUID) c_int;
pub extern fn sceIoRead(fd: SceUID, data: ?*c_void, size: SceSize) c_int;
pub extern fn sceIoReadAsync(fd: SceUID, data: ?*c_void, size: SceSize) c_int;
pub extern fn sceIoWrite(fd: SceUID, data: ?*const c_void, size: SceSize) c_int;
pub extern fn sceIoWriteAsync(fd: SceUID, data: ?*const c_void, size: SceSize) c_int;
pub extern fn sceIoLseek(fd: SceUID, offset: SceOff, whence: c_int) i64;
pub extern fn sceIoLseekAsync(fd: SceUID, offset: SceOff, whence: c_int) c_int;
pub extern fn sceIoLseek32(fd: SceUID, offset: c_int, whence: c_int) c_int;
pub extern fn sceIoLseek32Async(fd: SceUID, offset: c_int, whence: c_int) c_int;
pub extern fn sceIoRemove(file: [*c]const u8) c_int;
pub extern fn sceIoMkdir(dir: [*c]const u8, mode: u32) c_int;
pub extern fn sceIoRmdir(path: [*c]const u8) c_int;
pub extern fn sceIoChdir(path: [*c]const u8) c_int;
pub extern fn sceIoRename(oldname: [*c]const u8, newname: [*c]const u8) c_int;
pub extern fn sceIoDopen(dirname: [*c]const u8) SceUID;
pub extern fn sceIoDread(fd: SceUID, dir: [*c]SceIoDirent) c_int;
pub extern fn sceIoDclose(fd: SceUID) c_int;
pub extern fn sceIoDevctl(dev: [*c]const u8, cmd: c_uint, indata: ?*c_void, inlen: c_int, outdata: ?*c_void, outlen: c_int) c_int;
pub extern fn sceIoAssign(dev1: [*c]const u8, dev2: [*c]const u8, dev3: [*c]const u8, mode: c_int, unk1: ?*c_void, unk2: c_long) c_int;
pub extern fn sceIoUnassign(dev: [*c]const u8) c_int;
pub extern fn sceIoGetstat(file: [*c]const u8, stat: [*c]SceIoStat) c_int;
pub extern fn sceIoChstat(file: [*c]const u8, stat: [*c]SceIoStat, bits: c_int) c_int;
pub extern fn sceIoIoctl(fd: SceUID, cmd: c_uint, indata: ?*c_void, inlen: c_int, outdata: ?*c_void, outlen: c_int) c_int;
pub extern fn sceIoIoctlAsync(fd: SceUID, cmd: c_uint, indata: ?*c_void, inlen: c_int, outdata: ?*c_void, outlen: c_int) c_int;
pub extern fn sceIoSync(device: [*c]const u8, unk: c_uint) c_int;
pub extern fn sceIoWaitAsync(fd: SceUID, res: [*c]SceInt64) c_int;
pub extern fn sceIoWaitAsyncCB(fd: SceUID, res: [*c]SceInt64) c_int;
pub extern fn sceIoPollAsync(fd: SceUID, res: [*c]SceInt64) c_int;
pub extern fn sceIoGetAsyncStat(fd: SceUID, poll: c_int, res: [*c]SceInt64) c_int;
pub extern fn sceIoCancel(fd: SceUID) c_int;
pub extern fn sceIoGetDevType(fd: SceUID) c_int;
pub extern fn sceIoChangeAsyncPriority(fd: SceUID, pri: c_int) c_int;
pub extern fn sceIoSetAsyncCallback(fd: SceUID, cb: SceUID, argp: ?*c_void) c_int;
pub const struct_PspIoDrv = extern struct {
name: [*c]const u8,
dev_type: u32,
unk2: u32,
name2: [*c]const u8,
funcs: [*c]PspIoDrvFuncs,
};
pub const struct_PspIoDrvArg = extern struct {
drv: [*c]struct_PspIoDrv,
arg: ?*c_void,
};
pub const PspIoDrvArg = struct_PspIoDrvArg;
pub const struct_PspIoDrvFileArg = extern struct {
unk1: u32,
fs_num: u32,
drv: [*c]PspIoDrvArg,
unk2: u32,
arg: ?*c_void,
};
pub const PspIoDrvFileArg = struct_PspIoDrvFileArg;
pub const struct_PspIoDrvFuncs = extern struct {
IoInit: ?fn ([*c]PspIoDrvArg) callconv(.C) c_int,
IoExit: ?fn ([*c]PspIoDrvArg) callconv(.C) c_int,
IoOpen: ?fn ([*c]PspIoDrvFileArg, [*c]u8, c_int, SceMode) callconv(.C) c_int,
IoClose: ?fn ([*c]PspIoDrvFileArg) callconv(.C) c_int,
IoRead: ?fn ([*c]PspIoDrvFileArg, [*c]u8, c_int) callconv(.C) c_int,
IoWrite: ?fn ([*c]PspIoDrvFileArg, [*c]const u8, c_int) callconv(.C) c_int,
IoLseek: ?fn ([*c]PspIoDrvFileArg, SceOff, c_int) callconv(.C) SceOff,
IoIoctl: ?fn ([*c]PspIoDrvFileArg, c_uint, ?*c_void, c_int, ?*c_void, c_int) callconv(.C) c_int,
IoRemove: ?fn ([*c]PspIoDrvFileArg, [*c]const u8) callconv(.C) c_int,
IoMkdir: ?fn ([*c]PspIoDrvFileArg, [*c]const u8, SceMode) callconv(.C) c_int,
IoRmdir: ?fn ([*c]PspIoDrvFileArg, [*c]const u8) callconv(.C) c_int,
IoDopen: ?fn ([*c]PspIoDrvFileArg, [*c]const u8) callconv(.C) c_int,
IoDclose: ?fn ([*c]PspIoDrvFileArg) callconv(.C) c_int,
IoDread: ?fn ([*c]PspIoDrvFileArg, [*c]SceIoDirent) callconv(.C) c_int,
IoGetstat: ?fn ([*c]PspIoDrvFileArg, [*c]const u8, [*c]SceIoStat) callconv(.C) c_int,
IoChstat: ?fn ([*c]PspIoDrvFileArg, [*c]const u8, [*c]SceIoStat, c_int) callconv(.C) c_int,
IoRename: ?fn ([*c]PspIoDrvFileArg, [*c]const u8, [*c]const u8) callconv(.C) c_int,
IoChdir: ?fn ([*c]PspIoDrvFileArg, [*c]const u8) callconv(.C) c_int,
IoMount: ?fn ([*c]PspIoDrvFileArg) callconv(.C) c_int,
IoUmount: ?fn ([*c]PspIoDrvFileArg) callconv(.C) c_int,
IoDevctl: ?fn ([*c]PspIoDrvFileArg, [*c]const u8, c_uint, ?*c_void, c_int, ?*c_void, c_int) callconv(.C) c_int,
IoUnk21: ?fn ([*c]PspIoDrvFileArg) callconv(.C) c_int,
};
pub const PspIoDrvFuncs = struct_PspIoDrvFuncs;
pub const PspIoDrv = struct_PspIoDrv;
pub extern fn sceIoAddDrv(drv: [*c]PspIoDrv) c_int;
pub extern fn sceIoDelDrv(drv_name: [*c]const u8) c_int;
pub extern fn sceIoReopen(file: [*c]const u8, flags: c_int, mode: SceMode, fd: SceUID) c_int;
pub extern fn sceIoGetThreadCwd(uid: SceUID, dir: [*c]u8, len: c_int) c_int;
pub extern fn sceIoChangeThreadCwd(uid: SceUID, dir: [*c]u8) c_int;
pub const IOAccessModes = enum_IOAccessModes;
pub const IOFileModes = enum_IOFileModes;
pub const IoAssignPerms = enum_IoAssignPerms; | src/psp/sdk/pspiofilemgr.zig |
const aoc = @import("../aoc.zig");
const std = @import("std");
const Reindeer = struct {
speed: u16, flying_duration: u16, resting_duration: u16,
time_just_flew: u16 = 0, time_just_rested: u16 = 0,
distance_flown: u16 = 0, points: u16 = 0,
fn tick(self: *Reindeer) void {
if (self.time_just_flew == self.flying_duration) {
self.time_just_rested += 1;
if (self.time_just_rested == self.resting_duration) {
self.time_just_flew = 0;
self.time_just_rested = 0;
}
}
else {
self.distance_flown += self.speed;
self.time_just_flew += 1;
}
}
};
pub fn run(problem: *aoc.Problem) !aoc.Solution {
var reindeer_buf: [16]Reindeer = undefined;
var reindeer_size: u8 = 0;
while (problem.line()) |line| {
var tokens = std.mem.tokenize(u8, line, " ");
_ = tokens.next().?; _ = tokens.next().?; _ = tokens.next().?;
const speed = try std.fmt.parseInt(u16, tokens.next().?, 10);
_ = tokens.next().?; _ = tokens.next().?;
const duration = try std.fmt.parseInt(u16, tokens.next().?, 10);
_ = tokens.next().?; _ = tokens.next().?; _ = tokens.next().?; _ = tokens.next().?; _ = tokens.next().?; _ = tokens.next().?;
const rest = try std.fmt.parseInt(u16, tokens.next().?, 10);
reindeer_buf[reindeer_size] = Reindeer { .speed = speed, .flying_duration = duration, .resting_duration = rest };
reindeer_size += 1;
}
var time: u16 = 0;
var furthest: u16 = 0;
var most_points: u16 = 0;
while (time < 2503) : (time += 1) {
for (reindeer_buf[0..reindeer_size]) |*reindeer| {
reindeer.tick();
furthest = std.math.max(furthest, reindeer.distance_flown);
}
for (reindeer_buf[0..reindeer_size]) |*reindeer| {
if (reindeer.distance_flown == furthest) {
reindeer.points += 1;
most_points = std.math.max(most_points, reindeer.points);
}
}
}
return problem.solution(furthest, most_points);
} | src/main/zig/2015/day14.zig |
const std = @import("std");
const FixedBufferAllocator = std.heap.FixedBufferAllocator;
// ----------------------------------------------------------------------------
const arm_m = @import("../drivers/arm_m.zig");
const arm_cmse = @import("../drivers/arm_cmse.zig");
// ----------------------------------------------------------------------------
const shadowstack = @import("shadowstack.zig");
const shadowexcstack = @import("shadowexcstack.zig");
const ffi = @import("ffi.zig");
const log = @import("debug.zig").log;
// ----------------------------------------------------------------------------
var arena: [8192]u8 = undefined;
var fixed_allocator: FixedBufferAllocator = undefined;
const allocator = &fixed_allocator.allocator;
const NonSecureThread = struct {
exc_stack_state: shadowexcstack.StackState,
stack_state: shadowstack.StackState,
secure_psp: usize,
secure_psp_limit: usize,
};
var threads = [1]?*NonSecureThread{null} ** 64;
var next_free_thread: u8 = undefined;
var cur_thread: u8 = 0;
var default_thread: NonSecureThread = undefined;
pub fn init() void {
fixed_allocator = FixedBufferAllocator.init(&arena);
for (threads) |*thread| {
thread.* = null;
}
next_free_thread = 1;
// Default thread
cur_thread = 0;
default_thread.stack_state = shadowstack.StackState.new(allocator, null) catch
@panic("allocation of a default shadow stack failed");
default_thread.secure_psp_limit = arm_m.getPspLimit();
threads[0] = &default_thread;
shadowstack.loadState(&default_thread.stack_state);
}
const CreateThreadError = error{OutOfMemory};
fn createThread(create_info: *const ffi.TCThreadCreateInfo) CreateThreadError!ffi.TCThread {
if (@as(usize, next_free_thread) >= threads.len) {
return error.OutOfMemory;
}
arm_m.setFaultmask();
defer arm_m.clearFaultmask();
const thread_id = @as(usize, next_free_thread);
const thread_info = try allocator.create(NonSecureThread);
errdefer allocator.destroy(thread_info);
const exc_stack_state = try shadowexcstack.StackState.new(allocator, create_info);
errdefer exc_stack_state.destroy(allocator);
thread_info.exc_stack_state = exc_stack_state;
const stack_state = try shadowstack.StackState.new(allocator, create_info);
errdefer stack_state.destroy(allocator);
thread_info.stack_state = stack_state;
// Allocate a secure stack for the new thread. The size is a rough guess
// that should be enough for holding a single exception frame and a bounded,
// reasonable number of stack frames.
const StackType = [256]u8;
const stack_alignment = 8;
const stack = try allocator.alignedAlloc(StackType, stack_alignment, 1);
errdefer allocator.free(stack);
thread_info.secure_psp = @ptrToInt(&stack[0][0]) + stack[0].len;
thread_info.secure_psp_limit = @ptrToInt(&stack[0][0]);
// Commit the update
next_free_thread += 1;
threads[thread_id] = thread_info;
log(.Trace, "createThread({}) → id = {}, info = {}\r\n", .{ create_info, thread_id, thread_info });
return thread_id;
}
const ActivateThreadError = error{
BadThread,
ThreadMode,
};
fn activateThread(thread: ffi.TCThread) ActivateThreadError!void {
// Cannot switch contexts in Thread mode. We cannot switch secure process
// stacks while they are in use, not to mention that switching contexts
// in Thread mode is a weird thing to do.
if (!arm_m.isHandlerMode()) {
return error.ThreadMode;
}
arm_m.setFaultmask();
defer arm_m.clearFaultmask();
// This is probably faster than proper bounds checking
const new_thread_id = @as(usize, thread) & (threads.len - 1);
const new_thread = threads[new_thread_id] orelse return error.BadThread;
const old_thread_id = @as(usize, cur_thread);
const old_thread = threads[old_thread_id].?;
log(.Trace, "activateThread({} → {})\r\n", .{ old_thread_id, new_thread_id });
shadowexcstack.saveState(&old_thread.exc_stack_state);
shadowexcstack.loadState(&new_thread.exc_stack_state);
shadowstack.saveState(&old_thread.stack_state);
shadowstack.loadState(&new_thread.stack_state);
old_thread.secure_psp = arm_m.getPsp();
arm_m.setPsp(new_thread.secure_psp);
arm_m.setPspLimit(new_thread.secure_psp_limit);
cur_thread = @truncate(u8, new_thread_id);
}
// Non-Secure application interface
// ----------------------------------------------------------------------------
fn TCReset(_1: usize, _2: usize, _3: usize, _4: usize) callconv(.C) usize {
init();
return 0;
}
fn TCCreateThread(raw_p_create_info: usize, raw_p_thread: usize, _3: usize, _4: usize) callconv(.C) usize {
// Check Non-Secure pointers
const p_create_info = arm_cmse.checkObject(ffi.TCThreadCreateInfo, raw_p_create_info, arm_cmse.CheckOptions{}) catch |err| {
return ffi.TC_RESULT.ERROR_UNPRIVILEGED;
};
const p_thread = arm_cmse.checkObject(ffi.TCThread, raw_p_thread, arm_cmse.CheckOptions{ .readwrite = true }) catch |err| {
return ffi.TC_RESULT.ERROR_UNPRIVILEGED;
};
const create_info = p_create_info.*;
const thread = createThread(&create_info) catch |err| switch (err) {
error.OutOfMemory => return ffi.TC_RESULT.ERROR_OUT_OF_MEMORY,
};
p_thread.* = thread;
return ffi.TC_RESULT.SUCCESS;
}
fn TCLockdown(_1: usize, _2: usize, _3: usize, _4: usize) callconv(.C) usize {
@panic("unimplemented");
}
fn TCActivateThread(thread: usize, _2: usize, _3: usize, _4: usize) callconv(.C) usize {
activateThread(thread) catch |err| switch (err) {
error.BadThread => return ffi.TC_RESULT.ERROR_INVALID_ARGUMENT,
error.ThreadMode => return ffi.TC_RESULT.ERROR_INVALID_OPERATION,
};
return ffi.TC_RESULT.SUCCESS;
}
comptime {
arm_cmse.exportNonSecureCallable("TCReset", TCReset);
arm_cmse.exportNonSecureCallable("TCCreateThread", TCCreateThread);
arm_cmse.exportNonSecureCallable("TCLockdown", TCLockdown);
arm_cmse.exportNonSecureCallable("TCActivateThread", TCActivateThread);
} | src/monitor/threads.zig |
const std = @import("std");
const main = @import("main.zig");
const bufwriter = @import("bufwriter.zig");
const utils = @import("utils.zig");
const printPrettify = utils.printPrettify;
const testing = std.testing;
const debug = std.debug.print;
const dif = @import("dif.zig");
const DifNode = dif.DifNode;
const DifNodeMap = std.StringHashMap(ial.Entry(DifNode));
const ial = @import("indexedarraylist.zig");
const RenderError = error{
UnexpectedType,
NoSuchNode,
NoSuchEdge,
NoSuchInstance,
OutOfMemory,
};
/// Pre-populated sets of indexes to the different types of difnodes
pub const DifNodeMapSet = struct {
node_map: *DifNodeMap,
edge_map: *DifNodeMap,
instance_map: *DifNodeMap,
group_map: *DifNodeMap,
};
pub fn DotContext(comptime Writer: type) type {
return struct {
const Self = @This();
writer: Writer,
pub fn init(writer: Writer) Self {
return Self{
.writer = writer,
};
}
fn findUnit(node: *ial.Entry(dif.DifNode)) !*ial.Entry(dif.DifNode) {
var current = node;
while (current.get().node_type != .Unit) {
if (current.get().parent) |*parent| {
current = parent;
} else {
// Ending up here is a bug
return error.NoUnitFound;
}
}
return current;
}
inline fn print(self: *Self, comptime fmt: []const u8, args: anytype) !void {
try self.writer.print(fmt, args);
}
fn printError(self: *Self, node: *ial.Entry(dif.DifNode), comptime fmt: []const u8, args: anytype) void {
_ = self;
const err_writer = std.io.getStdErr().writer();
const unit = findUnit(node) catch {
err_writer.print("BUG: Could not find unit associated with node\n", .{}) catch {};
// TODO: Don't have to unreach here - can continue to render anything but the filename and source chunk
unreachable;
};
const src_buf = unit.get().data.Unit.src_buf;
const lc = utils.idxToLineCol(src_buf, node.get().initial_token.?.start);
err_writer.print("{s}:{d}:{d}: error: ", .{ unit.get().name.?, lc.line, lc.col }) catch {};
err_writer.print(fmt, args) catch {};
err_writer.print("\n", .{}) catch {};
utils.dumpSrcChunkRef(@TypeOf(err_writer), err_writer, src_buf, node.get().initial_token.?.start);
err_writer.print("\n", .{}) catch {};
// Print ^ at start of symbol
err_writer.writeByteNTimes(' ', lc.col-1) catch {};
err_writer.print("^\n", .{}) catch {};
}
};
}
fn renderInstantiation(comptime Writer: type, ctx: *DotContext(Writer), instance_ref: *ial.Entry(DifNode)) anyerror!void {
// Early opt out / safeguard. Most likely a bug
const instance = instance_ref.get();
if (instance.node_type != .Instantiation) {
return RenderError.UnexpectedType;
}
//
// Get all parameters of source, target and edge.
//
// This assumes the graph is well-formed at this point. TODO: Create duplicate graph from the Dif without optionals
var params_instance = instance.data.Instantiation.params;
var node = instance.data.Instantiation.node_type_ref.?.get();
var params_node = node.data.Node.params;
//
// Generate the dot output
//
// Print node name and start attr-list
try ctx.print("\"{s}\"[", .{instance.name});
// Compose label
{
try ctx.print("label=\"", .{});
// Instance-name/label
if (params_instance.label) |label| {
try ctx.print("{s}", .{label});
} else if (instance.name) |name| {
try printPrettify(Writer, ctx.writer, name, .{ .do_caps = true });
}
// Node-type-name/label
if (params_node.label orelse node.name) |node_label| {
try ctx.print("\n{s}", .{node_label});
}
try ctx.print("\",", .{});
}
// Shape
if (params_instance.shape orelse params_node.shape) |shape| {
try ctx.print("shape=\"{s}\",", .{shape});
}
// Foreground
if (params_instance.fgcolor orelse params_node.fgcolor) |fgcolor| {
try ctx.print("fontcolor=\"{0s}\",", .{fgcolor});
}
// Background
if (params_instance.bgcolor orelse params_node.bgcolor) |bgcolor| {
try ctx.print("style=filled,bgcolor=\"{0s}\",fillcolor=\"{0s}\",", .{bgcolor});
}
// end attr-list/node
try ctx.print("];\n", .{});
// Check for note:
if (params_instance.note) |note| {
var note_idx = instance_ref.idx;
try ctx.print(
\\note_{0x}[label="{1s}",style=filled,fillcolor="#ffffaa",shape=note];
\\note_{0x} -> "{2s}"[arrowtail=none,arrowhead=none,style=dashed];
\\
, .{ note_idx, note, instance.name });
}
}
fn renderRelationship(comptime Writer: type, ctx: *DotContext(Writer), instance_ref: *ial.Entry(DifNode)) anyerror!void {
// Early opt out / safeguard. Most likely a bug
const instance = instance_ref.get();
if (instance.node_type != .Relationship) {
return RenderError.UnexpectedType;
}
//
// Get all parameters of source, target and edge.
//
// This assumes the graph is well-formed at this point. TODO: Create duplicate graph from the Dif without optionals
var node_source = instance.data.Relationship.source_ref.?.get();
var node_target = instance.data.Relationship.target_ref.?.get();
var edge = instance.data.Relationship.edge_ref.?.get();
var params_instance = instance.data.Relationship.params;
var params_edge = edge.data.Edge.params;
//
// Generate the dot output
//
try ctx.print("\"{s}\" -> \"{s}\"[", .{ node_source.name, node_target.name });
// Label
if (params_instance.label orelse params_edge.label) |label| {
try ctx.print("label=\"{s}\",", .{label});
} else {
if (edge.name) |label| {
try ctx.print("label=\"", .{});
try printPrettify(Writer, ctx.writer, label, .{});
try ctx.print("\",", .{});
}
}
// if source is group:
if (node_source.node_type == .Group) {
try ctx.print("ltail=cluster_{s},", .{node_source.name.?});
}
// if target is group:
if (node_target.node_type == .Group) {
try ctx.print("lhead=cluster_{s},", .{node_target.name.?});
}
// Style
var edge_style = params_instance.edge_style orelse params_edge.edge_style orelse dif.EdgeStyle.solid;
// Start edge
try ctx.print("style=\"{s}\",", .{std.meta.tagName(edge_style)});
try ctx.print("dir=both,", .{});
if (params_instance.source_symbol orelse params_edge.source_symbol) |source_symbol| {
var arrow = switch (source_symbol) {
.arrow_open => "vee",
.arrow_closed => "onormal",
.arrow_filled => "normal",
.none => "none",
};
try ctx.print("arrowtail={s},", .{arrow});
} else {
try ctx.print("arrowtail=none,", .{});
}
// End edge
if (params_instance.target_symbol orelse params_edge.target_symbol) |target_symbol| {
var arrow = switch (target_symbol) {
.arrow_open => "vee",
.arrow_closed => "onormal",
.arrow_filled => "normal",
.none => "none",
};
try ctx.print("arrowhead={s},", .{arrow});
} else {
try ctx.print("arrowhead=normal,", .{});
}
try ctx.print("];\n", .{});
}
/// Recursive
/// TODO: Specify which node-types to render? To e.g. render only nodes, groups, notes (and note-edges) - or only edges
fn renderGeneration(comptime Writer: type, ctx: *DotContext(Writer), instance: *ial.Entry(DifNode)) anyerror!void {
var node = instance;
// Iterate over siblings
while (true) {
switch (node.get().node_type) {
.Unit => {
if (node.get().first_child) |*child| {
try renderGeneration(Writer, ctx, child);
}
},
.Instantiation => {
try renderInstantiation(Writer, ctx, node);
},
.Relationship => {
try renderRelationship(Writer, ctx, node);
},
.Group => {
// Recurse on groups
if (node.get().first_child) |*child| {
try ctx.print("subgraph cluster_{s} {{\n", .{node.get().name});
// Invisible point inside group, used to create edges to/from groups
try ctx.print("{s} [shape=point,style=invis,height=0,width=0];", .{node.get().name});
try renderGeneration(Writer, ctx, child);
try ctx.print("}}\n", .{});
// Checking group-fields in case of note, which shall be created outside of group
var params_group = node.get().data.Group.params;
// Check for note:
if (params_group.note) |note| {
var note_idx = instance.idx;
try ctx.print(
\\note_{0x}[label="{1s}",style=filled,fillcolor="#ffffaa",shape=note];
\\note_{0x} -> {2s}[lhead=cluster_{2s},arrowtail=none,arrowhead=none,style=dashed];
\\
, .{ note_idx, note, node.get().name });
}
}
},
else => {},
}
if (node.get().next_sibling) |*next| {
node = next;
} else {
break;
}
}
// Group-level attributes
if(instance.get().parent) |*parent| {
const maybe_params_group: ?dif.GroupParams = switch(parent.get().data) {
.Group => |el| el.params,
.Unit => |el| el.params,
else => null
};
if(maybe_params_group) |params_group| {
if (params_group.label) |label| {
try ctx.print("label=\"{s}\";labelloc=\"t\";\n", .{label});
}
if (params_group.layout) |layout| {
try ctx.print("layout=\"{s}\";\n", .{layout});
}
}
}
}
pub fn difToDot(comptime Writer: type, ctx: *DotContext(Writer), root_node: *ial.Entry(DifNode)) !void {
try ctx.print("strict digraph {{\ncompound=true;\n", .{});
try renderGeneration(Writer, ctx, root_node);
try ctx.print("}}\n", .{});
}
test "writeNodeFields" {
// Go through each fields and verify that it gets converted as expected
var buf: [1024]u8 = undefined;
var buf_context = bufwriter.ArrayBuf{ .buf = buf[0..] };
var writer = buf_context.writer();
const source =
\\node MyNode {
\\ label="My label";
\\ fgcolor="#000000";
\\ bgcolor="#FF0000";
\\}
\\Node: MyNode;
\\
;
try main.dayaToDot(std.testing.allocator, bufwriter.ArrayBufWriter, writer, source, "test");
// Check that certain strings actually gets converted. It might not be 100% correct, but is intended to catch that
// basic flow of logic is happening
try testing.expect(std.mem.indexOf(u8, buf_context.slice(), "\"Node\"") != null);
try testing.expect(std.mem.indexOf(u8, buf_context.slice(), "My label") != null);
try testing.expect(std.mem.indexOf(u8, buf_context.slice(), "bgcolor=\"#FF0000\"") != null);
try testing.expect(std.mem.indexOf(u8, buf_context.slice(), "color=\"#000000\"") != null);
}
test "writeRelationshipFields" {
// Go through each fields and verify that it gets converted as expected
var buf: [1024]u8 = undefined;
var context = bufwriter.ArrayBuf{ .buf = buf[0..] };
var writer = context.writer();
const source =
\\node MyNode {}
\\edge Uses {
\\ label="Edge label";
\\ source_symbol=arrow_filled;
\\ target_symbol=arrow_open;
\\}
\\NodeA: MyNode;
\\NodeB: MyNode;
\\NodeA Uses NodeB;
\\
;
try main.dayaToDot(std.testing.allocator, bufwriter.ArrayBufWriter, writer, source, "test");
// Check that certain strings actually gets converted. It might not be 100% correct, but is intended to catch that
// basic flow of logic is happening
try testing.expect(std.mem.indexOf(u8, context.slice(), "Edge label") != null);
try testing.expect(std.mem.indexOf(u8, context.slice(), "arrowhead=vee") != null);
try testing.expect(std.mem.indexOf(u8, context.slice(), "arrowtail=normal") != null);
} | libdaya/src/dot.zig |
const bench = @import("bench");
const std = @import("std");
const builtin = std.builtin;
const debug = std.debug;
const heap = std.heap;
const mem = std.mem;
const testing = std.testing;
pub const GcAllocator = struct {
const PointerList = std.ArrayList(Pointer);
start: [*]const u8,
ptrs: PointerList,
const Self = @This();
const Flags = packed struct {
checked: bool,
marked: bool,
const zero = Flags{
.checked = false,
.marked = false,
};
};
const Pointer = struct {
flags: Flags,
memory: []u8,
};
pub inline fn init(child_alloc: mem.Allocator) Self {
return GcAllocator{
.start = @intToPtr([*]const u8, @frameAddress()),
.ptrs = PointerList.init(child_alloc),
};
}
pub fn deinit(gc: *Self) void {
const child_alloc = gc.childAllocator();
for (gc.ptrs.items) |ptr| {
child_alloc.free(ptr.memory);
}
gc.ptrs.deinit();
gc.* = undefined;
}
pub fn collect(gc: *Self) void {
@call(.{ .modifier = .never_inline }, collectNoInline, .{gc});
}
pub fn collectFrame(gc: *Self, frame: []const u8) void {
gc.mark(frame);
gc.sweep();
}
pub fn allocator(gc: *Self) mem.Allocator {
return mem.Allocator.init(gc, Self.allocFn, Self.resizeFn, Self.freeFn);
}
fn collectNoInline(gc: *GcAllocator) void {
const frame = blk: {
const end = @intToPtr([*]const u8, @frameAddress());
const i_start = @ptrToInt(gc.start);
const i_end = @ptrToInt(end);
if (i_start < i_end)
break :blk gc.start[0 .. i_end - i_start];
break :blk end[0 .. i_start - i_end];
};
gc.collectFrame(frame);
}
fn mark(gc: *GcAllocator, frame: []const u8) void {
const ptr_size = @sizeOf(*u8);
for ([_]void{{}} ** ptr_size) |_, i| {
if (frame.len <= i)
break;
const frame2 = frame[i..];
const len = (frame2.len / ptr_size) * ptr_size;
for (std.mem.bytesAsSlice([*]u8, frame2[0..len])) |frame_ptr| {
const ptr = gc.findPtr(frame_ptr) orelse continue;
if (ptr.flags.checked)
continue;
ptr.flags.marked = true;
ptr.flags.checked = true;
gc.mark(ptr.memory);
}
}
}
fn sweep(gc: *GcAllocator) void {
const ptrs = gc.ptrs.items;
var i: usize = 0;
while (i < gc.ptrs.items.len) {
const ptr = &ptrs[i];
if (ptr.flags.marked) {
ptr.flags = Flags.zero;
i += 1;
continue;
}
gc.freePtr(ptr);
}
}
fn findPtr(gc: *GcAllocator, to_find_ptr: anytype) ?*Pointer {
comptime debug.assert(@typeInfo(@TypeOf(to_find_ptr)) == builtin.TypeId.Pointer);
for (gc.ptrs.items) |*ptr| {
const ptr_start = @ptrToInt(ptr.memory.ptr);
const ptr_end = ptr_start + ptr.memory.len;
if (ptr_start <= @ptrToInt(to_find_ptr) and @ptrToInt(to_find_ptr) < ptr_end)
return ptr;
}
return null;
}
fn freePtr(gc: *Self, ptr: *Pointer) void {
const child_alloc = gc.childAllocator();
child_alloc.free(ptr.memory);
// Swap the just freed pointer with the last pointer in the list.
ptr.* = undefined;
ptr.* = gc.ptrs.popOrNull() orelse undefined;
}
fn childAllocator(gc: *Self) mem.Allocator {
return gc.ptrs.allocator;
}
pub fn alloc(self: *Self, comptime T: type, n: usize) mem.Allocator.Error![]T {
return try self.allocator().alloc(T, n);
}
pub fn free(self: *Self, bytes: anytype) void {
if (comptime std.meta.trait.isManyItemPtr(@TypeOf(bytes))) {
const ptr = self.findPtr(bytes) orelse @panic("Freeing memory not allocated by garbage collector!");
self.freePtr(ptr);
} else if (comptime std.meta.trait.isSlice(@TypeOf(bytes))) {
const ptr = self.findPtr(bytes.ptr) orelse @panic("Freeing memory not allocated by garbage collector!");
self.freePtr(ptr);
} else {
@compileError("GcAllocator.free only support many item pointers and slices");
}
}
pub fn create(self: *Self, comptime T: type) mem.Allocator.Error!*T {
return try self.allocator().create(T);
}
pub fn destroy(self: *Self, ptr: anytype) void {
self.allocator().destroy(ptr);
}
pub fn dupe(self: *Self, comptime T: type, src: []const T) mem.Allocator.Error![]T {
return try self.allocator().dupe(T, src);
}
pub fn dupeZ(self: *Self, comptime T: type, src: []const T) mem.Allocator.Error![]T {
return try self.allocator().dupeZ(T, src);
}
fn freeFn(self: *Self, bytes: []u8, buf_align: u29, ret_addr: usize) void {
_ = ret_addr;
_ = buf_align;
self.free(bytes);
}
fn allocFn(
self: *Self,
len: usize,
ptr_align: u29,
len_align: u29,
ret_addr: usize,
) mem.Allocator.Error![]u8 {
const child_alloc = self.childAllocator();
const memory = child_alloc.rawAlloc(len, ptr_align, len_align, ret_addr) catch blk: {
self.collect();
break :blk try child_alloc.rawAlloc(len, ptr_align, len_align, ret_addr);
};
try self.ptrs.append(Pointer{
.flags = Flags.zero,
.memory = memory,
});
return memory;
}
fn resizeFn(
self: *Self,
buf: []u8,
buf_align: u29,
new_len: usize,
len_align: u29,
ret_addr: usize,
) ?usize {
_ = ret_addr;
_ = len_align;
_ = buf_align;
if (new_len == 0) {
self.free(buf);
return null;
}
if (new_len > buf.len) {
var ptr = self.findPtr(buf.ptr) orelse return null;
return self.childAllocator().rawResize(ptr.memory, buf_align, new_len, len_align, ret_addr);
}
return new_len;
}
};
const Leaker = struct {
l: *Leaker,
};
var test_buf: [1024 * 1024]u8 = undefined;
test "gc.collect: No leaks" {
var fba = heap.FixedBufferAllocator.init(test_buf[0..]);
var gc = GcAllocator.init(fba.allocator());
defer gc.deinit();
const allocator = gc.allocator();
var a = try allocator.create(Leaker);
a.* = Leaker{ .l = try allocator.create(Leaker) };
a.l.l = a;
gc.collect();
try testing.expect(gc.findPtr(a) != null);
try testing.expect(gc.findPtr(a.l) != null);
try testing.expectEqual(@as(usize, 2), gc.ptrs.items.len);
}
fn leak(allocator: mem.Allocator) !void {
var a = try allocator.create(Leaker);
a.* = Leaker{ .l = try allocator.create(Leaker) };
a.l.l = a;
}
test "gc.collect: Leaks" {
var fba = heap.FixedBufferAllocator.init(test_buf[0..]);
var gc = GcAllocator.init(fba.allocator());
defer gc.deinit();
const allocator = gc.allocator();
var a = try allocator.create(Leaker);
a.* = Leaker{ .l = try allocator.create(Leaker) };
a.l.l = a;
try @call(.{ .modifier = .never_inline }, leak, .{allocator});
gc.collect();
try testing.expect(gc.findPtr(a) != null);
try testing.expect(gc.findPtr(a.l) != null);
try testing.expectEqual(@as(usize, 2), gc.ptrs.items.len);
}
test "gc.free" {
var fba = heap.FixedBufferAllocator.init(test_buf[0..]);
var gc = GcAllocator.init(fba.allocator());
defer gc.deinit();
const allocator = gc.allocator();
var a = try allocator.create(Leaker);
var b = try allocator.create(Leaker);
allocator.destroy(b);
try testing.expect(gc.findPtr(a) != null);
try testing.expectEqual(@as(usize, 1), gc.ptrs.items.len);
}
test "gc.benchmark" {
try bench.benchmark(struct {
const Arg = struct {
num: usize,
size: usize,
fn benchAllocator(a: Arg, allocator: mem.Allocator, comptime free: bool) !void {
var i: usize = 0;
while (i < a.num) : (i += 1) {
const bytes = try allocator.alloc(u8, a.size);
defer if (free) allocator.free(bytes);
}
}
};
pub const args = [_]Arg{
Arg{ .num = 10 ^ 4, .size = 1 },
Arg{ .num = 10 ^ 4, .size = 256 },
Arg{ .num = 10 ^ 4, .size = 4096 },
Arg{ .num = 10 ^ 6, .size = 1 },
Arg{ .num = 10 ^ 8, .size = 1 },
Arg{ .num = 10 ^ 8, .size = 2 },
};
pub const iterations = 10000;
pub fn FixedBufferAllocator(a: Arg) void {
var fba = heap.FixedBufferAllocator.init(test_buf[0..]);
a.benchAllocator(fba.allocator(), false) catch unreachable;
}
pub fn Arena_FixedBufferAllocator(a: Arg) void {
var fba = heap.FixedBufferAllocator.init(test_buf[0..]);
var arena = heap.ArenaAllocator.init(fba.allocator());
defer arena.deinit();
a.benchAllocator(arena.allocator(), false) catch unreachable;
}
pub fn GcAllocator_FixedBufferAllocator(a: Arg) void {
var fba = heap.FixedBufferAllocator.init(test_buf[0..]);
var gc = GcAllocator.init(fba.allocator());
defer gc.deinit();
a.benchAllocator(gc.allocator(), false) catch unreachable;
gc.collect();
}
pub fn PageAllocator(a: Arg) void {
const pa = heap.page_allocator;
a.benchAllocator(pa, true) catch unreachable;
}
pub fn Arena_PageAllocator(a: Arg) void {
const pa = heap.page_allocator;
var arena = heap.ArenaAllocator.init(pa);
defer arena.deinit();
a.benchAllocator(arena.allocator(), false) catch unreachable;
}
pub fn GcAllocator_PageAllocator(a: Arg) void {
const pa = heap.page_allocator;
var gc = GcAllocator.init(pa);
defer gc.deinit();
a.benchAllocator(gc.allocator(), false) catch unreachable;
gc.collect();
}
});
} | gc.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const print = std.debug.print;
const FieldName = enum(usize) {
byr,
iyr,
eyr,
hgt,
hcl,
ecl,
pid,
cid,
};
fn yearInRange(y: ?usize, min: usize, max: usize) bool {
return y != null and y.? >= min and y.? <= max;
}
fn heightValid(hgt: []const u8) !bool {
const n = std.fmt.parseUnsigned(usize, hgt[0 .. hgt.len - 2], 10) catch return false;
const unit = hgt[hgt.len - 2 ..];
return if (std.mem.eql(u8, unit, "cm"))
n >= 150 and n <= 193
else if (std.mem.eql(u8, unit, "in"))
n >= 59 and n <= 76
else
error.OhNoDude;
}
const EyeColor = enum {
amb,
blu,
brn,
gry,
grn,
hzl,
oth,
};
pub fn main() !void {
var lines = std.mem.split(@embedFile("../inputs/day04.txt"), "\n\n");
var count: usize = 0;
outer: while (lines.next()) |line| {
var found = [_]bool{false} ** std.meta.fields(FieldName).len;
var fields = std.mem.tokenize(line, " \r\n");
while (fields.next()) |f| {
const colon = std.mem.indexOf(u8, f, ":").?;
const val = std.mem.trim(u8, f[colon + 1 ..], &std.ascii.spaces);
const fieldName = std.meta.stringToEnum(FieldName, f[0..colon]).?;
const fieldValid = switch (fieldName) {
.byr => val.len == 4 and yearInRange(try std.fmt.parseUnsigned(usize, val, 10), 1920, 2002),
.iyr => val.len == 4 and yearInRange(try std.fmt.parseUnsigned(usize, val, 10), 2010, 2020),
.eyr => val.len == 4 and yearInRange(try std.fmt.parseUnsigned(usize, val, 10), 2020, 2030),
.hgt => try heightValid(val),
.hcl => val.len == 7 and val[0] == '#' and blk: for (val[1..]) |c| {
if (!((c >= '0' and c <= '9') or (c >= 'a' and c <= 'f'))) break :blk false;
} else true,
.ecl => std.meta.stringToEnum(EyeColor, val) != null,
.pid => val.len == 9 and blk: for (val[1..]) |c| {
if (c < '0' or c > '9') break :blk false;
} else true,
.cid => true,
};
found[@enumToInt(fieldName)] = true;
if (!fieldValid) continue :outer;
}
const valid = blk: for (found[0 .. found.len - 1]) |b| {
if (!b) break :blk false;
} else true;
if (valid) count += 1;
}
print("valid count: {}\n", .{count});
} | src/day04.zig |
pub const WINHTTP_FLAG_ASYNC = @as(u32, 268435456);
pub const WINHTTP_FLAG_SECURE_DEFAULTS = @as(u32, 805306368);
pub const SECURITY_FLAG_IGNORE_UNKNOWN_CA = @as(u32, 256);
pub const SECURITY_FLAG_IGNORE_CERT_DATE_INVALID = @as(u32, 8192);
pub const SECURITY_FLAG_IGNORE_CERT_CN_INVALID = @as(u32, 4096);
pub const SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE = @as(u32, 512);
pub const WINHTTP_AUTOPROXY_AUTO_DETECT = @as(u32, 1);
pub const WINHTTP_AUTOPROXY_CONFIG_URL = @as(u32, 2);
pub const WINHTTP_AUTOPROXY_HOST_KEEPCASE = @as(u32, 4);
pub const WINHTTP_AUTOPROXY_HOST_LOWERCASE = @as(u32, 8);
pub const WINHTTP_AUTOPROXY_ALLOW_AUTOCONFIG = @as(u32, 256);
pub const WINHTTP_AUTOPROXY_ALLOW_STATIC = @as(u32, 512);
pub const WINHTTP_AUTOPROXY_ALLOW_CM = @as(u32, 1024);
pub const WINHTTP_AUTOPROXY_RUN_INPROCESS = @as(u32, 65536);
pub const WINHTTP_AUTOPROXY_RUN_OUTPROCESS_ONLY = @as(u32, 131072);
pub const WINHTTP_AUTOPROXY_NO_DIRECTACCESS = @as(u32, 262144);
pub const WINHTTP_AUTOPROXY_NO_CACHE_CLIENT = @as(u32, 524288);
pub const WINHTTP_AUTOPROXY_NO_CACHE_SVC = @as(u32, 1048576);
pub const WINHTTP_AUTOPROXY_SORT_RESULTS = @as(u32, 4194304);
pub const WINHTTP_AUTO_DETECT_TYPE_DHCP = @as(u32, 1);
pub const WINHTTP_AUTO_DETECT_TYPE_DNS_A = @as(u32, 2);
pub const NETWORKING_KEY_BUFSIZE = @as(u32, 128);
pub const WINHTTP_PROXY_TYPE_DIRECT = @as(u32, 1);
pub const WINHTTP_PROXY_TYPE_PROXY = @as(u32, 2);
pub const WINHTTP_PROXY_TYPE_AUTO_PROXY_URL = @as(u32, 4);
pub const WINHTTP_PROXY_TYPE_AUTO_DETECT = @as(u32, 8);
pub const WINHTTP_REQUEST_STAT_FLAG_TCP_FAST_OPEN = @as(u32, 1);
pub const WINHTTP_REQUEST_STAT_FLAG_TLS_SESSION_RESUMPTION = @as(u32, 2);
pub const WINHTTP_REQUEST_STAT_FLAG_TLS_FALSE_START = @as(u32, 4);
pub const WINHTTP_REQUEST_STAT_FLAG_PROXY_TLS_SESSION_RESUMPTION = @as(u32, 8);
pub const WINHTTP_REQUEST_STAT_FLAG_PROXY_TLS_FALSE_START = @as(u32, 16);
pub const WINHTTP_REQUEST_STAT_FLAG_FIRST_REQUEST = @as(u32, 32);
pub const WINHTTP_MATCH_CONNECTION_GUID_FLAG_REQUIRE_MARKED_CONNECTION = @as(u32, 1);
pub const WINHTTP_MATCH_CONNECTION_GUID_FLAGS_MASK = @as(u32, 1);
pub const WINHTTP_RESOLVER_CACHE_CONFIG_FLAG_SOFT_LIMIT = @as(u32, 1);
pub const WINHTTP_RESOLVER_CACHE_CONFIG_FLAG_BYPASS_CACHE = @as(u32, 2);
pub const WINHTTP_RESOLVER_CACHE_CONFIG_FLAG_USE_DNS_TTL = @as(u32, 4);
pub const WINHTTP_RESOLVER_CACHE_CONFIG_FLAG_CONN_USE_TTL = @as(u32, 8);
pub const WINHTTP_TIME_FORMAT_BUFSIZE = @as(u32, 62);
pub const WINHTTP_OPTION_CALLBACK = @as(u32, 1);
pub const WINHTTP_OPTION_RESOLVE_TIMEOUT = @as(u32, 2);
pub const WINHTTP_OPTION_CONNECT_TIMEOUT = @as(u32, 3);
pub const WINHTTP_OPTION_CONNECT_RETRIES = @as(u32, 4);
pub const WINHTTP_OPTION_SEND_TIMEOUT = @as(u32, 5);
pub const WINHTTP_OPTION_RECEIVE_TIMEOUT = @as(u32, 6);
pub const WINHTTP_OPTION_RECEIVE_RESPONSE_TIMEOUT = @as(u32, 7);
pub const WINHTTP_OPTION_HANDLE_TYPE = @as(u32, 9);
pub const WINHTTP_OPTION_READ_BUFFER_SIZE = @as(u32, 12);
pub const WINHTTP_OPTION_WRITE_BUFFER_SIZE = @as(u32, 13);
pub const WINHTTP_OPTION_PARENT_HANDLE = @as(u32, 21);
pub const WINHTTP_OPTION_EXTENDED_ERROR = @as(u32, 24);
pub const WINHTTP_OPTION_SECURITY_FLAGS = @as(u32, 31);
pub const WINHTTP_OPTION_SECURITY_CERTIFICATE_STRUCT = @as(u32, 32);
pub const WINHTTP_OPTION_URL = @as(u32, 34);
pub const WINHTTP_OPTION_SECURITY_KEY_BITNESS = @as(u32, 36);
pub const WINHTTP_OPTION_PROXY = @as(u32, 38);
pub const WINHTTP_OPTION_PROXY_RESULT_ENTRY = @as(u32, 39);
pub const WINHTTP_OPTION_USER_AGENT = @as(u32, 41);
pub const WINHTTP_OPTION_CONTEXT_VALUE = @as(u32, 45);
pub const WINHTTP_OPTION_CLIENT_CERT_CONTEXT = @as(u32, 47);
pub const WINHTTP_OPTION_REQUEST_PRIORITY = @as(u32, 58);
pub const WINHTTP_OPTION_HTTP_VERSION = @as(u32, 59);
pub const WINHTTP_OPTION_DISABLE_FEATURE = @as(u32, 63);
pub const WINHTTP_OPTION_CODEPAGE = @as(u32, 68);
pub const WINHTTP_OPTION_MAX_CONNS_PER_SERVER = @as(u32, 73);
pub const WINHTTP_OPTION_MAX_CONNS_PER_1_0_SERVER = @as(u32, 74);
pub const WINHTTP_OPTION_AUTOLOGON_POLICY = @as(u32, 77);
pub const WINHTTP_OPTION_SERVER_CERT_CONTEXT = @as(u32, 78);
pub const WINHTTP_OPTION_ENABLE_FEATURE = @as(u32, 79);
pub const WINHTTP_OPTION_WORKER_THREAD_COUNT = @as(u32, 80);
pub const WINHTTP_OPTION_PASSPORT_COBRANDING_TEXT = @as(u32, 81);
pub const WINHTTP_OPTION_PASSPORT_COBRANDING_URL = @as(u32, 82);
pub const WINHTTP_OPTION_CONFIGURE_PASSPORT_AUTH = @as(u32, 83);
pub const WINHTTP_OPTION_SECURE_PROTOCOLS = @as(u32, 84);
pub const WINHTTP_OPTION_ENABLETRACING = @as(u32, 85);
pub const WINHTTP_OPTION_PASSPORT_SIGN_OUT = @as(u32, 86);
pub const WINHTTP_OPTION_PASSPORT_RETURN_URL = @as(u32, 87);
pub const WINHTTP_OPTION_REDIRECT_POLICY = @as(u32, 88);
pub const WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS = @as(u32, 89);
pub const WINHTTP_OPTION_MAX_HTTP_STATUS_CONTINUE = @as(u32, 90);
pub const WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE = @as(u32, 91);
pub const WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE = @as(u32, 92);
pub const WINHTTP_OPTION_CONNECTION_INFO = @as(u32, 93);
pub const WINHTTP_OPTION_CLIENT_CERT_ISSUER_LIST = @as(u32, 94);
pub const WINHTTP_OPTION_SPN = @as(u32, 96);
pub const WINHTTP_OPTION_GLOBAL_PROXY_CREDS = @as(u32, 97);
pub const WINHTTP_OPTION_GLOBAL_SERVER_CREDS = @as(u32, 98);
pub const WINHTTP_OPTION_UNLOAD_NOTIFY_EVENT = @as(u32, 99);
pub const WINHTTP_OPTION_REJECT_USERPWD_IN_URL = @as(u32, 100);
pub const WINHTTP_OPTION_USE_GLOBAL_SERVER_CREDENTIALS = @as(u32, 101);
pub const WINHTTP_OPTION_RECEIVE_PROXY_CONNECT_RESPONSE = @as(u32, 103);
pub const WINHTTP_OPTION_IS_PROXY_CONNECT_RESPONSE = @as(u32, 104);
pub const WINHTTP_OPTION_SERVER_SPN_USED = @as(u32, 106);
pub const WINHTTP_OPTION_PROXY_SPN_USED = @as(u32, 107);
pub const WINHTTP_OPTION_SERVER_CBT = @as(u32, 108);
pub const WINHTTP_OPTION_UNSAFE_HEADER_PARSING = @as(u32, 110);
pub const WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS = @as(u32, 111);
pub const WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET = @as(u32, 114);
pub const WINHTTP_OPTION_WEB_SOCKET_CLOSE_TIMEOUT = @as(u32, 115);
pub const WINHTTP_OPTION_WEB_SOCKET_KEEPALIVE_INTERVAL = @as(u32, 116);
pub const WINHTTP_OPTION_DECOMPRESSION = @as(u32, 118);
pub const WINHTTP_OPTION_WEB_SOCKET_RECEIVE_BUFFER_SIZE = @as(u32, 122);
pub const WINHTTP_OPTION_WEB_SOCKET_SEND_BUFFER_SIZE = @as(u32, 123);
pub const WINHTTP_OPTION_TCP_PRIORITY_HINT = @as(u32, 128);
pub const WINHTTP_OPTION_CONNECTION_FILTER = @as(u32, 131);
pub const WINHTTP_OPTION_ENABLE_HTTP_PROTOCOL = @as(u32, 133);
pub const WINHTTP_OPTION_HTTP_PROTOCOL_USED = @as(u32, 134);
pub const WINHTTP_OPTION_KDC_PROXY_SETTINGS = @as(u32, 136);
pub const WINHTTP_OPTION_PROXY_DISABLE_SERVICE_CALLS = @as(u32, 137);
pub const WINHTTP_OPTION_ENCODE_EXTRA = @as(u32, 138);
pub const WINHTTP_OPTION_DISABLE_STREAM_QUEUE = @as(u32, 139);
pub const WINHTTP_OPTION_IPV6_FAST_FALLBACK = @as(u32, 140);
pub const WINHTTP_OPTION_CONNECTION_STATS_V0 = @as(u32, 141);
pub const WINHTTP_OPTION_REQUEST_TIMES = @as(u32, 142);
pub const WINHTTP_OPTION_EXPIRE_CONNECTION = @as(u32, 143);
pub const WINHTTP_OPTION_DISABLE_SECURE_PROTOCOL_FALLBACK = @as(u32, 144);
pub const WINHTTP_OPTION_HTTP_PROTOCOL_REQUIRED = @as(u32, 145);
pub const WINHTTP_OPTION_REQUEST_STATS = @as(u32, 146);
pub const WINHTTP_OPTION_SERVER_CERT_CHAIN_CONTEXT = @as(u32, 147);
pub const WINHTTP_OPTION_CONNECTION_STATS_V1 = @as(u32, 150);
pub const WINHTTP_OPTION_SECURITY_INFO = @as(u32, 151);
pub const WINHTTP_OPTION_TCP_KEEPALIVE = @as(u32, 152);
pub const WINHTTP_OPTION_TCP_FAST_OPEN = @as(u32, 153);
pub const WINHTTP_OPTION_TLS_FALSE_START = @as(u32, 154);
pub const WINHTTP_OPTION_IGNORE_CERT_REVOCATION_OFFLINE = @as(u32, 155);
pub const WINHTTP_OPTION_SOURCE_ADDRESS = @as(u32, 156);
pub const WINHTTP_OPTION_HEAP_EXTENSION = @as(u32, 157);
pub const WINHTTP_OPTION_TLS_PROTOCOL_INSECURE_FALLBACK = @as(u32, 158);
pub const WINHTTP_OPTION_STREAM_ERROR_CODE = @as(u32, 159);
pub const WINHTTP_OPTION_REQUIRE_STREAM_END = @as(u32, 160);
pub const WINHTTP_OPTION_ENABLE_HTTP2_PLUS_CLIENT_CERT = @as(u32, 161);
pub const WINHTTP_OPTION_FAILED_CONNECTION_RETRIES = @as(u32, 162);
pub const WINHTTP_OPTION_SET_GLOBAL_CALLBACK = @as(u32, 163);
pub const WINHTTP_OPTION_HTTP2_KEEPALIVE = @as(u32, 164);
pub const WINHTTP_OPTION_RESOLUTION_HOSTNAME = @as(u32, 165);
pub const WINHTTP_OPTION_SET_TOKEN_BINDING = @as(u32, 166);
pub const WINHTTP_OPTION_TOKEN_BINDING_PUBLIC_KEY = @as(u32, 167);
pub const WINHTTP_OPTION_REFERER_TOKEN_BINDING_HOSTNAME = @as(u32, 168);
pub const WINHTTP_OPTION_HTTP2_PLUS_TRANSFER_ENCODING = @as(u32, 169);
pub const WINHTTP_OPTION_RESOLVER_CACHE_CONFIG = @as(u32, 170);
pub const WINHTTP_OPTION_DISABLE_CERT_CHAIN_BUILDING = @as(u32, 171);
pub const WINHTTP_OPTION_BACKGROUND_CONNECTIONS = @as(u32, 172);
pub const WINHTTP_OPTION_FIRST_AVAILABLE_CONNECTION = @as(u32, 173);
pub const WINHTTP_OPTION_ENABLE_TEST_SIGNING = @as(u32, 174);
pub const WINHTTP_OPTION_NTSERVICE_FLAG_TEST = @as(u32, 175);
pub const WINHTTP_OPTION_DISABLE_PROXY_LINK_LOCAL_NAME_RESOLUTION = @as(u32, 176);
pub const WINHTTP_OPTION_TCP_PRIORITY_STATUS = @as(u32, 177);
pub const WINHTTP_OPTION_CONNECTION_GUID = @as(u32, 178);
pub const WINHTTP_OPTION_MATCH_CONNECTION_GUID = @as(u32, 179);
pub const WINHTTP_OPTION_PROXY_CONFIG_INFO = @as(u32, 180);
pub const WINHTTP_OPTION_AGGREGATE_PROXY_CONFIG = @as(u32, 181);
pub const WINHTTP_OPTION_SELECTED_PROXY_CONFIG_INFO = @as(u32, 182);
pub const WINHTTP_OPTION_HTTP2_RECEIVE_WINDOW = @as(u32, 183);
pub const WINHTTP_LAST_OPTION = @as(u32, 183);
pub const WINHTTP_OPTION_USERNAME = @as(u32, 4096);
pub const WINHTTP_OPTION_PASSWORD = @as(u32, 4097);
pub const WINHTTP_OPTION_PROXY_USERNAME = @as(u32, 4098);
pub const WINHTTP_OPTION_PROXY_PASSWORD = @as(u32, 4099);
pub const WINHTTP_CONNS_PER_SERVER_UNLIMITED = @as(u32, 4294967295);
pub const WINHTTP_CONNECTION_RETRY_CONDITION_408 = @as(u32, 1);
pub const WINHTTP_CONNECTION_RETRY_CONDITION_SSL_HANDSHAKE = @as(u32, 2);
pub const WINHTTP_CONNECTION_RETRY_CONDITION_STALE_CONNECTION = @as(u32, 4);
pub const WINHTTP_DECOMPRESSION_FLAG_GZIP = @as(u32, 1);
pub const WINHTTP_DECOMPRESSION_FLAG_DEFLATE = @as(u32, 2);
pub const WINHTTP_PROTOCOL_FLAG_HTTP2 = @as(u32, 1);
pub const WINHTTP_PROTOCOL_FLAG_HTTP3 = @as(u32, 2);
pub const WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM = @as(u32, 0);
pub const WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW = @as(u32, 1);
pub const WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH = @as(u32, 2);
pub const WINHTTP_AUTOLOGON_SECURITY_LEVEL_DEFAULT = @as(u32, 0);
pub const WINHTTP_OPTION_REDIRECT_POLICY_NEVER = @as(u32, 0);
pub const WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP = @as(u32, 1);
pub const WINHTTP_OPTION_REDIRECT_POLICY_ALWAYS = @as(u32, 2);
pub const WINHTTP_OPTION_REDIRECT_POLICY_LAST = @as(u32, 2);
pub const WINHTTP_OPTION_REDIRECT_POLICY_DEFAULT = @as(u32, 1);
pub const WINHTTP_DISABLE_PASSPORT_AUTH = @as(u32, 0);
pub const WINHTTP_ENABLE_PASSPORT_AUTH = @as(u32, 268435456);
pub const WINHTTP_DISABLE_PASSPORT_KEYRING = @as(u32, 536870912);
pub const WINHTTP_ENABLE_PASSPORT_KEYRING = @as(u32, 1073741824);
pub const WINHTTP_DISABLE_COOKIES = @as(u32, 1);
pub const WINHTTP_DISABLE_REDIRECTS = @as(u32, 2);
pub const WINHTTP_DISABLE_AUTHENTICATION = @as(u32, 4);
pub const WINHTTP_DISABLE_KEEP_ALIVE = @as(u32, 8);
pub const WINHTTP_ENABLE_SSL_REVOCATION = @as(u32, 1);
pub const WINHTTP_ENABLE_SSL_REVERT_IMPERSONATION = @as(u32, 2);
pub const WINHTTP_DISABLE_SPN_SERVER_PORT = @as(u32, 0);
pub const WINHTTP_ENABLE_SPN_SERVER_PORT = @as(u32, 1);
pub const WINHTTP_OPTION_SPN_MASK = @as(u32, 1);
pub const WINHTTP_HANDLE_TYPE_SESSION = @as(u32, 1);
pub const WINHTTP_HANDLE_TYPE_CONNECT = @as(u32, 2);
pub const WINHTTP_HANDLE_TYPE_REQUEST = @as(u32, 3);
pub const WINHTTP_AUTH_SCHEME_PASSPORT = @as(u32, 4);
pub const WINHTTP_AUTH_SCHEME_DIGEST = @as(u32, 8);
pub const WINHTTP_AUTH_TARGET_SERVER = @as(u32, 0);
pub const WINHTTP_AUTH_TARGET_PROXY = @as(u32, 1);
pub const SECURITY_FLAG_SECURE = @as(u32, 1);
pub const SECURITY_FLAG_STRENGTH_WEAK = @as(u32, 268435456);
pub const SECURITY_FLAG_STRENGTH_MEDIUM = @as(u32, 1073741824);
pub const SECURITY_FLAG_STRENGTH_STRONG = @as(u32, 536870912);
pub const WINHTTP_CALLBACK_STATUS_FLAG_CERT_REV_FAILED = @as(u32, 1);
pub const WINHTTP_CALLBACK_STATUS_FLAG_INVALID_CERT = @as(u32, 2);
pub const WINHTTP_CALLBACK_STATUS_FLAG_CERT_REVOKED = @as(u32, 4);
pub const WINHTTP_CALLBACK_STATUS_FLAG_INVALID_CA = @as(u32, 8);
pub const WINHTTP_CALLBACK_STATUS_FLAG_CERT_CN_INVALID = @as(u32, 16);
pub const WINHTTP_CALLBACK_STATUS_FLAG_CERT_DATE_INVALID = @as(u32, 32);
pub const WINHTTP_CALLBACK_STATUS_FLAG_CERT_WRONG_USAGE = @as(u32, 64);
pub const WINHTTP_CALLBACK_STATUS_FLAG_SECURITY_CHANNEL_ERROR = @as(u32, 2147483648);
pub const WINHTTP_FLAG_SECURE_PROTOCOL_SSL2 = @as(u32, 8);
pub const WINHTTP_FLAG_SECURE_PROTOCOL_SSL3 = @as(u32, 32);
pub const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 = @as(u32, 128);
pub const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 = @as(u32, 512);
pub const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 = @as(u32, 2048);
pub const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3 = @as(u32, 8192);
pub const WINHTTP_CALLBACK_STATUS_RESOLVING_NAME = @as(u32, 1);
pub const WINHTTP_CALLBACK_STATUS_NAME_RESOLVED = @as(u32, 2);
pub const WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER = @as(u32, 4);
pub const WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER = @as(u32, 8);
pub const WINHTTP_CALLBACK_STATUS_SENDING_REQUEST = @as(u32, 16);
pub const WINHTTP_CALLBACK_STATUS_REQUEST_SENT = @as(u32, 32);
pub const WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE = @as(u32, 64);
pub const WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED = @as(u32, 128);
pub const WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION = @as(u32, 256);
pub const WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED = @as(u32, 512);
pub const WINHTTP_CALLBACK_STATUS_HANDLE_CREATED = @as(u32, 1024);
pub const WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING = @as(u32, 2048);
pub const WINHTTP_CALLBACK_STATUS_DETECTING_PROXY = @as(u32, 4096);
pub const WINHTTP_CALLBACK_STATUS_REDIRECT = @as(u32, 16384);
pub const WINHTTP_CALLBACK_STATUS_INTERMEDIATE_RESPONSE = @as(u32, 32768);
pub const WINHTTP_CALLBACK_STATUS_SECURE_FAILURE = @as(u32, 65536);
pub const WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE = @as(u32, 131072);
pub const WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE = @as(u32, 262144);
pub const WINHTTP_CALLBACK_STATUS_READ_COMPLETE = @as(u32, 524288);
pub const WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE = @as(u32, 1048576);
pub const WINHTTP_CALLBACK_STATUS_REQUEST_ERROR = @as(u32, 2097152);
pub const WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE = @as(u32, 4194304);
pub const WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE = @as(u32, 16777216);
pub const WINHTTP_CALLBACK_STATUS_CLOSE_COMPLETE = @as(u32, 33554432);
pub const WINHTTP_CALLBACK_STATUS_SHUTDOWN_COMPLETE = @as(u32, 67108864);
pub const WINHTTP_CALLBACK_STATUS_SETTINGS_WRITE_COMPLETE = @as(u32, 268435456);
pub const WINHTTP_CALLBACK_STATUS_SETTINGS_READ_COMPLETE = @as(u32, 536870912);
pub const API_RECEIVE_RESPONSE = @as(u32, 1);
pub const API_QUERY_DATA_AVAILABLE = @as(u32, 2);
pub const API_READ_DATA = @as(u32, 3);
pub const API_WRITE_DATA = @as(u32, 4);
pub const API_SEND_REQUEST = @as(u32, 5);
pub const API_GET_PROXY_FOR_URL = @as(u32, 6);
pub const WINHTTP_CALLBACK_FLAG_DETECTING_PROXY = @as(u32, 4096);
pub const WINHTTP_CALLBACK_FLAG_REDIRECT = @as(u32, 16384);
pub const WINHTTP_CALLBACK_FLAG_INTERMEDIATE_RESPONSE = @as(u32, 32768);
pub const WINHTTP_CALLBACK_FLAG_SECURE_FAILURE = @as(u32, 65536);
pub const WINHTTP_CALLBACK_FLAG_SENDREQUEST_COMPLETE = @as(u32, 4194304);
pub const WINHTTP_CALLBACK_FLAG_HEADERS_AVAILABLE = @as(u32, 131072);
pub const WINHTTP_CALLBACK_FLAG_DATA_AVAILABLE = @as(u32, 262144);
pub const WINHTTP_CALLBACK_FLAG_READ_COMPLETE = @as(u32, 524288);
pub const WINHTTP_CALLBACK_FLAG_WRITE_COMPLETE = @as(u32, 1048576);
pub const WINHTTP_CALLBACK_FLAG_REQUEST_ERROR = @as(u32, 2097152);
pub const WINHTTP_CALLBACK_FLAG_GETPROXYFORURL_COMPLETE = @as(u32, 16777216);
pub const WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS = @as(u32, 4294967295);
pub const WINHTTP_QUERY_MIME_VERSION = @as(u32, 0);
pub const WINHTTP_QUERY_CONTENT_TYPE = @as(u32, 1);
pub const WINHTTP_QUERY_CONTENT_TRANSFER_ENCODING = @as(u32, 2);
pub const WINHTTP_QUERY_CONTENT_ID = @as(u32, 3);
pub const WINHTTP_QUERY_CONTENT_DESCRIPTION = @as(u32, 4);
pub const WINHTTP_QUERY_CONTENT_LENGTH = @as(u32, 5);
pub const WINHTTP_QUERY_CONTENT_LANGUAGE = @as(u32, 6);
pub const WINHTTP_QUERY_ALLOW = @as(u32, 7);
pub const WINHTTP_QUERY_PUBLIC = @as(u32, 8);
pub const WINHTTP_QUERY_DATE = @as(u32, 9);
pub const WINHTTP_QUERY_EXPIRES = @as(u32, 10);
pub const WINHTTP_QUERY_LAST_MODIFIED = @as(u32, 11);
pub const WINHTTP_QUERY_MESSAGE_ID = @as(u32, 12);
pub const WINHTTP_QUERY_URI = @as(u32, 13);
pub const WINHTTP_QUERY_DERIVED_FROM = @as(u32, 14);
pub const WINHTTP_QUERY_COST = @as(u32, 15);
pub const WINHTTP_QUERY_LINK = @as(u32, 16);
pub const WINHTTP_QUERY_PRAGMA = @as(u32, 17);
pub const WINHTTP_QUERY_VERSION = @as(u32, 18);
pub const WINHTTP_QUERY_STATUS_CODE = @as(u32, 19);
pub const WINHTTP_QUERY_STATUS_TEXT = @as(u32, 20);
pub const WINHTTP_QUERY_RAW_HEADERS = @as(u32, 21);
pub const WINHTTP_QUERY_RAW_HEADERS_CRLF = @as(u32, 22);
pub const WINHTTP_QUERY_CONNECTION = @as(u32, 23);
pub const WINHTTP_QUERY_ACCEPT = @as(u32, 24);
pub const WINHTTP_QUERY_ACCEPT_CHARSET = @as(u32, 25);
pub const WINHTTP_QUERY_ACCEPT_ENCODING = @as(u32, 26);
pub const WINHTTP_QUERY_ACCEPT_LANGUAGE = @as(u32, 27);
pub const WINHTTP_QUERY_AUTHORIZATION = @as(u32, 28);
pub const WINHTTP_QUERY_CONTENT_ENCODING = @as(u32, 29);
pub const WINHTTP_QUERY_FORWARDED = @as(u32, 30);
pub const WINHTTP_QUERY_FROM = @as(u32, 31);
pub const WINHTTP_QUERY_IF_MODIFIED_SINCE = @as(u32, 32);
pub const WINHTTP_QUERY_LOCATION = @as(u32, 33);
pub const WINHTTP_QUERY_ORIG_URI = @as(u32, 34);
pub const WINHTTP_QUERY_REFERER = @as(u32, 35);
pub const WINHTTP_QUERY_RETRY_AFTER = @as(u32, 36);
pub const WINHTTP_QUERY_SERVER = @as(u32, 37);
pub const WINHTTP_QUERY_TITLE = @as(u32, 38);
pub const WINHTTP_QUERY_USER_AGENT = @as(u32, 39);
pub const WINHTTP_QUERY_WWW_AUTHENTICATE = @as(u32, 40);
pub const WINHTTP_QUERY_PROXY_AUTHENTICATE = @as(u32, 41);
pub const WINHTTP_QUERY_ACCEPT_RANGES = @as(u32, 42);
pub const WINHTTP_QUERY_SET_COOKIE = @as(u32, 43);
pub const WINHTTP_QUERY_COOKIE = @as(u32, 44);
pub const WINHTTP_QUERY_REQUEST_METHOD = @as(u32, 45);
pub const WINHTTP_QUERY_REFRESH = @as(u32, 46);
pub const WINHTTP_QUERY_CONTENT_DISPOSITION = @as(u32, 47);
pub const WINHTTP_QUERY_AGE = @as(u32, 48);
pub const WINHTTP_QUERY_CACHE_CONTROL = @as(u32, 49);
pub const WINHTTP_QUERY_CONTENT_BASE = @as(u32, 50);
pub const WINHTTP_QUERY_CONTENT_LOCATION = @as(u32, 51);
pub const WINHTTP_QUERY_CONTENT_MD5 = @as(u32, 52);
pub const WINHTTP_QUERY_CONTENT_RANGE = @as(u32, 53);
pub const WINHTTP_QUERY_ETAG = @as(u32, 54);
pub const WINHTTP_QUERY_HOST = @as(u32, 55);
pub const WINHTTP_QUERY_IF_MATCH = @as(u32, 56);
pub const WINHTTP_QUERY_IF_NONE_MATCH = @as(u32, 57);
pub const WINHTTP_QUERY_IF_RANGE = @as(u32, 58);
pub const WINHTTP_QUERY_IF_UNMODIFIED_SINCE = @as(u32, 59);
pub const WINHTTP_QUERY_MAX_FORWARDS = @as(u32, 60);
pub const WINHTTP_QUERY_PROXY_AUTHORIZATION = @as(u32, 61);
pub const WINHTTP_QUERY_RANGE = @as(u32, 62);
pub const WINHTTP_QUERY_TRANSFER_ENCODING = @as(u32, 63);
pub const WINHTTP_QUERY_UPGRADE = @as(u32, 64);
pub const WINHTTP_QUERY_VARY = @as(u32, 65);
pub const WINHTTP_QUERY_VIA = @as(u32, 66);
pub const WINHTTP_QUERY_WARNING = @as(u32, 67);
pub const WINHTTP_QUERY_EXPECT = @as(u32, 68);
pub const WINHTTP_QUERY_PROXY_CONNECTION = @as(u32, 69);
pub const WINHTTP_QUERY_UNLESS_MODIFIED_SINCE = @as(u32, 70);
pub const WINHTTP_QUERY_PROXY_SUPPORT = @as(u32, 75);
pub const WINHTTP_QUERY_AUTHENTICATION_INFO = @as(u32, 76);
pub const WINHTTP_QUERY_PASSPORT_URLS = @as(u32, 77);
pub const WINHTTP_QUERY_PASSPORT_CONFIG = @as(u32, 78);
pub const WINHTTP_QUERY_MAX = @as(u32, 78);
pub const WINHTTP_QUERY_EX_ALL_HEADERS = @as(u32, 21);
pub const WINHTTP_QUERY_CUSTOM = @as(u32, 65535);
pub const WINHTTP_QUERY_FLAG_REQUEST_HEADERS = @as(u32, 2147483648);
pub const WINHTTP_QUERY_FLAG_SYSTEMTIME = @as(u32, 1073741824);
pub const WINHTTP_QUERY_FLAG_NUMBER = @as(u32, 536870912);
pub const WINHTTP_QUERY_FLAG_NUMBER64 = @as(u32, 134217728);
pub const WINHTTP_QUERY_FLAG_TRAILERS = @as(u32, 33554432);
pub const WINHTTP_QUERY_FLAG_WIRE_ENCODING = @as(u32, 16777216);
pub const HTTP_STATUS_CONTINUE = @as(u32, 100);
pub const HTTP_STATUS_SWITCH_PROTOCOLS = @as(u32, 101);
pub const HTTP_STATUS_OK = @as(u32, 200);
pub const HTTP_STATUS_CREATED = @as(u32, 201);
pub const HTTP_STATUS_ACCEPTED = @as(u32, 202);
pub const HTTP_STATUS_PARTIAL = @as(u32, 203);
pub const HTTP_STATUS_NO_CONTENT = @as(u32, 204);
pub const HTTP_STATUS_RESET_CONTENT = @as(u32, 205);
pub const HTTP_STATUS_PARTIAL_CONTENT = @as(u32, 206);
pub const HTTP_STATUS_WEBDAV_MULTI_STATUS = @as(u32, 207);
pub const HTTP_STATUS_AMBIGUOUS = @as(u32, 300);
pub const HTTP_STATUS_MOVED = @as(u32, 301);
pub const HTTP_STATUS_REDIRECT = @as(u32, 302);
pub const HTTP_STATUS_REDIRECT_METHOD = @as(u32, 303);
pub const HTTP_STATUS_NOT_MODIFIED = @as(u32, 304);
pub const HTTP_STATUS_USE_PROXY = @as(u32, 305);
pub const HTTP_STATUS_REDIRECT_KEEP_VERB = @as(u32, 307);
pub const HTTP_STATUS_PERMANENT_REDIRECT = @as(u32, 308);
pub const HTTP_STATUS_BAD_REQUEST = @as(u32, 400);
pub const HTTP_STATUS_DENIED = @as(u32, 401);
pub const HTTP_STATUS_PAYMENT_REQ = @as(u32, 402);
pub const HTTP_STATUS_FORBIDDEN = @as(u32, 403);
pub const HTTP_STATUS_NOT_FOUND = @as(u32, 404);
pub const HTTP_STATUS_BAD_METHOD = @as(u32, 405);
pub const HTTP_STATUS_NONE_ACCEPTABLE = @as(u32, 406);
pub const HTTP_STATUS_PROXY_AUTH_REQ = @as(u32, 407);
pub const HTTP_STATUS_REQUEST_TIMEOUT = @as(u32, 408);
pub const HTTP_STATUS_CONFLICT = @as(u32, 409);
pub const HTTP_STATUS_GONE = @as(u32, 410);
pub const HTTP_STATUS_LENGTH_REQUIRED = @as(u32, 411);
pub const HTTP_STATUS_PRECOND_FAILED = @as(u32, 412);
pub const HTTP_STATUS_REQUEST_TOO_LARGE = @as(u32, 413);
pub const HTTP_STATUS_URI_TOO_LONG = @as(u32, 414);
pub const HTTP_STATUS_UNSUPPORTED_MEDIA = @as(u32, 415);
pub const HTTP_STATUS_RETRY_WITH = @as(u32, 449);
pub const HTTP_STATUS_SERVER_ERROR = @as(u32, 500);
pub const HTTP_STATUS_NOT_SUPPORTED = @as(u32, 501);
pub const HTTP_STATUS_BAD_GATEWAY = @as(u32, 502);
pub const HTTP_STATUS_SERVICE_UNAVAIL = @as(u32, 503);
pub const HTTP_STATUS_GATEWAY_TIMEOUT = @as(u32, 504);
pub const HTTP_STATUS_VERSION_NOT_SUP = @as(u32, 505);
pub const HTTP_STATUS_FIRST = @as(u32, 100);
pub const HTTP_STATUS_LAST = @as(u32, 505);
pub const ICU_NO_ENCODE = @as(u32, 536870912);
pub const ICU_NO_META = @as(u32, 134217728);
pub const ICU_ENCODE_SPACES_ONLY = @as(u32, 67108864);
pub const ICU_BROWSER_MODE = @as(u32, 33554432);
pub const ICU_ENCODE_PERCENT = @as(u32, 4096);
pub const ICU_ESCAPE_AUTHORITY = @as(u32, 8192);
pub const WINHTTP_ADDREQ_INDEX_MASK = @as(u32, 65535);
pub const WINHTTP_ADDREQ_FLAGS_MASK = @as(u32, 4294901760);
pub const WINHTTP_ADDREQ_FLAG_ADD_IF_NEW = @as(u32, 268435456);
pub const WINHTTP_ADDREQ_FLAG_ADD = @as(u32, 536870912);
pub const WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA = @as(u32, 1073741824);
pub const WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON = @as(u32, 16777216);
pub const WINHTTP_ADDREQ_FLAG_COALESCE = @as(u32, 1073741824);
pub const WINHTTP_ADDREQ_FLAG_REPLACE = @as(u32, 2147483648);
pub const WINHTTP_EXTENDED_HEADER_FLAG_UNICODE = @as(u32, 1);
pub const WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH = @as(u32, 0);
pub const WINHTTP_ERROR_BASE = @as(u32, 12000);
pub const ERROR_WINHTTP_OUT_OF_HANDLES = @as(u32, 12001);
pub const ERROR_WINHTTP_TIMEOUT = @as(u32, 12002);
pub const ERROR_WINHTTP_INTERNAL_ERROR = @as(u32, 12004);
pub const ERROR_WINHTTP_INVALID_URL = @as(u32, 12005);
pub const ERROR_WINHTTP_UNRECOGNIZED_SCHEME = @as(u32, 12006);
pub const ERROR_WINHTTP_NAME_NOT_RESOLVED = @as(u32, 12007);
pub const ERROR_WINHTTP_INVALID_OPTION = @as(u32, 12009);
pub const ERROR_WINHTTP_OPTION_NOT_SETTABLE = @as(u32, 12011);
pub const ERROR_WINHTTP_SHUTDOWN = @as(u32, 12012);
pub const ERROR_WINHTTP_LOGIN_FAILURE = @as(u32, 12015);
pub const ERROR_WINHTTP_OPERATION_CANCELLED = @as(u32, 12017);
pub const ERROR_WINHTTP_INCORRECT_HANDLE_TYPE = @as(u32, 12018);
pub const ERROR_WINHTTP_INCORRECT_HANDLE_STATE = @as(u32, 12019);
pub const ERROR_WINHTTP_CANNOT_CONNECT = @as(u32, 12029);
pub const ERROR_WINHTTP_CONNECTION_ERROR = @as(u32, 12030);
pub const ERROR_WINHTTP_RESEND_REQUEST = @as(u32, 12032);
pub const ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED = @as(u32, 12044);
pub const ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN = @as(u32, 12100);
pub const ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND = @as(u32, 12101);
pub const ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND = @as(u32, 12102);
pub const ERROR_WINHTTP_CANNOT_CALL_AFTER_OPEN = @as(u32, 12103);
pub const ERROR_WINHTTP_HEADER_NOT_FOUND = @as(u32, 12150);
pub const ERROR_WINHTTP_INVALID_SERVER_RESPONSE = @as(u32, 12152);
pub const ERROR_WINHTTP_INVALID_HEADER = @as(u32, 12153);
pub const ERROR_WINHTTP_INVALID_QUERY_REQUEST = @as(u32, 12154);
pub const ERROR_WINHTTP_HEADER_ALREADY_EXISTS = @as(u32, 12155);
pub const ERROR_WINHTTP_REDIRECT_FAILED = @as(u32, 12156);
pub const ERROR_WINHTTP_AUTO_PROXY_SERVICE_ERROR = @as(u32, 12178);
pub const ERROR_WINHTTP_BAD_AUTO_PROXY_SCRIPT = @as(u32, 12166);
pub const ERROR_WINHTTP_UNABLE_TO_DOWNLOAD_SCRIPT = @as(u32, 12167);
pub const ERROR_WINHTTP_UNHANDLED_SCRIPT_TYPE = @as(u32, 12176);
pub const ERROR_WINHTTP_SCRIPT_EXECUTION_ERROR = @as(u32, 12177);
pub const ERROR_WINHTTP_NOT_INITIALIZED = @as(u32, 12172);
pub const ERROR_WINHTTP_SECURE_FAILURE = @as(u32, 12175);
pub const ERROR_WINHTTP_SECURE_CERT_DATE_INVALID = @as(u32, 12037);
pub const ERROR_WINHTTP_SECURE_CERT_CN_INVALID = @as(u32, 12038);
pub const ERROR_WINHTTP_SECURE_INVALID_CA = @as(u32, 12045);
pub const ERROR_WINHTTP_SECURE_CERT_REV_FAILED = @as(u32, 12057);
pub const ERROR_WINHTTP_SECURE_CHANNEL_ERROR = @as(u32, 12157);
pub const ERROR_WINHTTP_SECURE_INVALID_CERT = @as(u32, 12169);
pub const ERROR_WINHTTP_SECURE_CERT_REVOKED = @as(u32, 12170);
pub const ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE = @as(u32, 12179);
pub const ERROR_WINHTTP_AUTODETECTION_FAILED = @as(u32, 12180);
pub const ERROR_WINHTTP_HEADER_COUNT_EXCEEDED = @as(u32, 12181);
pub const ERROR_WINHTTP_HEADER_SIZE_OVERFLOW = @as(u32, 12182);
pub const ERROR_WINHTTP_CHUNKED_ENCODING_HEADER_SIZE_OVERFLOW = @as(u32, 12183);
pub const ERROR_WINHTTP_RESPONSE_DRAIN_OVERFLOW = @as(u32, 12184);
pub const ERROR_WINHTTP_CLIENT_CERT_NO_PRIVATE_KEY = @as(u32, 12185);
pub const ERROR_WINHTTP_CLIENT_CERT_NO_ACCESS_PRIVATE_KEY = @as(u32, 12186);
pub const ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED_PROXY = @as(u32, 12187);
pub const ERROR_WINHTTP_SECURE_FAILURE_PROXY = @as(u32, 12188);
pub const ERROR_WINHTTP_RESERVED_189 = @as(u32, 12189);
pub const ERROR_WINHTTP_HTTP_PROTOCOL_MISMATCH = @as(u32, 12190);
pub const ERROR_WINHTTP_GLOBAL_CALLBACK_FAILED = @as(u32, 12191);
pub const ERROR_WINHTTP_FEATURE_DISABLED = @as(u32, 12192);
pub const WINHTTP_ERROR_LAST = @as(u32, 12192);
pub const WINHTTP_RESET_STATE = @as(u32, 1);
pub const WINHTTP_RESET_SWPAD_CURRENT_NETWORK = @as(u32, 2);
pub const WINHTTP_RESET_SWPAD_ALL = @as(u32, 4);
pub const WINHTTP_RESET_SCRIPT_CACHE = @as(u32, 8);
pub const WINHTTP_RESET_ALL = @as(u32, 65535);
pub const WINHTTP_RESET_NOTIFY_NETWORK_CHANGED = @as(u32, 65536);
pub const WINHTTP_RESET_OUT_OF_PROC = @as(u32, 131072);
pub const WINHTTP_RESET_DISCARD_RESOLVERS = @as(u32, 262144);
pub const WINHTTP_WEB_SOCKET_MAX_CLOSE_REASON_LENGTH = @as(u32, 123);
pub const WINHTTP_WEB_SOCKET_MIN_KEEPALIVE_VALUE = @as(u32, 15000);
//--------------------------------------------------------------------------------
// Section: Types (47)
//--------------------------------------------------------------------------------
pub const INTERNET_PORT = enum(u32) {
HTTP_PORT = 80,
HTTPS_PORT = 443,
PORT = 0,
};
pub const INTERNET_DEFAULT_HTTP_PORT = INTERNET_PORT.HTTP_PORT;
pub const INTERNET_DEFAULT_HTTPS_PORT = INTERNET_PORT.HTTPS_PORT;
pub const INTERNET_DEFAULT_PORT = INTERNET_PORT.PORT;
pub const WINHTTP_OPEN_REQUEST_FLAGS = enum(u32) {
BYPASS_PROXY_CACHE = 256,
ESCAPE_DISABLE = 64,
ESCAPE_DISABLE_QUERY = 128,
ESCAPE_PERCENT = 4,
NULL_CODEPAGE = 8,
// REFRESH = 256, this enum value conflicts with BYPASS_PROXY_CACHE
SECURE = 8388608,
_,
pub fn initFlags(o: struct {
BYPASS_PROXY_CACHE: u1 = 0,
ESCAPE_DISABLE: u1 = 0,
ESCAPE_DISABLE_QUERY: u1 = 0,
ESCAPE_PERCENT: u1 = 0,
NULL_CODEPAGE: u1 = 0,
SECURE: u1 = 0,
}) WINHTTP_OPEN_REQUEST_FLAGS {
return @intToEnum(WINHTTP_OPEN_REQUEST_FLAGS,
(if (o.BYPASS_PROXY_CACHE == 1) @enumToInt(WINHTTP_OPEN_REQUEST_FLAGS.BYPASS_PROXY_CACHE) else 0)
| (if (o.ESCAPE_DISABLE == 1) @enumToInt(WINHTTP_OPEN_REQUEST_FLAGS.ESCAPE_DISABLE) else 0)
| (if (o.ESCAPE_DISABLE_QUERY == 1) @enumToInt(WINHTTP_OPEN_REQUEST_FLAGS.ESCAPE_DISABLE_QUERY) else 0)
| (if (o.ESCAPE_PERCENT == 1) @enumToInt(WINHTTP_OPEN_REQUEST_FLAGS.ESCAPE_PERCENT) else 0)
| (if (o.NULL_CODEPAGE == 1) @enumToInt(WINHTTP_OPEN_REQUEST_FLAGS.NULL_CODEPAGE) else 0)
| (if (o.SECURE == 1) @enumToInt(WINHTTP_OPEN_REQUEST_FLAGS.SECURE) else 0)
);
}
};
pub const WINHTTP_FLAG_BYPASS_PROXY_CACHE = WINHTTP_OPEN_REQUEST_FLAGS.BYPASS_PROXY_CACHE;
pub const WINHTTP_FLAG_ESCAPE_DISABLE = WINHTTP_OPEN_REQUEST_FLAGS.ESCAPE_DISABLE;
pub const WINHTTP_FLAG_ESCAPE_DISABLE_QUERY = WINHTTP_OPEN_REQUEST_FLAGS.ESCAPE_DISABLE_QUERY;
pub const WINHTTP_FLAG_ESCAPE_PERCENT = WINHTTP_OPEN_REQUEST_FLAGS.ESCAPE_PERCENT;
pub const WINHTTP_FLAG_NULL_CODEPAGE = WINHTTP_OPEN_REQUEST_FLAGS.NULL_CODEPAGE;
pub const WINHTTP_FLAG_REFRESH = WINHTTP_OPEN_REQUEST_FLAGS.BYPASS_PROXY_CACHE;
pub const WINHTTP_FLAG_SECURE = WINHTTP_OPEN_REQUEST_FLAGS.SECURE;
pub const WIN_HTTP_CREATE_URL_FLAGS = enum(u32) {
ESCAPE = 2147483648,
REJECT_USERPWD = 16384,
DECODE = 268435456,
};
pub const ICU_ESCAPE = WIN_HTTP_CREATE_URL_FLAGS.ESCAPE;
pub const ICU_REJECT_USERPWD = WIN_HTTP_CREATE_URL_FLAGS.REJECT_USERPWD;
pub const ICU_DECODE = WIN_HTTP_CREATE_URL_FLAGS.DECODE;
pub const WINHTTP_ACCESS_TYPE = enum(u32) {
NO_PROXY = 1,
DEFAULT_PROXY = 0,
NAMED_PROXY = 3,
AUTOMATIC_PROXY = 4,
};
pub const WINHTTP_ACCESS_TYPE_NO_PROXY = WINHTTP_ACCESS_TYPE.NO_PROXY;
pub const WINHTTP_ACCESS_TYPE_DEFAULT_PROXY = WINHTTP_ACCESS_TYPE.DEFAULT_PROXY;
pub const WINHTTP_ACCESS_TYPE_NAMED_PROXY = WINHTTP_ACCESS_TYPE.NAMED_PROXY;
pub const WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY = WINHTTP_ACCESS_TYPE.AUTOMATIC_PROXY;
pub const WINHTTP_CREDS_AUTHSCHEME = enum(u32) {
BASIC = 1,
NTLM = 2,
NEGOTIATE = 16,
};
pub const WINHTTP_AUTH_SCHEME_BASIC = WINHTTP_CREDS_AUTHSCHEME.BASIC;
pub const WINHTTP_AUTH_SCHEME_NTLM = WINHTTP_CREDS_AUTHSCHEME.NTLM;
pub const WINHTTP_AUTH_SCHEME_NEGOTIATE = WINHTTP_CREDS_AUTHSCHEME.NEGOTIATE;
pub const WINHTTP_INTERNET_SCHEME = enum(u32) {
HTTP = 1,
HTTPS = 2,
FTP = 3,
SOCKS = 4,
};
pub const WINHTTP_INTERNET_SCHEME_HTTP = WINHTTP_INTERNET_SCHEME.HTTP;
pub const WINHTTP_INTERNET_SCHEME_HTTPS = WINHTTP_INTERNET_SCHEME.HTTPS;
pub const WINHTTP_INTERNET_SCHEME_FTP = WINHTTP_INTERNET_SCHEME.FTP;
pub const WINHTTP_INTERNET_SCHEME_SOCKS = WINHTTP_INTERNET_SCHEME.SOCKS;
pub const WINHTTP_ASYNC_RESULT = extern struct {
dwResult: usize,
dwError: u32,
};
pub const HTTP_VERSION_INFO = extern struct {
dwMajorVersion: u32,
dwMinorVersion: u32,
};
pub const URL_COMPONENTS = extern struct {
dwStructSize: u32,
lpszScheme: ?PWSTR,
dwSchemeLength: u32,
nScheme: WINHTTP_INTERNET_SCHEME,
lpszHostName: ?PWSTR,
dwHostNameLength: u32,
nPort: u16,
lpszUserName: ?PWSTR,
dwUserNameLength: u32,
lpszPassword: ?PWSTR,
dwPasswordLength: u32,
lpszUrlPath: ?PWSTR,
dwUrlPathLength: u32,
lpszExtraInfo: ?PWSTR,
dwExtraInfoLength: u32,
};
pub const WINHTTP_PROXY_INFO = extern struct {
dwAccessType: WINHTTP_ACCESS_TYPE,
lpszProxy: ?PWSTR,
lpszProxyBypass: ?PWSTR,
};
pub const WINHTTP_AUTOPROXY_OPTIONS = extern struct {
dwFlags: u32,
dwAutoDetectFlags: u32,
lpszAutoConfigUrl: ?[*:0]const u16,
lpvReserved: ?*anyopaque,
dwReserved: u32,
fAutoLogonIfChallenged: BOOL,
};
pub const WINHTTP_PROXY_RESULT_ENTRY = extern struct {
fProxy: BOOL,
fBypass: BOOL,
ProxyScheme: WINHTTP_INTERNET_SCHEME,
pwszProxy: ?PWSTR,
ProxyPort: u16,
};
pub const WINHTTP_PROXY_RESULT = extern struct {
cEntries: u32,
pEntries: ?*WINHTTP_PROXY_RESULT_ENTRY,
};
pub const WINHTTP_PROXY_RESULT_EX = extern struct {
cEntries: u32,
pEntries: ?*WINHTTP_PROXY_RESULT_ENTRY,
hProxyDetectionHandle: ?HANDLE,
dwProxyInterfaceAffinity: u32,
};
pub const _WinHttpProxyNetworkKey = extern struct {
pbBuffer: [128]u8,
};
pub const WINHTTP_PROXY_SETTINGS = extern struct {
dwStructSize: u32,
dwFlags: u32,
dwCurrentSettingsVersion: u32,
pwszConnectionName: ?PWSTR,
pwszProxy: ?PWSTR,
pwszProxyBypass: ?PWSTR,
pwszAutoconfigUrl: ?PWSTR,
pwszAutoconfigSecondaryUrl: ?PWSTR,
dwAutoDiscoveryFlags: u32,
pwszLastKnownGoodAutoConfigUrl: ?PWSTR,
dwAutoconfigReloadDelayMins: u32,
ftLastKnownDetectTime: FILETIME,
dwDetectedInterfaceIpCount: u32,
pdwDetectedInterfaceIp: ?*u32,
cNetworkKeys: u32,
pNetworkKeys: ?*_WinHttpProxyNetworkKey,
};
pub const WINHTTP_CERTIFICATE_INFO = extern struct {
ftExpiry: FILETIME,
ftStart: FILETIME,
lpszSubjectInfo: ?PWSTR,
lpszIssuerInfo: ?PWSTR,
lpszProtocolName: ?PWSTR,
lpszSignatureAlgName: ?PWSTR,
lpszEncryptionAlgName: ?PWSTR,
dwKeySize: u32,
};
pub const WINHTTP_REQUEST_TIME_ENTRY = enum(i32) {
ProxyDetectionStart = 0,
ProxyDetectionEnd = 1,
ConnectionAcquireStart = 2,
ConnectionAcquireWaitEnd = 3,
ConnectionAcquireEnd = 4,
NameResolutionStart = 5,
NameResolutionEnd = 6,
ConnectionEstablishmentStart = 7,
ConnectionEstablishmentEnd = 8,
TlsHandshakeClientLeg1Start = 9,
TlsHandshakeClientLeg1End = 10,
TlsHandshakeClientLeg2Start = 11,
TlsHandshakeClientLeg2End = 12,
TlsHandshakeClientLeg3Start = 13,
TlsHandshakeClientLeg3End = 14,
StreamWaitStart = 15,
StreamWaitEnd = 16,
SendRequestStart = 17,
SendRequestHeadersCompressionStart = 18,
SendRequestHeadersCompressionEnd = 19,
SendRequestHeadersEnd = 20,
SendRequestEnd = 21,
ReceiveResponseStart = 22,
ReceiveResponseHeadersDecompressionStart = 23,
ReceiveResponseHeadersDecompressionEnd = 24,
ReceiveResponseHeadersEnd = 25,
ReceiveResponseBodyDecompressionDelta = 26,
ReceiveResponseEnd = 27,
ProxyTunnelStart = 28,
ProxyTunnelEnd = 29,
ProxyTlsHandshakeClientLeg1Start = 30,
ProxyTlsHandshakeClientLeg1End = 31,
ProxyTlsHandshakeClientLeg2Start = 32,
ProxyTlsHandshakeClientLeg2End = 33,
ProxyTlsHandshakeClientLeg3Start = 34,
ProxyTlsHandshakeClientLeg3End = 35,
RequestTimeLast = 36,
RequestTimeMax = 64,
};
pub const WinHttpProxyDetectionStart = WINHTTP_REQUEST_TIME_ENTRY.ProxyDetectionStart;
pub const WinHttpProxyDetectionEnd = WINHTTP_REQUEST_TIME_ENTRY.ProxyDetectionEnd;
pub const WinHttpConnectionAcquireStart = WINHTTP_REQUEST_TIME_ENTRY.ConnectionAcquireStart;
pub const WinHttpConnectionAcquireWaitEnd = WINHTTP_REQUEST_TIME_ENTRY.ConnectionAcquireWaitEnd;
pub const WinHttpConnectionAcquireEnd = WINHTTP_REQUEST_TIME_ENTRY.ConnectionAcquireEnd;
pub const WinHttpNameResolutionStart = WINHTTP_REQUEST_TIME_ENTRY.NameResolutionStart;
pub const WinHttpNameResolutionEnd = WINHTTP_REQUEST_TIME_ENTRY.NameResolutionEnd;
pub const WinHttpConnectionEstablishmentStart = WINHTTP_REQUEST_TIME_ENTRY.ConnectionEstablishmentStart;
pub const WinHttpConnectionEstablishmentEnd = WINHTTP_REQUEST_TIME_ENTRY.ConnectionEstablishmentEnd;
pub const WinHttpTlsHandshakeClientLeg1Start = WINHTTP_REQUEST_TIME_ENTRY.TlsHandshakeClientLeg1Start;
pub const WinHttpTlsHandshakeClientLeg1End = WINHTTP_REQUEST_TIME_ENTRY.TlsHandshakeClientLeg1End;
pub const WinHttpTlsHandshakeClientLeg2Start = WINHTTP_REQUEST_TIME_ENTRY.TlsHandshakeClientLeg2Start;
pub const WinHttpTlsHandshakeClientLeg2End = WINHTTP_REQUEST_TIME_ENTRY.TlsHandshakeClientLeg2End;
pub const WinHttpTlsHandshakeClientLeg3Start = WINHTTP_REQUEST_TIME_ENTRY.TlsHandshakeClientLeg3Start;
pub const WinHttpTlsHandshakeClientLeg3End = WINHTTP_REQUEST_TIME_ENTRY.TlsHandshakeClientLeg3End;
pub const WinHttpStreamWaitStart = WINHTTP_REQUEST_TIME_ENTRY.StreamWaitStart;
pub const WinHttpStreamWaitEnd = WINHTTP_REQUEST_TIME_ENTRY.StreamWaitEnd;
pub const WinHttpSendRequestStart = WINHTTP_REQUEST_TIME_ENTRY.SendRequestStart;
pub const WinHttpSendRequestHeadersCompressionStart = WINHTTP_REQUEST_TIME_ENTRY.SendRequestHeadersCompressionStart;
pub const WinHttpSendRequestHeadersCompressionEnd = WINHTTP_REQUEST_TIME_ENTRY.SendRequestHeadersCompressionEnd;
pub const WinHttpSendRequestHeadersEnd = WINHTTP_REQUEST_TIME_ENTRY.SendRequestHeadersEnd;
pub const WinHttpSendRequestEnd = WINHTTP_REQUEST_TIME_ENTRY.SendRequestEnd;
pub const WinHttpReceiveResponseStart = WINHTTP_REQUEST_TIME_ENTRY.ReceiveResponseStart;
pub const WinHttpReceiveResponseHeadersDecompressionStart = WINHTTP_REQUEST_TIME_ENTRY.ReceiveResponseHeadersDecompressionStart;
pub const WinHttpReceiveResponseHeadersDecompressionEnd = WINHTTP_REQUEST_TIME_ENTRY.ReceiveResponseHeadersDecompressionEnd;
pub const WinHttpReceiveResponseHeadersEnd = WINHTTP_REQUEST_TIME_ENTRY.ReceiveResponseHeadersEnd;
pub const WinHttpReceiveResponseBodyDecompressionDelta = WINHTTP_REQUEST_TIME_ENTRY.ReceiveResponseBodyDecompressionDelta;
pub const WinHttpReceiveResponseEnd = WINHTTP_REQUEST_TIME_ENTRY.ReceiveResponseEnd;
pub const WinHttpProxyTunnelStart = WINHTTP_REQUEST_TIME_ENTRY.ProxyTunnelStart;
pub const WinHttpProxyTunnelEnd = WINHTTP_REQUEST_TIME_ENTRY.ProxyTunnelEnd;
pub const WinHttpProxyTlsHandshakeClientLeg1Start = WINHTTP_REQUEST_TIME_ENTRY.ProxyTlsHandshakeClientLeg1Start;
pub const WinHttpProxyTlsHandshakeClientLeg1End = WINHTTP_REQUEST_TIME_ENTRY.ProxyTlsHandshakeClientLeg1End;
pub const WinHttpProxyTlsHandshakeClientLeg2Start = WINHTTP_REQUEST_TIME_ENTRY.ProxyTlsHandshakeClientLeg2Start;
pub const WinHttpProxyTlsHandshakeClientLeg2End = WINHTTP_REQUEST_TIME_ENTRY.ProxyTlsHandshakeClientLeg2End;
pub const WinHttpProxyTlsHandshakeClientLeg3Start = WINHTTP_REQUEST_TIME_ENTRY.ProxyTlsHandshakeClientLeg3Start;
pub const WinHttpProxyTlsHandshakeClientLeg3End = WINHTTP_REQUEST_TIME_ENTRY.ProxyTlsHandshakeClientLeg3End;
pub const WinHttpRequestTimeLast = WINHTTP_REQUEST_TIME_ENTRY.RequestTimeLast;
pub const WinHttpRequestTimeMax = WINHTTP_REQUEST_TIME_ENTRY.RequestTimeMax;
pub const WINHTTP_REQUEST_STAT_ENTRY = enum(i32) {
ConnectFailureCount = 0,
ProxyFailureCount = 1,
TlsHandshakeClientLeg1Size = 2,
TlsHandshakeServerLeg1Size = 3,
TlsHandshakeClientLeg2Size = 4,
TlsHandshakeServerLeg2Size = 5,
RequestHeadersSize = 6,
RequestHeadersCompressedSize = 7,
ResponseHeadersSize = 8,
ResponseHeadersCompressedSize = 9,
ResponseBodySize = 10,
ResponseBodyCompressedSize = 11,
ProxyTlsHandshakeClientLeg1Size = 12,
ProxyTlsHandshakeServerLeg1Size = 13,
ProxyTlsHandshakeClientLeg2Size = 14,
ProxyTlsHandshakeServerLeg2Size = 15,
RequestStatLast = 16,
RequestStatMax = 32,
};
pub const WinHttpConnectFailureCount = WINHTTP_REQUEST_STAT_ENTRY.ConnectFailureCount;
pub const WinHttpProxyFailureCount = WINHTTP_REQUEST_STAT_ENTRY.ProxyFailureCount;
pub const WinHttpTlsHandshakeClientLeg1Size = WINHTTP_REQUEST_STAT_ENTRY.TlsHandshakeClientLeg1Size;
pub const WinHttpTlsHandshakeServerLeg1Size = WINHTTP_REQUEST_STAT_ENTRY.TlsHandshakeServerLeg1Size;
pub const WinHttpTlsHandshakeClientLeg2Size = WINHTTP_REQUEST_STAT_ENTRY.TlsHandshakeClientLeg2Size;
pub const WinHttpTlsHandshakeServerLeg2Size = WINHTTP_REQUEST_STAT_ENTRY.TlsHandshakeServerLeg2Size;
pub const WinHttpRequestHeadersSize = WINHTTP_REQUEST_STAT_ENTRY.RequestHeadersSize;
pub const WinHttpRequestHeadersCompressedSize = WINHTTP_REQUEST_STAT_ENTRY.RequestHeadersCompressedSize;
pub const WinHttpResponseHeadersSize = WINHTTP_REQUEST_STAT_ENTRY.ResponseHeadersSize;
pub const WinHttpResponseHeadersCompressedSize = WINHTTP_REQUEST_STAT_ENTRY.ResponseHeadersCompressedSize;
pub const WinHttpResponseBodySize = WINHTTP_REQUEST_STAT_ENTRY.ResponseBodySize;
pub const WinHttpResponseBodyCompressedSize = WINHTTP_REQUEST_STAT_ENTRY.ResponseBodyCompressedSize;
pub const WinHttpProxyTlsHandshakeClientLeg1Size = WINHTTP_REQUEST_STAT_ENTRY.ProxyTlsHandshakeClientLeg1Size;
pub const WinHttpProxyTlsHandshakeServerLeg1Size = WINHTTP_REQUEST_STAT_ENTRY.ProxyTlsHandshakeServerLeg1Size;
pub const WinHttpProxyTlsHandshakeClientLeg2Size = WINHTTP_REQUEST_STAT_ENTRY.ProxyTlsHandshakeClientLeg2Size;
pub const WinHttpProxyTlsHandshakeServerLeg2Size = WINHTTP_REQUEST_STAT_ENTRY.ProxyTlsHandshakeServerLeg2Size;
pub const WinHttpRequestStatLast = WINHTTP_REQUEST_STAT_ENTRY.RequestStatLast;
pub const WinHttpRequestStatMax = WINHTTP_REQUEST_STAT_ENTRY.RequestStatMax;
pub const WINHTTP_EXTENDED_HEADER = extern struct {
Anonymous1: extern union {
pwszName: ?[*:0]const u16,
pszName: ?[*:0]const u8,
},
Anonymous2: extern union {
pwszValue: ?[*:0]const u16,
pszValue: ?[*:0]const u8,
},
};
pub const WINHTTP_HEADER_NAME = extern union {
pwszName: ?[*:0]const u16,
pszName: ?[*:0]const u8,
};
pub const WINHTTP_SECURE_DNS_SETTING = enum(i32) {
Default = 0,
ForcePlaintext = 1,
RequireEncryption = 2,
TryEncryptionWithFallback = 3,
Max = 4,
};
pub const WinHttpSecureDnsSettingDefault = WINHTTP_SECURE_DNS_SETTING.Default;
pub const WinHttpSecureDnsSettingForcePlaintext = WINHTTP_SECURE_DNS_SETTING.ForcePlaintext;
pub const WinHttpSecureDnsSettingRequireEncryption = WINHTTP_SECURE_DNS_SETTING.RequireEncryption;
pub const WinHttpSecureDnsSettingTryEncryptionWithFallback = WINHTTP_SECURE_DNS_SETTING.TryEncryptionWithFallback;
pub const WinHttpSecureDnsSettingMax = WINHTTP_SECURE_DNS_SETTING.Max;
pub const WINHTTP_CONNECTION_GROUP = extern struct {
cConnections: u32,
guidGroup: Guid,
};
pub const WINHTTP_HOST_CONNECTION_GROUP = extern struct {
pwszHost: ?[*:0]const u16,
cConnectionGroups: u32,
pConnectionGroups: ?*WINHTTP_CONNECTION_GROUP,
};
pub const WINHTTP_QUERY_CONNECTION_GROUP_RESULT = extern struct {
cHosts: u32,
pHostConnectionGroups: ?*WINHTTP_HOST_CONNECTION_GROUP,
};
pub const WINHTTP_HTTP2_RECEIVE_WINDOW = extern struct {
ulStreamWindow: u32,
ulStreamWindowUpdateDelta: u32,
};
pub const WINHTTP_FAILED_CONNECTION_RETRIES = extern struct {
dwMaxRetries: u32,
dwAllowedRetryConditions: u32,
};
pub const WINHTTP_CREDS = extern struct {
lpszUserName: ?PSTR,
lpszPassword: ?PSTR,
lpszRealm: ?PSTR,
dwAuthScheme: WINHTTP_CREDS_AUTHSCHEME,
lpszHostName: ?PSTR,
dwPort: u32,
};
pub const WINHTTP_CREDS_EX = extern struct {
lpszUserName: ?PSTR,
lpszPassword: ?PSTR,
lpszRealm: ?PSTR,
dwAuthScheme: WINHTTP_CREDS_AUTHSCHEME,
lpszHostName: ?PSTR,
dwPort: u32,
lpszUrl: ?PSTR,
};
pub const WINHTTP_STATUS_CALLBACK = fn(
hInternet: ?*anyopaque,
dwContext: usize,
dwInternetStatus: u32,
lpvStatusInformation: ?*anyopaque,
dwStatusInformationLength: u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub const LPWINHTTP_STATUS_CALLBACK = fn(
) callconv(@import("std").os.windows.WINAPI) void;
pub const WINHTTP_CURRENT_USER_IE_PROXY_CONFIG = extern struct {
fAutoDetect: BOOL,
lpszAutoConfigUrl: ?PWSTR,
lpszProxy: ?PWSTR,
lpszProxyBypass: ?PWSTR,
};
pub const WINHTTP_WEB_SOCKET_OPERATION = enum(i32) {
SEND_OPERATION = 0,
RECEIVE_OPERATION = 1,
CLOSE_OPERATION = 2,
SHUTDOWN_OPERATION = 3,
};
pub const WINHTTP_WEB_SOCKET_SEND_OPERATION = WINHTTP_WEB_SOCKET_OPERATION.SEND_OPERATION;
pub const WINHTTP_WEB_SOCKET_RECEIVE_OPERATION = WINHTTP_WEB_SOCKET_OPERATION.RECEIVE_OPERATION;
pub const WINHTTP_WEB_SOCKET_CLOSE_OPERATION = WINHTTP_WEB_SOCKET_OPERATION.CLOSE_OPERATION;
pub const WINHTTP_WEB_SOCKET_SHUTDOWN_OPERATION = WINHTTP_WEB_SOCKET_OPERATION.SHUTDOWN_OPERATION;
pub const WINHTTP_WEB_SOCKET_BUFFER_TYPE = enum(i32) {
BINARY_MESSAGE_BUFFER_TYPE = 0,
BINARY_FRAGMENT_BUFFER_TYPE = 1,
UTF8_MESSAGE_BUFFER_TYPE = 2,
UTF8_FRAGMENT_BUFFER_TYPE = 3,
CLOSE_BUFFER_TYPE = 4,
};
pub const WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE = WINHTTP_WEB_SOCKET_BUFFER_TYPE.BINARY_MESSAGE_BUFFER_TYPE;
pub const WINHTTP_WEB_SOCKET_BINARY_FRAGMENT_BUFFER_TYPE = WINHTTP_WEB_SOCKET_BUFFER_TYPE.BINARY_FRAGMENT_BUFFER_TYPE;
pub const WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE = WINHTTP_WEB_SOCKET_BUFFER_TYPE.UTF8_MESSAGE_BUFFER_TYPE;
pub const WINHTTP_WEB_SOCKET_UTF8_FRAGMENT_BUFFER_TYPE = WINHTTP_WEB_SOCKET_BUFFER_TYPE.UTF8_FRAGMENT_BUFFER_TYPE;
pub const WINHTTP_WEB_SOCKET_CLOSE_BUFFER_TYPE = WINHTTP_WEB_SOCKET_BUFFER_TYPE.CLOSE_BUFFER_TYPE;
pub const WINHTTP_WEB_SOCKET_CLOSE_STATUS = enum(i32) {
SUCCESS_CLOSE_STATUS = 1000,
ENDPOINT_TERMINATED_CLOSE_STATUS = 1001,
PROTOCOL_ERROR_CLOSE_STATUS = 1002,
INVALID_DATA_TYPE_CLOSE_STATUS = 1003,
EMPTY_CLOSE_STATUS = 1005,
ABORTED_CLOSE_STATUS = 1006,
INVALID_PAYLOAD_CLOSE_STATUS = 1007,
POLICY_VIOLATION_CLOSE_STATUS = 1008,
MESSAGE_TOO_BIG_CLOSE_STATUS = 1009,
UNSUPPORTED_EXTENSIONS_CLOSE_STATUS = 1010,
SERVER_ERROR_CLOSE_STATUS = 1011,
SECURE_HANDSHAKE_ERROR_CLOSE_STATUS = 1015,
};
pub const WINHTTP_WEB_SOCKET_SUCCESS_CLOSE_STATUS = WINHTTP_WEB_SOCKET_CLOSE_STATUS.SUCCESS_CLOSE_STATUS;
pub const WINHTTP_WEB_SOCKET_ENDPOINT_TERMINATED_CLOSE_STATUS = WINHTTP_WEB_SOCKET_CLOSE_STATUS.ENDPOINT_TERMINATED_CLOSE_STATUS;
pub const WINHTTP_WEB_SOCKET_PROTOCOL_ERROR_CLOSE_STATUS = WINHTTP_WEB_SOCKET_CLOSE_STATUS.PROTOCOL_ERROR_CLOSE_STATUS;
pub const WINHTTP_WEB_SOCKET_INVALID_DATA_TYPE_CLOSE_STATUS = WINHTTP_WEB_SOCKET_CLOSE_STATUS.INVALID_DATA_TYPE_CLOSE_STATUS;
pub const WINHTTP_WEB_SOCKET_EMPTY_CLOSE_STATUS = WINHTTP_WEB_SOCKET_CLOSE_STATUS.EMPTY_CLOSE_STATUS;
pub const WINHTTP_WEB_SOCKET_ABORTED_CLOSE_STATUS = WINHTTP_WEB_SOCKET_CLOSE_STATUS.ABORTED_CLOSE_STATUS;
pub const WINHTTP_WEB_SOCKET_INVALID_PAYLOAD_CLOSE_STATUS = WINHTTP_WEB_SOCKET_CLOSE_STATUS.INVALID_PAYLOAD_CLOSE_STATUS;
pub const WINHTTP_WEB_SOCKET_POLICY_VIOLATION_CLOSE_STATUS = WINHTTP_WEB_SOCKET_CLOSE_STATUS.POLICY_VIOLATION_CLOSE_STATUS;
pub const WINHTTP_WEB_SOCKET_MESSAGE_TOO_BIG_CLOSE_STATUS = WINHTTP_WEB_SOCKET_CLOSE_STATUS.MESSAGE_TOO_BIG_CLOSE_STATUS;
pub const WINHTTP_WEB_SOCKET_UNSUPPORTED_EXTENSIONS_CLOSE_STATUS = WINHTTP_WEB_SOCKET_CLOSE_STATUS.UNSUPPORTED_EXTENSIONS_CLOSE_STATUS;
pub const WINHTTP_WEB_SOCKET_SERVER_ERROR_CLOSE_STATUS = WINHTTP_WEB_SOCKET_CLOSE_STATUS.SERVER_ERROR_CLOSE_STATUS;
pub const WINHTTP_WEB_SOCKET_SECURE_HANDSHAKE_ERROR_CLOSE_STATUS = WINHTTP_WEB_SOCKET_CLOSE_STATUS.SECURE_HANDSHAKE_ERROR_CLOSE_STATUS;
pub const WINHTTP_WEB_SOCKET_ASYNC_RESULT = extern struct {
AsyncResult: WINHTTP_ASYNC_RESULT,
Operation: WINHTTP_WEB_SOCKET_OPERATION,
};
pub const WINHTTP_WEB_SOCKET_STATUS = extern struct {
dwBytesTransferred: u32,
eBufferType: WINHTTP_WEB_SOCKET_BUFFER_TYPE,
};
pub const WINHTTP_CONNECTION_INFO = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
cbSize: u32,
LocalAddress: SOCKADDR_STORAGE,
RemoteAddress: SOCKADDR_STORAGE,
},
.X86 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
cbSize: u32,
LocalAddress: SOCKADDR_STORAGE,
RemoteAddress: SOCKADDR_STORAGE,
},
};
pub const WINHTTP_REQUEST_TIMES = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
cTimes: u32,
rgullTimes: [64]u64,
},
.X86 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
cTimes: u32,
rgullTimes: [64]u64,
},
};
pub const WINHTTP_REQUEST_STATS = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
ullFlags: u64,
ulIndex: u32,
cStats: u32,
rgullStats: [32]u64,
},
.X86 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
ullFlags: u64,
ulIndex: u32,
cStats: u32,
rgullStats: [32]u64,
},
};
pub const WINHTTP_MATCH_CONNECTION_GUID = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
ConnectionGuid: Guid,
ullFlags: u64,
},
.X86 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
ConnectionGuid: Guid,
ullFlags: u64,
},
};
pub const WINHTTP_RESOLVER_CACHE_CONFIG = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
ulMaxResolverCacheEntries: u32,
ulMaxCacheEntryAge: u32,
ulMinCacheEntryTtl: u32,
SecureDnsSetting: WINHTTP_SECURE_DNS_SETTING,
ullConnResolutionWaitTime: u64,
ullFlags: u64,
},
.X86 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
ulMaxResolverCacheEntries: u32,
ulMaxCacheEntryAge: u32,
ulMinCacheEntryTtl: u32,
SecureDnsSetting: WINHTTP_SECURE_DNS_SETTING,
ullConnResolutionWaitTime: u64,
ullFlags: u64,
},
};
//--------------------------------------------------------------------------------
// Section: Functions (51)
//--------------------------------------------------------------------------------
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpSetStatusCallback(
hInternet: ?*anyopaque,
lpfnInternetCallback: ?WINHTTP_STATUS_CALLBACK,
dwNotificationFlags: u32,
dwReserved: usize,
) callconv(@import("std").os.windows.WINAPI) ?WINHTTP_STATUS_CALLBACK;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpTimeFromSystemTime(
pst: ?*const SYSTEMTIME,
pwszTime: *[62]u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpTimeToSystemTime(
pwszTime: ?[*:0]const u16,
pst: ?*SYSTEMTIME,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpCrackUrl(
pwszUrl: [*:0]const u16,
dwUrlLength: u32,
dwFlags: u32,
lpUrlComponents: ?*URL_COMPONENTS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpCreateUrl(
lpUrlComponents: ?*URL_COMPONENTS,
dwFlags: WIN_HTTP_CREATE_URL_FLAGS,
pwszUrl: ?[*:0]u16,
pdwUrlLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpCheckPlatform(
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpGetDefaultProxyConfiguration(
pProxyInfo: ?*WINHTTP_PROXY_INFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpSetDefaultProxyConfiguration(
pProxyInfo: ?*WINHTTP_PROXY_INFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpOpen(
pszAgentW: ?[*:0]const u16,
dwAccessType: WINHTTP_ACCESS_TYPE,
pszProxyW: ?[*:0]const u16,
pszProxyBypassW: ?[*:0]const u16,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpCloseHandle(
hInternet: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpConnect(
hSession: ?*anyopaque,
pswzServerName: ?[*:0]const u16,
nServerPort: INTERNET_PORT,
dwReserved: u32,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpReadData(
hRequest: ?*anyopaque,
// TODO: what to do with BytesParamIndex 2?
lpBuffer: ?*anyopaque,
dwNumberOfBytesToRead: u32,
lpdwNumberOfBytesRead: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "WINHTTP" fn WinHttpReadDataEx(
hRequest: ?*anyopaque,
// TODO: what to do with BytesParamIndex 2?
lpBuffer: ?*anyopaque,
dwNumberOfBytesToRead: u32,
lpdwNumberOfBytesRead: ?*u32,
ullFlags: u64,
cbProperty: u32,
// TODO: what to do with BytesParamIndex 5?
pvProperty: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpWriteData(
hRequest: ?*anyopaque,
// TODO: what to do with BytesParamIndex 2?
lpBuffer: ?*const anyopaque,
dwNumberOfBytesToWrite: u32,
lpdwNumberOfBytesWritten: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpQueryDataAvailable(
hRequest: ?*anyopaque,
lpdwNumberOfBytesAvailable: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpQueryOption(
hInternet: ?*anyopaque,
dwOption: u32,
// TODO: what to do with BytesParamIndex 3?
lpBuffer: ?*anyopaque,
lpdwBufferLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpSetOption(
hInternet: ?*anyopaque,
dwOption: u32,
lpBuffer: ?[*]u8,
dwBufferLength: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpSetTimeouts(
hInternet: ?*anyopaque,
nResolveTimeout: i32,
nConnectTimeout: i32,
nSendTimeout: i32,
nReceiveTimeout: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpOpenRequest(
hConnect: ?*anyopaque,
pwszVerb: ?[*:0]const u16,
pwszObjectName: ?[*:0]const u16,
pwszVersion: ?[*:0]const u16,
pwszReferrer: ?[*:0]const u16,
ppwszAcceptTypes: ?*?PWSTR,
dwFlags: WINHTTP_OPEN_REQUEST_FLAGS,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpAddRequestHeaders(
hRequest: ?*anyopaque,
lpszHeaders: [*:0]const u16,
dwHeadersLength: u32,
dwModifiers: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "WINHTTP" fn WinHttpAddRequestHeadersEx(
hRequest: ?*anyopaque,
dwModifiers: u32,
ullFlags: u64,
ullExtra: u64,
cHeaders: u32,
pHeaders: [*]WINHTTP_EXTENDED_HEADER,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpSendRequest(
hRequest: ?*anyopaque,
lpszHeaders: ?[*:0]const u16,
dwHeadersLength: u32,
// TODO: what to do with BytesParamIndex 4?
lpOptional: ?*anyopaque,
dwOptionalLength: u32,
dwTotalLength: u32,
dwContext: usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpSetCredentials(
hRequest: ?*anyopaque,
AuthTargets: u32,
AuthScheme: u32,
pwszUserName: ?[*:0]const u16,
pwszPassword: ?[*:0]const u16,
pAuthParams: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpQueryAuthSchemes(
hRequest: ?*anyopaque,
lpdwSupportedSchemes: ?*u32,
lpdwFirstScheme: ?*u32,
pdwAuthTarget: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpReceiveResponse(
hRequest: ?*anyopaque,
lpReserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpQueryHeaders(
hRequest: ?*anyopaque,
dwInfoLevel: u32,
pwszName: ?[*:0]const u16,
// TODO: what to do with BytesParamIndex 4?
lpBuffer: ?*anyopaque,
lpdwBufferLength: ?*u32,
lpdwIndex: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "WINHTTP" fn WinHttpQueryHeadersEx(
hRequest: ?*anyopaque,
dwInfoLevel: u32,
ullFlags: u64,
uiCodePage: u32,
pdwIndex: ?*u32,
pHeaderName: ?*WINHTTP_HEADER_NAME,
// TODO: what to do with BytesParamIndex 7?
pBuffer: ?*anyopaque,
pdwBufferLength: ?*u32,
ppHeaders: ?[*]?*WINHTTP_EXTENDED_HEADER,
pdwHeadersCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "WINHTTP" fn WinHttpQueryConnectionGroup(
hInternet: ?*anyopaque,
pGuidConnection: ?*const Guid,
ullFlags: u64,
ppResult: ?*?*WINHTTP_QUERY_CONNECTION_GROUP_RESULT,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "WINHTTP" fn WinHttpFreeQueryConnectionGroupResult(
pResult: ?*WINHTTP_QUERY_CONNECTION_GROUP_RESULT,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpDetectAutoProxyConfigUrl(
dwAutoDetectFlags: u32,
ppwstrAutoConfigUrl: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpGetProxyForUrl(
hSession: ?*anyopaque,
lpcwszUrl: ?[*:0]const u16,
pAutoProxyOptions: ?*WINHTTP_AUTOPROXY_OPTIONS,
pProxyInfo: ?*WINHTTP_PROXY_INFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "WINHTTP" fn WinHttpCreateProxyResolver(
hSession: ?*anyopaque,
phResolver: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "WINHTTP" fn WinHttpGetProxyForUrlEx(
hResolver: ?*anyopaque,
pcwszUrl: ?[*:0]const u16,
pAutoProxyOptions: ?*WINHTTP_AUTOPROXY_OPTIONS,
pContext: usize,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "WINHTTP" fn WinHttpGetProxyForUrlEx2(
hResolver: ?*anyopaque,
pcwszUrl: ?[*:0]const u16,
pAutoProxyOptions: ?*WINHTTP_AUTOPROXY_OPTIONS,
cbInterfaceSelectionContext: u32,
// TODO: what to do with BytesParamIndex 3?
pInterfaceSelectionContext: ?*u8,
pContext: usize,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "WINHTTP" fn WinHttpGetProxyResult(
hResolver: ?*anyopaque,
pProxyResult: ?*WINHTTP_PROXY_RESULT,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "WINHTTP" fn WinHttpGetProxyResultEx(
hResolver: ?*anyopaque,
pProxyResultEx: ?*WINHTTP_PROXY_RESULT_EX,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "WINHTTP" fn WinHttpFreeProxyResult(
pProxyResult: ?*WINHTTP_PROXY_RESULT,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "WINHTTP" fn WinHttpFreeProxyResultEx(
pProxyResultEx: ?*WINHTTP_PROXY_RESULT_EX,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows8.0'
pub extern "WINHTTP" fn WinHttpResetAutoProxy(
hSession: ?*anyopaque,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WINHTTP" fn WinHttpGetIEProxyConfigForCurrentUser(
pProxyConfig: ?*WINHTTP_CURRENT_USER_IE_PROXY_CONFIG,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "WINHTTP" fn WinHttpWriteProxySettings(
hSession: ?*anyopaque,
fForceUpdate: BOOL,
pWinHttpProxySettings: ?*WINHTTP_PROXY_SETTINGS,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "WINHTTP" fn WinHttpReadProxySettings(
hSession: ?*anyopaque,
pcwszConnectionName: ?[*:0]const u16,
fFallBackToDefaultSettings: BOOL,
fSetAutoDiscoverForDefaultSettings: BOOL,
pdwSettingsVersion: ?*u32,
pfDefaultSettingsAreReturned: ?*BOOL,
pWinHttpProxySettings: ?*WINHTTP_PROXY_SETTINGS,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "WINHTTP" fn WinHttpFreeProxySettings(
pWinHttpProxySettings: ?*WINHTTP_PROXY_SETTINGS,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "WINHTTP" fn WinHttpGetProxySettingsVersion(
hSession: ?*anyopaque,
pdwProxySettingsVersion: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "WINHTTP" fn WinHttpSetProxySettingsPerUser(
fProxySettingsPerUser: BOOL,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "WINHTTP" fn WinHttpWebSocketCompleteUpgrade(
hRequest: ?*anyopaque,
pContext: usize,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows8.0'
pub extern "WINHTTP" fn WinHttpWebSocketSend(
hWebSocket: ?*anyopaque,
eBufferType: WINHTTP_WEB_SOCKET_BUFFER_TYPE,
pvBuffer: ?[*]u8,
dwBufferLength: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "WINHTTP" fn WinHttpWebSocketReceive(
hWebSocket: ?*anyopaque,
// TODO: what to do with BytesParamIndex 2?
pvBuffer: ?*anyopaque,
dwBufferLength: u32,
pdwBytesRead: ?*u32,
peBufferType: ?*WINHTTP_WEB_SOCKET_BUFFER_TYPE,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "WINHTTP" fn WinHttpWebSocketShutdown(
hWebSocket: ?*anyopaque,
usStatus: u16,
// TODO: what to do with BytesParamIndex 3?
pvReason: ?*anyopaque,
dwReasonLength: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "WINHTTP" fn WinHttpWebSocketClose(
hWebSocket: ?*anyopaque,
usStatus: u16,
// TODO: what to do with BytesParamIndex 3?
pvReason: ?*anyopaque,
dwReasonLength: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "WINHTTP" fn WinHttpWebSocketQueryCloseStatus(
hWebSocket: ?*anyopaque,
pusStatus: ?*u16,
// TODO: what to do with BytesParamIndex 3?
pvReason: ?*anyopaque,
dwReasonLength: u32,
pdwReasonLengthConsumed: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (0)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
},
.wide => struct {
},
.unspecified => if (@import("builtin").is_test) struct {
} else struct {
},
};
//--------------------------------------------------------------------------------
// Section: Imports (8)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BOOL = @import("../foundation.zig").BOOL;
const FILETIME = @import("../foundation.zig").FILETIME;
const HANDLE = @import("../foundation.zig").HANDLE;
const PSTR = @import("../foundation.zig").PSTR;
const PWSTR = @import("../foundation.zig").PWSTR;
const SOCKADDR_STORAGE = @import("../networking/win_sock.zig").SOCKADDR_STORAGE;
const SYSTEMTIME = @import("../foundation.zig").SYSTEMTIME;
test {
// The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476
if (@hasDecl(@This(), "WINHTTP_STATUS_CALLBACK")) { _ = WINHTTP_STATUS_CALLBACK; }
if (@hasDecl(@This(), "LPWINHTTP_STATUS_CALLBACK")) { _ = LPWINHTTP_STATUS_CALLBACK; }
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
} | win32/networking/win_http.zig |
const std = @import("std");
const testing = std.testing;
const allocator = std.testing.allocator;
const desc_usize = std.sort.desc(usize);
pub const Map = struct {
const Pos = struct {
x: isize,
y: isize,
pub fn init(x: isize, y: isize) Pos {
var self = Pos{ .x = x, .y = y };
return self;
}
};
width: usize,
height: usize,
data: std.AutoHashMap(Pos, usize),
seen: std.AutoHashMap(Pos, void),
pub fn init() Map {
var self = Map{
.width = 0,
.height = 0,
.data = std.AutoHashMap(Pos, usize).init(allocator),
.seen = std.AutoHashMap(Pos, void).init(allocator),
};
return self;
}
pub fn deinit(self: *Map) void {
self.seen.deinit();
self.data.deinit();
}
pub fn process_line(self: *Map, data: []const u8) !void {
if (self.width == 0) {
self.width = data.len;
}
if (self.width != data.len) {
return error.ChangingWidth;
}
const sy = @intCast(isize, self.height);
for (data) |num, x| {
const sx = @intCast(isize, x);
const p = Pos.init(sx, sy);
const n = num - '0';
try self.data.put(p, n);
}
self.height += 1;
}
pub fn get_total_risk(self: Map) usize {
var risk: usize = 0;
var x: isize = 0;
while (x < self.width) : (x += 1) {
var y: isize = 0;
while (y < self.height) : (y += 1) {
if (!self.is_basin(x, y)) continue;
risk += 1 + self.get_height(x, y);
}
}
return risk;
}
pub fn get_largest_n_basins_product(self: *Map, n: usize) !usize {
var sizes = std.ArrayList(usize).init(allocator);
defer sizes.deinit();
self.seen.clearRetainingCapacity();
var x: isize = 0;
while (x < self.width) : (x += 1) {
var y: isize = 0;
while (y < self.height) : (y += 1) {
if (!self.is_basin(x, y)) continue;
const size = try self.walk_basin(x, y);
if (size == 0) continue;
sizes.append(size) catch unreachable;
}
}
std.sort.sort(usize, sizes.items, {}, desc_usize);
var product: usize = 1;
for (sizes.items[0..n]) |s| {
product *= s;
}
return product;
}
fn get_height(self: Map, x: isize, y: isize) usize {
const p = Pos.init(x, y);
return self.data.get(p) orelse std.math.maxInt(usize);
}
fn is_basin(self: Map, x: isize, y: isize) bool {
var h = self.get_height(x, y);
if (h >= self.get_height(x - 1, y)) return false;
if (h >= self.get_height(x + 1, y)) return false;
if (h >= self.get_height(x, y - 1)) return false;
if (h >= self.get_height(x, y + 1)) return false;
return true;
}
fn walk_basin(self: *Map, x: isize, y: isize) !usize {
const p = Pos.init(x, y);
if (self.seen.contains(p)) return 0;
self.seen.put(p, {}) catch unreachable;
var size: usize = 1;
size += try self.walk_neighbors(x - 1, y);
size += try self.walk_neighbors(x + 1, y);
size += try self.walk_neighbors(x, y - 1);
size += try self.walk_neighbors(x, y + 1);
return size;
}
const WalkErrors = error{OutOfMemory};
fn walk_neighbors(self: *Map, x: isize, y: isize) WalkErrors!usize {
const p = Pos.init(x, y);
if (self.seen.contains(p)) return 0;
if (!self.data.contains(p)) return 0;
const h = self.get_height(x, y);
if (h == 9) return 0;
try self.seen.put(p, {});
var size: usize = 1;
if (h < self.get_height(x - 1, y)) size += try self.walk_neighbors(x - 1, y);
if (h < self.get_height(x + 1, y)) size += try self.walk_neighbors(x + 1, y);
if (h < self.get_height(x, y - 1)) size += try self.walk_neighbors(x, y - 1);
if (h < self.get_height(x, y + 1)) size += try self.walk_neighbors(x, y + 1);
return size;
}
};
test "sample part a" {
const data: []const u8 =
\\2199943210
\\3987894921
\\9856789892
\\8767896789
\\9899965678
;
var map = Map.init();
defer map.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
try map.process_line(line);
}
const risk = map.get_total_risk();
try testing.expect(risk == 15);
}
test "sample part b" {
const data: []const u8 =
\\2199943210
\\3987894921
\\9856789892
\\8767896789
\\9899965678
;
var map = Map.init();
defer map.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
try map.process_line(line);
}
const product = try map.get_largest_n_basins_product(3);
try testing.expect(product == 1134);
} | 2021/p09/map.zig |
const base = @import("../base.zig");
const gen = @import("../gen.zig");
const COMMON = [_:null]?base.Segment{
.{ .offset = 30 * 0, .month = 1, .day_start = 1, .day_end = 30 },
.{ .offset = 30 * 1, .month = 2, .day_start = 1, .day_end = 30 },
.{ .offset = 30 * 2, .month = 3, .day_start = 1, .day_end = 30 },
.{ .offset = 30 * 3, .month = 4, .day_start = 1, .day_end = 30 },
.{ .offset = 30 * 4, .month = 5, .day_start = 1, .day_end = 30 },
.{ .offset = 30 * 5, .month = 6, .day_start = 1, .day_end = 30 },
.{ .offset = 30 * 6, .month = 7, .day_start = 1, .day_end = 30 },
.{ .offset = 30 * 7, .month = 8, .day_start = 1, .day_end = 30 },
.{ .offset = 30 * 8, .month = 9, .day_start = 1, .day_end = 30 },
.{ .offset = 30 * 9, .month = 10, .day_start = 1, .day_end = 30 },
.{ .offset = 30 * 10, .month = 11, .day_start = 1, .day_end = 30 },
.{ .offset = 30 * 11, .month = 12, .day_start = 1, .day_end = 30 },
.{ .offset = 30 * 12, .month = 0, .day_start = 1, .day_end = 5 },
};
const IC = [_:null]?base.Intercalary{
gen.initIc(.{ .month = 0, .day = 1 }, COMMON[0..COMMON.len], COMMON[0..COMMON.len]),
gen.initIc(.{ .month = 0, .day = 2 }, COMMON[0..COMMON.len], COMMON[0..COMMON.len]),
gen.initIc(.{ .month = 0, .day = 3 }, COMMON[0..COMMON.len], COMMON[0..COMMON.len]),
gen.initIc(.{ .month = 0, .day = 4 }, COMMON[0..COMMON.len], COMMON[0..COMMON.len]),
gen.initIc(.{ .month = 0, .day = 5 }, COMMON[0..COMMON.len], COMMON[0..COMMON.len]),
};
var ic_var: [IC.len:null]?base.Intercalary = IC;
var common_var: [COMMON.len:null]?base.Segment = COMMON;
pub const ancient_egyptian = base.Cal{
.intercalary_list = @as([*:null]?base.Intercalary, &ic_var),
.common_lookup_list = @as([*:null]?base.Segment, &common_var),
.leap_lookup_list = @as([*:null]?base.Segment, &common_var),
.leap_cycle = .{
.year_count = 1,
.leap_year_count = 0,
.offset_years = 0,
.common_days = gen.dayCount(COMMON[0..COMMON.len]),
.leap_days = 0,
.offset_days = 0,
.skip100 = false,
.skip4000 = false,
.symmetric = false,
},
.week = .{
.start = @enumToInt(base.Weekday10.Primidi),
.length = gen.lastOfEnum(base.Weekday10),
.continuous = false,
},
.epoch_mjd = -951363, //Day before 1 Thoth, 1 Nabonassar
.common_month_max = gen.monthMax(COMMON[0..COMMON.len]),
.leap_month_max = gen.monthMax(COMMON[0..COMMON.len]),
.year0 = true,
}; | src/cal/ancient_egyptian.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const Inst = union(enum) { forward: i32, down: i32, up: i32 };
const Day2Err = error{InvalidInstruction};
const input = @embedFile("../inputs/day02.txt");
pub fn run(alloc: Allocator, stdout_: anytype) !void {
const parsed: ArrayList(Inst) = try parseInput(alloc);
defer parsed.deinit();
const res1 = try part1(parsed.items);
const res2 = try part2(parsed.items);
if (stdout_) |stdout| {
try stdout.print("Part 1: {}\n", .{res1});
try stdout.print("Part 2: {}\n", .{res2});
}
}
fn part1(parsed: []const Inst) !i64 {
var depth: i64 = 0;
var position: i64 = 0;
for (parsed) |inst| {
switch (inst) {
.forward => |num| position += num,
.down => |num| depth += num,
.up => |num| depth -= num,
}
}
return depth * position;
}
fn part2(parsed: []const Inst) !i64 {
var depth: i64 = 0;
var position: i64 = 0;
var aim: i32 = 0;
for (parsed) |inst| {
switch (inst) {
.forward => |num| {
position += num;
depth += aim * num;
},
.down => |num| aim += num,
.up => |num| aim -= num,
}
}
return depth * position;
}
/// Caller must deinit return value with a call to `.deinit()` when done.
fn parseInput(alloc: Allocator) !ArrayList(Inst) {
var list = ArrayList(Inst).init(alloc);
var lines = std.mem.tokenize(u8, input, "\r\n");
while (lines.next()) |line| {
try list.append(try parseInstruction(line));
}
return list;
}
fn parseInstruction(line: []const u8) !Inst {
var parts = std.mem.split(u8, line, " ");
const kind = parts.next() orelse return Day2Err.InvalidInstruction;
const num_str = parts.next() orelse return Day2Err.InvalidInstruction;
const num = try std.fmt.parseInt(i32, num_str, 0);
if (std.mem.eql(u8, kind, "forward")) {
return Inst{ .forward = num };
} else if (std.mem.eql(u8, kind, "down")) {
return Inst{ .down = num };
} else if (std.mem.eql(u8, kind, "up")) {
return Inst{ .up = num };
} else {
return Day2Err.InvalidInstruction;
}
} | src/day02.zig |
const std = @import("std");
const fs = std.fs;
const json = std.json;
const assert = std.debug.assert;
const Record = struct {
timestamp: u64,
benchmark_name: []const u8,
allocator: WhichAllocator,
commit_hash: [20]u8,
error_message: []const u8 = &[0]u8{},
samples_taken: u64 = 0,
wall_time_median: u64 = 0,
wall_time_mean: u64 = 0,
wall_time_min: u64 = 0,
wall_time_max: u64 = 0,
utime_median: u64 = 0,
utime_mean: u64 = 0,
utime_min: u64 = 0,
utime_max: u64 = 0,
stime_median: u64 = 0,
stime_mean: u64 = 0,
stime_min: u64 = 0,
stime_max: u64 = 0,
maxrss: u64 = 0,
baseline_error_message: []const u8 = &[0]u8{},
baseline_samples_taken: u64 = 0,
baseline_wall_time_median: u64 = 0,
baseline_wall_time_mean: u64 = 0,
baseline_wall_time_min: u64 = 0,
baseline_wall_time_max: u64 = 0,
baseline_utime_median: u64 = 0,
baseline_utime_mean: u64 = 0,
baseline_utime_min: u64 = 0,
baseline_utime_max: u64 = 0,
baseline_stime_median: u64 = 0,
baseline_stime_mean: u64 = 0,
baseline_stime_min: u64 = 0,
baseline_stime_max: u64 = 0,
baseline_maxrss: u64 = 0,
const WhichAllocator = enum {
/// malloc/realloc/free
libc,
/// the default general purpose allocator in the zig std lib.
/// currently std.heap.page_allocator
std_gpa,
};
const Key = struct {
commit_hash: [20]u8,
benchmark_name: []const u8,
allocator: Record.WhichAllocator,
fn eql(self: Key, other: Key) bool {
return self.allocator == other.allocator and
std.mem.eql(u8, &self.commit_hash, &other.commit_hash) and
std.mem.eql(u8, self.benchmark_name, other.benchmark_name);
}
};
};
fn jsonToRecord(
arena: *std.mem.Allocator,
/// main object
mo: json.Value,
/// baseline object
bo: json.Value,
timestamp: u64,
benchmark_name: []const u8,
commit_hash: [20]u8,
which_allocator: Record.WhichAllocator,
) !Record {
// Example success output of benchmark program:
// {"samples_taken":3,"wall_time":{"median":1922782021,"mean":1922782021,"min":1922782021,"max":1922782021},"utime":{"median":1872974000,"mean":1872974000,"min":1872974000,"max":1872974000},"stime":{"median":49022000,"mean":49022000,"min":49022000,"max":49022000},"maxrss":66240}
//
// Example failure output of the benchmark program:
// FileNotFound
var record: Record = .{
.timestamp = timestamp,
.benchmark_name = try arena.dupe(u8, benchmark_name),
.commit_hash = commit_hash,
.allocator = which_allocator,
};
if (mo == .String) {
record.error_message = try arena.dupe(u8, mo.String);
} else {
record.samples_taken = @intCast(u64, mo.Object.getValue("samples_taken").?.Integer);
record.wall_time_median = @intCast(u64, mo.Object.getValue("wall_time").?.Object.getValue("median").?.Integer);
record.wall_time_mean = @intCast(u64, mo.Object.getValue("wall_time").?.Object.getValue("mean").?.Integer);
record.wall_time_min = @intCast(u64, mo.Object.getValue("wall_time").?.Object.getValue("min").?.Integer);
record.wall_time_max = @intCast(u64, mo.Object.getValue("wall_time").?.Object.getValue("max").?.Integer);
record.utime_median = @intCast(u64, mo.Object.getValue("utime").?.Object.getValue("median").?.Integer);
record.utime_mean = @intCast(u64, mo.Object.getValue("utime").?.Object.getValue("mean").?.Integer);
record.utime_min = @intCast(u64, mo.Object.getValue("utime").?.Object.getValue("min").?.Integer);
record.utime_max = @intCast(u64, mo.Object.getValue("utime").?.Object.getValue("max").?.Integer);
record.stime_median = @intCast(u64, mo.Object.getValue("stime").?.Object.getValue("median").?.Integer);
record.stime_mean = @intCast(u64, mo.Object.getValue("stime").?.Object.getValue("mean").?.Integer);
record.stime_min = @intCast(u64, mo.Object.getValue("stime").?.Object.getValue("min").?.Integer);
record.stime_max = @intCast(u64, mo.Object.getValue("stime").?.Object.getValue("max").?.Integer);
record.maxrss = @intCast(u64, mo.Object.getValue("maxrss").?.Integer);
}
if (bo == .String) {
record.error_message = try arena.dupe(u8, bo.String);
} else {
record.baseline_samples_taken = @intCast(u64, bo.Object.getValue("samples_taken").?.Integer);
record.baseline_wall_time_median = @intCast(u64, bo.Object.getValue("wall_time").?.Object.getValue("median").?.Integer);
record.baseline_wall_time_mean = @intCast(u64, bo.Object.getValue("wall_time").?.Object.getValue("mean").?.Integer);
record.baseline_wall_time_min = @intCast(u64, bo.Object.getValue("wall_time").?.Object.getValue("min").?.Integer);
record.baseline_wall_time_max = @intCast(u64, bo.Object.getValue("wall_time").?.Object.getValue("max").?.Integer);
record.baseline_utime_median = @intCast(u64, bo.Object.getValue("utime").?.Object.getValue("median").?.Integer);
record.baseline_utime_mean = @intCast(u64, bo.Object.getValue("utime").?.Object.getValue("mean").?.Integer);
record.baseline_utime_min = @intCast(u64, bo.Object.getValue("utime").?.Object.getValue("min").?.Integer);
record.baseline_utime_max = @intCast(u64, bo.Object.getValue("utime").?.Object.getValue("max").?.Integer);
record.baseline_stime_median = @intCast(u64, bo.Object.getValue("stime").?.Object.getValue("median").?.Integer);
record.baseline_stime_mean = @intCast(u64, bo.Object.getValue("stime").?.Object.getValue("mean").?.Integer);
record.baseline_stime_min = @intCast(u64, bo.Object.getValue("stime").?.Object.getValue("min").?.Integer);
record.baseline_stime_max = @intCast(u64, bo.Object.getValue("stime").?.Object.getValue("max").?.Integer);
record.baseline_maxrss = @intCast(u64, bo.Object.getValue("maxrss").?.Integer);
}
return record;
}
const records_csv_path = "records.csv";
const comma = ",";
const zig_src_root = "zig-builds/src";
const zig_src_build = "zig-builds/src/build";
const zig_src_bin = "zig-builds/src/build/zig";
const CommitTable = std.HashMap(
Record.Key,
usize,
std.hash_map.getAutoHashStratFn(Record.Key, .Deep),
Record.Key.eql,
);
const poll_timeout = 60 * std.time.ns_per_s;
pub fn main() !void {
const gpa = std.heap.page_allocator;
var arena_state = std.heap.ArenaAllocator.init(gpa);
defer arena_state.deinit();
const arena = &arena_state.allocator;
const args = try std.process.argsAlloc(arena);
var auto_commit_and_push = false;
for (args[1..]) |arg| {
if (std.mem.eql(u8, arg, "--auto-commit-and-push")) {
auto_commit_and_push = true;
} else {
std.debug.warn("unrecognized command line parameter: '{}'\n", .{arg});
std.process.exit(1);
}
}
// Load CSV into memory
std.debug.warn("Loading CSV data...\n", .{});
var records = std.ArrayList(Record).init(gpa);
defer records.deinit();
var commit_table = CommitTable.init(gpa);
defer commit_table.deinit();
{
const csv_text = try fs.cwd().readFileAlloc(gpa, records_csv_path, 2 * 1024 * 1024 * 1024);
defer gpa.free(csv_text);
var field_indexes: [@typeInfo(Record).Struct.fields.len]usize = undefined;
var seen_fields = [1]bool{false} ** field_indexes.len;
var line_it = std.mem.split(csv_text, "\n");
{
const first_line = line_it.next() orelse {
std.debug.warn("empty CSV file", .{});
std.process.exit(1);
};
var csv_index: usize = 0;
var it = std.mem.split(first_line, comma);
while (it.next()) |field_name| : (csv_index += 1) {
if (csv_index >= field_indexes.len) {
std.debug.warn("extra CSV field: {}\n", .{field_name});
std.process.exit(1);
}
const field_index = fieldIndex(Record, field_name) orelse {
std.debug.warn("bad CSV field name: {}\n", .{field_name});
std.process.exit(1);
};
//std.debug.warn("found field '{}' = {}\n", .{ field_name, field_index });
field_indexes[csv_index] = field_index;
seen_fields[field_index] = true;
}
inline for (@typeInfo(Record).Struct.fields) |field, i| {
if (!seen_fields[i]) {
std.debug.warn("missing CSV field: {}", .{field.name});
std.process.exit(1);
}
}
}
var line_index: usize = 1;
while (line_it.next()) |line| : (line_index += 1) {
if (std.mem.eql(u8, line, "")) continue; // Skip blank lines.
var it = std.mem.split(line, comma);
var csv_index: usize = 0;
const record_index = records.items.len;
const record = try records.addOne();
while (it.next()) |field| : (csv_index += 1) {
if (csv_index >= field_indexes.len) {
std.debug.warn("extra CSV field on line {}\n", .{line_index + 1});
std.process.exit(1);
}
setRecordField(arena, record, field, field_indexes[csv_index]);
}
if (csv_index != field_indexes.len) {
std.debug.warn("CSV line {} missing a field\n", .{line_index + 1});
std.process.exit(1);
}
const key: Record.Key = .{
.commit_hash = record.commit_hash,
.benchmark_name = record.benchmark_name,
.allocator = record.allocator,
};
if (try commit_table.put(key, record_index)) |existing| {
const existing_record = records.items[existing.value];
_ = commit_table.putAssumeCapacity(key, existing.value);
records.shrink(records.items.len - 1);
}
}
}
var manifest_parser = json.Parser.init(gpa, false);
const manifest_text = try fs.cwd().readFileAlloc(gpa, "benchmarks/manifest.json", 3 * 1024 * 1024);
const manifest_tree = try manifest_parser.parse(manifest_text);
var queue = std.ArrayList([20]u8).init(gpa);
defer queue.deinit();
var last_time_slept = false;
while (true) {
queue.shrink(0);
// Detect queue.txt items
const queue_txt_path = "queue.txt";
if (fs.cwd().readFileAlloc(gpa, queue_txt_path, 1024 * 1024)) |queue_txt| {
defer gpa.free(queue_txt);
var it = std.mem.tokenize(queue_txt, " \r\n\t");
while (it.next()) |commit_txt| {
const commit = parseCommit(commit_txt) catch |err| {
std.debug.warn("bad commit format: '{}': {}\n", .{ commit_txt, @errorName(err) });
continue;
};
try queue.append(commit);
}
} else |err| {
std.debug.warn("unable to read {}: {}\n", .{ queue_txt_path, @errorName(err) });
}
// Eliminate the ones already done.
{
var queue_index: usize = 0;
while (queue_index < queue.items.len) {
const queue_commit = queue.items[queue_index];
if (isCommitDone(manifest_tree.root, &commit_table, queue_commit)) {
_ = queue.orderedRemove(queue_index);
continue;
}
queue_index += 1;
}
}
{
const baf = try std.io.BufferedAtomicFile.create(gpa, fs.cwd(), queue_txt_path, .{});
defer baf.destroy();
const out = baf.stream();
for (queue.items) |commit| {
try out.print("{x}\n", .{commit});
}
try baf.finish();
}
// Detect changes to zig master branch
while (true) {
exec(gpa, &[_][]const u8{ "git", "fetch", "origin", "--prune", "--tags" }, .{
.cwd = zig_src_root,
}) catch |err| {
std.debug.warn("unable to fetch latest git commits: {}\n", .{@errorName(err)});
std.time.sleep(poll_timeout);
continue;
};
const commit_str = execCapture(gpa, &[_][]const u8{
"git", "log",
"-n1", "origin/master",
"--pretty=format:%H",
}, .{
.cwd = zig_src_root,
}) catch |err| {
std.debug.warn("unable to check latest master commit: {}\n", .{@errorName(err)});
std.time.sleep(poll_timeout);
continue;
};
defer gpa.free(commit_str);
const trimmed = std.mem.trim(u8, commit_str, " \n\r\t");
const latest = try parseCommit(trimmed);
if (!isCommitDone(manifest_tree.root, &commit_table, latest)) {
try queue.append(latest);
}
break;
}
const prev_records_len = records.items.len;
for (queue.items) |queue_item| {
runBenchmarks(gpa, arena, &records, &commit_table, manifest_tree.root, queue_item) catch |err| {
std.debug.warn("error running benchmarks: {}\n", .{@errorName(err)});
};
}
if (records.items.len != prev_records_len) {
last_time_slept = false;
// Save CSV
std.debug.warn("Updating {}...\n", .{records_csv_path});
{
const baf = try std.io.BufferedAtomicFile.create(gpa, fs.cwd(), records_csv_path, .{});
defer baf.destroy();
const out = baf.stream();
inline for (@typeInfo(Record).Struct.fields) |field, i| {
if (i != 0) {
try out.writeAll(comma);
}
try out.writeAll(field.name);
}
try out.writeAll("\n");
for (records.items) |record| {
try writeCSVRecord(out, record);
try out.writeAll("\n");
}
try baf.finish();
}
if (auto_commit_and_push) {
std.debug.warn("Committing changes to git and pushing...\n", .{});
// Commit CSV changes to git and push
exec(gpa, &[_][]const u8{ "git", "add", records_csv_path }, .{}) catch |err| {
std.debug.warn("unable to stage {} for git commit: {}\n", .{ records_csv_path, @errorName(err) });
std.time.sleep(poll_timeout);
continue;
};
const commit_message = "add new benchmark records";
exec(gpa, &[_][]const u8{ "git", "commit", "-m", commit_message }, .{}) catch |err| {
std.debug.warn("unable to stage {} for git commit: {}\n", .{ records_csv_path, @errorName(err) });
std.time.sleep(poll_timeout);
continue;
};
exec(gpa, &[_][]const u8{ "git", "push", "origin", "master" }, .{}) catch |err| {
std.debug.warn("unable to git push: {}\n", .{@errorName(err)});
std.time.sleep(poll_timeout);
continue;
};
} else {
std.debug.warn("Skipping git commit and push. Use --auto-commit-and-push to change this.\n", .{});
}
} else {
if (!last_time_slept) {
std.debug.warn("Waiting until new commits are pushed to zig master branch...\n", .{});
}
std.time.sleep(poll_timeout);
last_time_slept = true;
}
}
}
fn isCommitDone(manifest_tree_root: json.Value, commit_table: *CommitTable, commit: [20]u8) bool {
var benchmarks_it = manifest_tree_root.Object.iterator();
while (benchmarks_it.next()) |kv| {
const skip_libc_alloc = if (kv.value.Object.getValue("skipLibCAllocator")) |v| v.Bool else false;
const which_allocators = if (skip_libc_alloc)
&[1]Record.WhichAllocator{.std_gpa}
else
&[_]Record.WhichAllocator{ .libc, .std_gpa };
for (which_allocators) |which_allocator| {
const key: Record.Key = .{
.commit_hash = commit,
.benchmark_name = kv.key,
.allocator = which_allocator,
};
if (commit_table.get(key) == null) {
return false;
}
}
}
return true;
}
fn fieldIndex(comptime T: type, name: []const u8) ?usize {
inline for (@typeInfo(T).Struct.fields) |field, i| {
if (std.mem.eql(u8, field.name, name))
return i;
}
return null;
}
fn setRecordField(arena: *std.mem.Allocator, record: *Record, data: []const u8, index: usize) void {
inline for (@typeInfo(Record).Struct.fields) |field, i| {
if (i == index) {
setRecordFieldT(arena, field.field_type, &@field(record, field.name), data);
return;
}
}
unreachable;
}
fn setRecordFieldT(arena: *std.mem.Allocator, comptime T: type, ptr: *T, data: []const u8) void {
if (@typeInfo(T) == .Enum) {
ptr.* = std.meta.stringToEnum(T, data) orelse {
std.debug.warn("bad enum value: {}\n", .{data});
std.process.exit(1);
};
return;
}
switch (T) {
u64 => {
ptr.* = std.fmt.parseInt(u64, data, 10) catch |err| {
std.debug.warn("bad u64 value '{}': {}\n", .{ data, @errorName(err) });
std.process.exit(1);
};
},
[]const u8 => {
ptr.* = arena.dupe(u8, data) catch @panic("out of memory");
},
[20]u8 => {
ptr.* = parseCommit(data) catch |err| {
std.debug.warn("wrong format for commit hash: '{}': {}", .{ data, @errorName(err) });
std.process.exit(1);
};
},
else => @compileError("no deserialization for " ++ @typeName(T)),
}
}
fn writeCSVRecord(out: var, record: Record) !void {
inline for (@typeInfo(Record).Struct.fields) |field, i| {
if (i != 0) {
try out.writeAll(comma);
}
try writeCSVRecordField(out, @field(record, field.name));
}
}
fn writeCSVRecordField(out: var, field: var) !void {
const T = @TypeOf(field);
if (@typeInfo(T) == .Enum) {
return out.writeAll(@tagName(field));
}
switch (T) {
u64 => return out.print("{}", .{field}),
[]const u8 => return out.writeAll(field),
[20]u8 => return out.print("{x}", .{field}),
else => @compileError("unsupported writeCSVRecordField type: " ++ @typeName(T)),
}
}
fn parseCommit(text: []const u8) ![20]u8 {
var result: [20]u8 = undefined;
if (text.len != 40) {
return error.WrongSHALength;
}
var i: usize = 0;
while (i < 20) : (i += 1) {
const byte = std.fmt.parseInt(u8, text[i * 2 ..][0..2], 16) catch |err| {
return error.BadSHACharacter;
};
result[i] = byte;
}
return result;
}
fn runBenchmarks(
gpa: *std.mem.Allocator,
arena: *std.mem.Allocator,
records: *std.ArrayList(Record),
commit_table: *CommitTable,
manifest: json.Value,
commit: [20]u8,
) !void {
const abs_zig_src_bin = try fs.realpathAlloc(gpa, zig_src_bin);
defer gpa.free(abs_zig_src_bin);
try records.ensureCapacity(records.items.len + manifest.Object.size * 2);
var commit_str: [40]u8 = undefined;
_ = std.fmt.bufPrint(&commit_str, "{x}", .{commit}) catch unreachable;
const timestamp_str = execCapture(gpa, &[_][]const u8{
"git", "log",
"-n1", &commit_str,
"--pretty=format:%at",
}, .{
.cwd = zig_src_root,
}) catch |err| {
std.debug.warn("unable to check timestamp of commit {}: {}\n", .{ &commit_str, @errorName(err) });
return error.UnableToCheckCommitTimestamp;
};
const timestamp = std.fmt.parseInt(u64, std.mem.trim(u8, timestamp_str, " \n\r\t"), 10) catch |err| {
std.debug.warn("bad timestamp format: '{}': {}\n", .{ timestamp_str, @errorName(err) });
return error.BadTimestampFormat;
};
// cd benchmarks/self-hosted-parser
// zig run --main-pkg-path ../.. --pkg-begin app main.zig --pkg-end ../../bench.zig
var benchmarks_it = manifest.Object.iterator();
while (benchmarks_it.next()) |entry| {
const skip_libc_alloc = if (entry.value.Object.getValue("skipLibCAllocator")) |v| v.Bool else false;
const which_allocators = if (skip_libc_alloc)
&[1]Record.WhichAllocator{.std_gpa}
else
&[_]Record.WhichAllocator{ .libc, .std_gpa };
const benchmark_name = entry.key;
const baseline_commit_str = entry.value.Object.getValue("baseline").?.String;
const baseline_commit = try parseCommit(baseline_commit_str);
const dir_name = entry.value.Object.getValue("dir").?.String;
const main_basename = entry.value.Object.getValue("mainPath").?.String;
const baseline_basename = entry.value.Object.getValue("baselinePath").?.String;
const bench_cwd = try fs.path.join(gpa, &[_][]const u8{ "benchmarks", dir_name });
defer gpa.free(bench_cwd);
const full_main_path = try fs.path.join(gpa, &[_][]const u8{ bench_cwd, main_basename });
defer gpa.free(full_main_path);
const abs_main_path = try fs.realpathAlloc(gpa, full_main_path);
defer gpa.free(abs_main_path);
const full_baseline_path = try fs.path.join(gpa, &[_][]const u8{ bench_cwd, baseline_basename });
defer gpa.free(full_baseline_path);
const abs_baseline_path = try fs.realpathAlloc(gpa, full_baseline_path);
defer gpa.free(abs_baseline_path);
const baseline_zig = try fs.path.join(gpa, &[_][]const u8{
"../../zig-builds", baseline_commit_str,
"bin", "zig",
});
defer gpa.free(baseline_zig);
// Check out the appropriate commit and rebuild Zig.
try exec(gpa, &[_][]const u8{ "git", "checkout", &commit_str }, .{
.cwd = zig_src_root,
});
try exec(gpa, &[_][]const u8{"ninja"}, .{
.cwd = zig_src_build,
});
for (which_allocators) |which_allocator| {
std.debug.warn(
"Running '{}' for {x}, allocator={}, baseline...\n",
.{ benchmark_name, commit, @tagName(which_allocator) },
);
var baseline_argv = std.ArrayList([]const u8).init(gpa);
defer baseline_argv.deinit();
try appendBenchArgs(&baseline_argv, baseline_zig, abs_baseline_path, which_allocator);
const baseline_stdout = try execCapture(gpa, baseline_argv.items, .{ .cwd = bench_cwd });
defer gpa.free(baseline_stdout);
var bench_parser = json.Parser.init(gpa, false);
defer bench_parser.deinit();
var baseline_json = bench_parser.parse(baseline_stdout) catch |err| {
std.debug.warn("bad json: {}\n{}\n", .{ @errorName(err), baseline_stdout });
return error.InvalidBenchJSON;
};
defer baseline_json.deinit();
std.debug.warn(
"Running '{}' for {x}, allocator={}...\n",
.{ benchmark_name, commit, @tagName(which_allocator) },
);
var main_argv = std.ArrayList([]const u8).init(gpa);
defer main_argv.deinit();
try appendBenchArgs(&main_argv, abs_zig_src_bin, abs_main_path, which_allocator);
const main_stdout = try execCapture(gpa, main_argv.items, .{ .cwd = bench_cwd });
defer gpa.free(main_stdout);
bench_parser.reset();
var main_json = bench_parser.parse(main_stdout) catch |err| {
std.debug.warn("bad json: {}\n{}\n", .{ @errorName(err), main_stdout });
return error.InvalidBenchJSON;
};
defer main_json.deinit();
const record = try jsonToRecord(
arena,
main_json.root,
baseline_json.root,
timestamp,
benchmark_name,
commit,
which_allocator,
);
const key: Record.Key = .{
.commit_hash = record.commit_hash,
.benchmark_name = record.benchmark_name,
.allocator = record.allocator,
};
const main_gop = try commit_table.getOrPut(key);
if (main_gop.found_existing) {
records.items[main_gop.kv.value] = record;
} else {
main_gop.kv.value = records.items.len;
records.appendAssumeCapacity(record);
}
}
}
}
fn appendBenchArgs(
list: *std.ArrayList([]const u8),
zig_exe: []const u8,
main_path: []const u8,
which_allocator: Record.WhichAllocator,
) !void {
try list.ensureCapacity(20);
list.appendSliceAssumeCapacity(&[_][]const u8{
zig_exe,
"run",
"--cache",
"off",
"--main-pkg-path",
"../..",
"--pkg-begin",
"app",
main_path,
"--pkg-end",
"--release-fast",
});
switch (which_allocator) {
.libc => list.appendAssumeCapacity("-lc"),
.std_gpa => {},
}
list.appendSliceAssumeCapacity(&[_][]const u8{
"../../bench.zig",
"--",
zig_exe,
});
}
fn exec(
gpa: *std.mem.Allocator,
argv: []const []const u8,
options: struct { cwd: ?[]const u8 = null },
) !void {
const child = try std.ChildProcess.init(argv, gpa);
defer child.deinit();
child.stdin_behavior = .Inherit;
child.stdout_behavior = .Inherit;
child.stderr_behavior = .Inherit;
child.cwd = options.cwd;
const term = try child.spawnAndWait();
switch (term) {
.Exited => |code| {
if (code != 0) {
return error.ChildProcessBadExitCode;
}
},
else => {
return error.ChildProcessCrashed;
},
}
}
fn execCapture(
gpa: *std.mem.Allocator,
argv: []const []const u8,
options: struct { cwd: ?[]const u8 = null },
) ![]u8 {
const child = try std.ChildProcess.init(argv, gpa);
defer child.deinit();
child.stdin_behavior = .Inherit;
child.stdout_behavior = .Pipe;
child.stderr_behavior = .Inherit;
child.cwd = options.cwd;
//std.debug.warn("cwd={}\n", .{child.cwd});
//for (argv) |arg| {
// std.debug.warn("{} ", .{arg});
//}
//std.debug.warn("\n", .{});
try child.spawn();
const stdout_in = child.stdout.?.inStream();
const stdout = try stdout_in.readAllAlloc(gpa, 9999);
errdefer gpa.free(stdout);
const term = try child.wait();
switch (term) {
.Exited => |code| {
if (code != 0) {
return error.ChildProcessBadExitCode;
}
},
else => {
return error.ChildProcessCrashed;
},
}
return stdout;
} | main.zig |
const std = @import("std");
const total_eggnog: u32 = 150;
fn solve_table(table: []u32, containers: []u32) !void {
const table_width = total_eggnog + 1;
const table_height = containers.len + 1;
{
// 1 way of making 0 eggnog using containers [0..num_containers]
var num_containers: usize = 0;
while (num_containers < table_height) : (num_containers += 1) {
table[num_containers * table_width] = 1;
}
}
{
// 0 ways of making eggnog_amount>0 eggnog with no containers
var eggnog_amount: usize = 1;
while (eggnog_amount < table_width) : (eggnog_amount += 1) {
table[eggnog_amount] = 0;
}
}
{
var num_containers: usize = 1;
while (num_containers < table_height) : (num_containers += 1) {
const this_container_size = containers[num_containers - 1];
var eggnog_amount: usize = 1;
while (eggnog_amount < table_width) : (eggnog_amount += 1) {
const ways_without_using_this_container =
table[(num_containers - 1) * table_width + eggnog_amount];
const ways_using_this_container =
if (this_container_size <= eggnog_amount)
table[(num_containers - 1) * table_width + (eggnog_amount - this_container_size)]
else
0;
table[num_containers * table_width + eggnog_amount] =
ways_without_using_this_container + ways_using_this_container;
}
}
}
}
fn count_ways_by_num_containers(depth: usize, num_containers: usize, eggnog_amount: usize, table: []u32, containers: []u32, ways: *std.AutoHashMap(usize, u32)) void {
const table_width = total_eggnog + 1;
if (table[num_containers * table_width + eggnog_amount] == 0) {
return;
} else if (eggnog_amount == 0) {
return ways.*.put(depth, ways.*.get(depth).? + 1) catch unreachable;
}
const this_container_size = containers[num_containers - 1];
count_ways_by_num_containers(depth, num_containers - 1, eggnog_amount, table, containers, ways);
if (this_container_size <= eggnog_amount)
count_ways_by_num_containers(depth + 1, num_containers - 1, eggnog_amount - this_container_size, table, containers, ways);
}
pub fn main() !void {
const file = try std.fs.cwd().openFile("inputs/day17.txt", .{ .read = true });
defer file.close();
var reader = std.io.bufferedReader(file.reader()).reader();
var buffer: [1024]u8 = undefined;
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
var containers = std.ArrayList(u32).init(&gpa.allocator);
defer containers.deinit();
while (try reader.readUntilDelimiterOrEof(&buffer, '\n')) |line| {
try containers.append(try std.fmt.parseInt(u32, line, 10));
}
var table = std.ArrayList(u32).init(&gpa.allocator);
defer table.deinit();
try table.resize((total_eggnog + 1) * (containers.items.len + 1));
try solve_table(table.items, containers.items);
std.debug.print("{d}\n", .{table.items[table.items.len - 1]});
var ways = std.AutoHashMap(usize, u32).init(&gpa.allocator);
defer ways.deinit();
{
var i: usize = 0;
while (i < containers.items.len + 1) : (i += 1) {
try ways.put(i, 0);
}
}
count_ways_by_num_containers(0, containers.items.len, total_eggnog, table.items, containers.items, &ways);
{
var i: usize = 0;
while (i < containers.items.len + 1) : (i += 1) {
if (ways.get(i).? > 0) {
std.debug.print("{d}\n", .{ways.get(i).?});
break;
}
}
}
} | src/day17.zig |
const builtin = @import("builtin");
const std = @import("std");
extern fn InitializeConditionVariable(*c_void) void;
extern fn SleepConditionVariableCS(*c_void, *c_void, u32) void;
extern fn WakeConditionVariable(*c_void) void;
extern fn InitializeCriticalSection(*c_void) void;
extern fn EnterCriticalSection(*c_void) void;
extern fn LeaveCriticalSection(*c_void) void;
extern fn DeleteCriticalSection(*c_void) void;
pub const ConditionVariable = switch (builtin.os.tag) {
// builtin.Os.linux => struct {
// TODO
// },
builtin.Os.Tag.windows => struct {
mutex: [40]u8, // 40-byte mutex struct.
condition_variable: u64,
need_to_wake: bool,
pub fn init() ConditionVariable {
var c: ConditionVariable = undefined;
c.need_to_wake = false;
InitializeCriticalSection(&c.mutex);
InitializeConditionVariable(&c.condition_variable);
return c;
}
// Puts current thread to sleep until another thread calls notify()
pub fn wait(self: *ConditionVariable) void {
EnterCriticalSection(&self.mutex);
if (!self.need_to_wake) {
// Releases the lock and sleeps
SleepConditionVariableCS(&self.condition_variable, &self.mutex, 0xffffffff);
}
self.need_to_wake = false;
LeaveCriticalSection(&self.mutex);
}
// Wake up the thread that has called wait()
pub fn notify(self: *ConditionVariable) void {
EnterCriticalSection(&self.mutex);
self.need_to_wake = true;
WakeConditionVariable(&self.condition_variable);
LeaveCriticalSection(&self.mutex);
}
pub fn free(self: *ConditionVariable) void {
DeleteCriticalSection(&self.mutex);
}
},
else => struct {
// Inefficient implementation using an atomic integer and sleeping
need_to_wake: std.atomic.Int(u32),
pub fn init() ConditionVariable {
return ConditionVariable{
.need_to_wake = std.atomic.Int(u32).init(0),
};
}
pub fn wait(self: *ConditionVariable) void {
while (self.need_to_wake.get() == 0) {
std.time.sleep(1000 * 1000 * 5); // 5ms
}
}
pub fn notify(self: *ConditionVariable) void {
self.need_to_wake.set(1);
}
pub fn free(self: *ConditionVariable) void {}
},
}; | src/ConditionVariable.zig |
const std = @import("std");
const leb = std.leb;
const macho = std.macho;
pub const Pointer = struct {
offset: u64,
segment_id: u16,
dylib_ordinal: ?i64 = null,
name: ?[]const u8 = null,
};
pub fn pointerCmp(context: void, a: Pointer, b: Pointer) bool {
if (a.segment_id < b.segment_id) return true;
if (a.segment_id == b.segment_id) {
return a.offset < b.offset;
}
return false;
}
pub fn rebaseInfoSize(pointers: []const Pointer) !u64 {
var stream = std.io.countingWriter(std.io.null_writer);
var writer = stream.writer();
var size: u64 = 0;
for (pointers) |pointer| {
size += 2;
try leb.writeILEB128(writer, pointer.offset);
size += 1;
}
size += 1 + stream.bytes_written;
return size;
}
pub fn writeRebaseInfo(pointers: []const Pointer, writer: anytype) !void {
for (pointers) |pointer| {
try writer.writeByte(macho.REBASE_OPCODE_SET_TYPE_IMM | @truncate(u4, macho.REBASE_TYPE_POINTER));
try writer.writeByte(macho.REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | @truncate(u4, pointer.segment_id));
try leb.writeILEB128(writer, pointer.offset);
try writer.writeByte(macho.REBASE_OPCODE_DO_REBASE_IMM_TIMES | @truncate(u4, 1));
}
try writer.writeByte(macho.REBASE_OPCODE_DONE);
}
pub fn bindInfoSize(pointers: []const Pointer) !u64 {
var stream = std.io.countingWriter(std.io.null_writer);
var writer = stream.writer();
var size: u64 = 0;
for (pointers) |pointer| {
size += 1;
if (pointer.dylib_ordinal.? > 15) {
try leb.writeULEB128(writer, @bitCast(u64, pointer.dylib_ordinal.?));
}
size += 1;
size += 1;
size += pointer.name.?.len;
size += 1;
size += 1;
try leb.writeILEB128(writer, pointer.offset);
size += 1;
}
size += stream.bytes_written + 1;
return size;
}
pub fn writeBindInfo(pointers: []const Pointer, writer: anytype) !void {
for (pointers) |pointer| {
if (pointer.dylib_ordinal.? > 15) {
try writer.writeByte(macho.BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB);
try leb.writeULEB128(writer, @bitCast(u64, pointer.dylib_ordinal.?));
} else if (pointer.dylib_ordinal.? > 0) {
try writer.writeByte(macho.BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | @truncate(u4, @bitCast(u64, pointer.dylib_ordinal.?)));
} else {
try writer.writeByte(macho.BIND_OPCODE_SET_DYLIB_SPECIAL_IMM | @truncate(u4, @bitCast(u64, pointer.dylib_ordinal.?)));
}
try writer.writeByte(macho.BIND_OPCODE_SET_TYPE_IMM | @truncate(u4, macho.BIND_TYPE_POINTER));
try writer.writeByte(macho.BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM); // TODO Sometimes we might want to add flags.
try writer.writeAll(pointer.name.?);
try writer.writeByte(0);
try writer.writeByte(macho.BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | @truncate(u4, pointer.segment_id));
try leb.writeILEB128(writer, pointer.offset);
try writer.writeByte(macho.BIND_OPCODE_DO_BIND);
}
try writer.writeByte(macho.BIND_OPCODE_DONE);
}
pub fn lazyBindInfoSize(pointers: []const Pointer) !u64 {
var stream = std.io.countingWriter(std.io.null_writer);
var writer = stream.writer();
var size: u64 = 0;
for (pointers) |pointer| {
size += 1;
try leb.writeILEB128(writer, pointer.offset);
size += 1;
if (pointer.dylib_ordinal.? > 15) {
try leb.writeULEB128(writer, @bitCast(u64, pointer.dylib_ordinal.?));
}
size += 1;
size += pointer.name.?.len;
size += 1;
size += 2;
}
size += stream.bytes_written;
return size;
}
pub fn writeLazyBindInfo(pointers: []const Pointer, writer: anytype) !void {
for (pointers) |pointer| {
try writer.writeByte(macho.BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | @truncate(u4, pointer.segment_id));
try leb.writeILEB128(writer, pointer.offset);
if (pointer.dylib_ordinal.? > 15) {
try writer.writeByte(macho.BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB);
try leb.writeULEB128(writer, @bitCast(u64, pointer.dylib_ordinal.?));
} else if (pointer.dylib_ordinal.? > 0) {
try writer.writeByte(macho.BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | @truncate(u4, @bitCast(u64, pointer.dylib_ordinal.?)));
} else {
try writer.writeByte(macho.BIND_OPCODE_SET_DYLIB_SPECIAL_IMM | @truncate(u4, @bitCast(u64, pointer.dylib_ordinal.?)));
}
try writer.writeByte(macho.BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM); // TODO Sometimes we might want to add flags.
try writer.writeAll(pointer.name.?);
try writer.writeByte(0);
try writer.writeByte(macho.BIND_OPCODE_DO_BIND);
try writer.writeByte(macho.BIND_OPCODE_DONE);
}
} | src/link/MachO/bind.zig |
const std = @import("std");
const testing = std.testing;
const Hash = u64;
const bits = 1;
const width = 1 << bits;
const mask = width - 1;
const parts = @sizeOf(Hash) * 8 / bits;
fn KeyValue(comptime KT: type, comptime VT: type) type {
return struct {
const Self = @This();
key: KT,
value: VT,
nextValue: ?*Self = null,
prevValue: ?*Self = null,
allocator: *std.mem.Allocator,
fn init(key: KT, value: VT, prevValue: ?*Self, allocator: *std.mem.Allocator) !*Self {
const v = try allocator.create(Self);
v.* = KeyValue(KT, VT){
.key = key,
.value = value,
.prevValue = prevValue,
.allocator = allocator,
};
return v;
}
fn deinit(self: *Self) void {
if (self.nextValue) |unwrappedValue| {
unwrappedValue.deinit();
}
self.allocator.destroy(self);
}
fn clone(self: *Self) error{OutOfMemory}!*Self {
const v = try Self.init(self.key, self.value, null, self.allocator);
if (self.nextValue) |nextValue| {
var next = try nextValue.clone();
v.nextValue = next;
next.prevValue = self;
}
return v;
}
};
}
fn Node(comptime KT: type, comptime VT: type, comptime equalsFn: fn (KT, KT) bool) type {
return struct {
const Self = @This();
value: ?*KeyValue(KT, VT) = null,
left: ?*Self = null,
right: ?*Self = null,
allocator: *std.mem.Allocator,
refCount: i32 = 1,
fn init(allocator: *std.mem.Allocator) !*Self {
const node = try allocator.create(Self);
node.* = Self{
.allocator = allocator,
};
return node;
}
fn deinit(self: *Self) void {
if (self.left) |unwrappedLeft| {
unwrappedLeft.deinit();
}
if (self.right) |unwrappedRight| {
unwrappedRight.deinit();
}
self.refCount -= 1;
if (self.refCount == 0) {
if (self.value) |unwrappedValue| {
unwrappedValue.deinit();
}
self.allocator.destroy(self);
}
}
fn incRefCount(self: *Self) void {
self.refCount += 1;
if (self.left) |left| {
left.incRefCount();
}
if (self.right) |right| {
right.incRefCount();
}
}
fn get(self: *Self, key: KT) ?*KeyValue(KT, VT) {
var maybeValue: ?*KeyValue(KT, VT) = self.value;
while (true) {
var valuePtr = maybeValue orelse break;
if (equalsFn(key, valuePtr.key)) {
return maybeValue;
} else {
maybeValue = valuePtr.nextValue orelse break;
}
}
return null;
}
fn put(self: *Self, key: KT, value: VT) !void {
if (self.value) |existingValue| {
var valuePtr: *KeyValue(KT, VT) = existingValue;
while (true) {
if (equalsFn(key, valuePtr.key)) {
valuePtr.value = value;
return;
} else {
if (valuePtr.nextValue) |nextValue| {
valuePtr = nextValue;
} else {
valuePtr.nextValue = try KeyValue(KT, VT).init(key, value, valuePtr, self.allocator);
return;
}
}
}
} else {
self.value = try KeyValue(KT, VT).init(key, value, null, self.allocator);
}
}
fn remove(self: *Self, key: KT) void {
var valueToRemove = self.get(key) orelse return;
if (self.value) |existingValue| {
var valuePtr: *KeyValue(KT, VT) = existingValue;
while (true) {
if (valuePtr == valueToRemove) {
if (valuePtr.prevValue) |prevValue| {
prevValue.nextValue = valuePtr.nextValue;
} else {
self.value = valuePtr.nextValue;
}
self.allocator.destroy(valuePtr);
return;
} else {
if (valuePtr.nextValue) |nextValue| {
valuePtr = nextValue;
} else {
return;
}
}
}
}
}
};
}
fn Map(comptime KT: type, comptime VT: type, comptime hashFn: fn (KT) Hash, comptime equalsFn: fn (KT, KT) bool) type {
return struct {
const Self = @This();
head: *Node(KT, VT, equalsFn),
allocator: *std.mem.Allocator,
fn init(allocator: *std.mem.Allocator) !Self {
return Self{
.head = try Node(KT, VT, equalsFn).init(allocator),
.allocator = allocator,
};
}
fn deinit(self: *Self) void {
self.head.deinit();
}
fn getNode(self: Self, key: KT, comptime writeWhenNotFound: bool, comptime writeWhenFound: bool) !*Node(KT, VT, equalsFn) {
const keyHash = hashFn(key);
var node = self.head;
var level: u6 = parts - 1;
while (true) {
var bit = (keyHash >> level) & mask;
var maybeNode = if (bit == 0) node.left else node.right;
if (maybeNode) |unwrappedNode| {
if (writeWhenFound and unwrappedNode.refCount > 1) {
var nextNode = try Node(KT, VT, equalsFn).init(self.allocator);
if (unwrappedNode.value) |unwrappedValue| {
nextNode.value = try unwrappedValue.clone();
}
nextNode.left = unwrappedNode.left;
nextNode.right = unwrappedNode.right;
unwrappedNode.refCount -= 1;
if (bit == 0) {
node.left = nextNode;
} else {
node.right = nextNode;
}
node = nextNode;
} else {
node = unwrappedNode;
}
} else {
if (writeWhenNotFound) {
var nextNode = try Node(KT, VT, equalsFn).init(self.allocator);
if (bit == 0) {
node.left = nextNode;
} else {
node.right = nextNode;
}
node = nextNode;
} else {
return error.NodeNotFound;
}
}
if (level == 0) {
break;
} else {
level -= 1;
}
}
return node;
}
fn clone(self: *Self) !Self {
var m = try Self.init(self.allocator);
if (self.head.left) |left| {
left.incRefCount();
m.head.left = left;
}
if (self.head.right) |right| {
right.incRefCount();
m.head.right = right;
}
return m;
}
fn put(self: *Self, key: KT, value: VT) !void {
var node = try self.getNode(key, true, true);
try node.put(key, value);
}
fn add(self: *Self, value: VT) !void {
var node = try self.getNode(value, true, true);
try node.put(value, value);
}
fn get(self: *Self, key: KT) ?VT {
var maybeNode = self.getNode(key, false, false) catch null;
if (maybeNode) |node| {
var v = node.get(key) orelse return null;
return v.value;
} else {
return null;
}
}
fn remove(self: *Self, key: KT) void {
var maybeNode = self.getNode(key, false, false) catch null;
if (maybeNode) |node| {
node.remove(key);
}
}
};
}
fn Set(comptime T: type, comptime hashFn: fn (T) Hash, comptime equalsFn: fn (T, T) bool) type {
return Map(T, T, hashFn, equalsFn);
}
fn stringHasher(input: []const u8) Hash {
// djb2
var hash: Hash = 5381;
for (input) |c| {
hash = 33 * hash + c;
}
return hash;
}
fn stringEquals(first: []const u8, second: []const u8) bool {
return std.mem.eql(u8, first, second);
}
test "basic map functionality" {
const da = std.heap.direct_allocator;
var m = try Map([]const u8, []const u8, stringHasher, stringEquals).init(da);
defer m.deinit();
try m.put("name", "zach");
try m.put("name2", "zach2");
m.remove("name2");
testing.expect(stringEquals(m.get("name") orelse "", "zach"));
testing.expect(m.get("name2") == null);
}
test "basic set functionality" {
const da = std.heap.direct_allocator;
var s = try Set([]const u8, stringHasher, stringEquals).init(da);
defer s.deinit();
try s.add("zach");
try s.add("zach2");
s.remove("zach2");
testing.expect(stringEquals(s.get("zach") orelse "", "zach"));
testing.expect(s.get("zach2") == null);
}
test "immutable ops" {
const da = std.heap.direct_allocator;
var m1 = try Map([]const u8, []const u8, stringHasher, stringEquals).init(da);
defer m1.deinit();
try m1.put("name", "zach");
try m1.put("name2", "zach3");
var m2 = try m1.clone();
try m2.put("name", "zach4");
try m2.put("name", "zach2");
defer m2.deinit();
testing.expect(stringEquals(m1.get("name") orelse "", "zach"));
testing.expect(stringEquals(m2.get("name") orelse "", "zach2"));
testing.expect(stringEquals(m2.get("name2") orelse "", "zach3"));
var s1 = try Set([]const u8, stringHasher, stringEquals).init(da);
defer s1.deinit();
try s1.add("zach");
var s2 = try s1.clone();
try s2.add("zach2");
defer s2.deinit();
testing.expect(stringEquals(s1.get("zach") orelse "", "zach"));
testing.expect(s1.get("zach2") == null);
testing.expect(stringEquals(s2.get("zach") orelse "", "zach"));
testing.expect(stringEquals(s2.get("zach2") orelse "", "zach2"));
} | src/main.zig |
const std = @import("std");
const Ring = @This();
allocator: *std.mem.Allocator,
buffer: []f32,
write_idx: usize = 0,
read_idx: usize = 0,
pub fn init(allocator: *std.mem.Allocator, size: usize) !Ring {
var ring = Ring{
.allocator = allocator,
.buffer = try allocator.alloc(f32, size),
};
std.mem.set(f32, ring.buffer, 0);
return ring;
}
pub fn deinit(self: *Ring) void {
self.allocator.free(self.buffer);
self.* = undefined;
}
pub fn write(self: *Ring, data: []const f32) void {
for (data) |value| {
const idx = self.write_idx % self.buffer.len;
self.buffer[idx] = value;
self.write_idx += 1;
if (self.write_idx - self.read_idx > self.buffer.len) {
self.read_idx = self.write_idx - self.buffer.len;
}
}
}
pub fn read(self: *Ring) ?f32 {
if (self.write_idx - self.read_idx == 0)
return null;
const idx = self.read_idx % self.buffer.len;
return idx;
}
pub fn iterateMax(self: *Ring, max_size: usize) ReadMaxIterator {
return ReadMaxIterator{
.ring = self,
.max_size = max_size,
};
}
pub const ReadMaxIterator = struct {
count: usize = 0,
max_size: usize,
ring: *Ring,
pub fn next(self: *ReadMaxIterator) ?f32 {
if (self.count >= self.max_size)
return null;
self.count += 1;
return ring.read();
}
};
pub fn available(self: Ring) usize {
return self.write_idx - self.read_idx;
}
pub fn readSlice(self: *Ring) SliceResult {
var result: SliceResult = undefined;
const count = self.available();
const read_idx = self.read_idx % self.buffer.len;
const write_idx = self.write_idx % self.buffer.len;
if (read_idx > write_idx) {
// We need two parts
result.first = self.buffer[read_idx..];
result.second = self.buffer[0..write_idx];
result.count = result.first.len + result.second.?.len;
} else {
result.first = self.buffer[read_idx..write_idx];
result.second = null;
result.count = result.first.len;
}
self.read_idx += count;
return result;
}
pub const SliceResult = struct {
first: []const f32,
second: ?[]const f32,
count: usize,
}; | src/util/ring.zig |
const c = @cImport({
@cInclude("cfl_input.h");
});
const widget = @import("widget.zig");
const enums = @import("enums.zig");
pub const Input = struct {
inner: ?*c.Fl_Input,
pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) Input {
const ptr = c.Fl_Input_new(x, y, w, h, title);
if (ptr == null) unreachable;
return Input{
.inner = ptr,
};
}
pub fn raw(self: *Input) ?*c.Fl_Input {
return self.inner;
}
pub fn fromRaw(ptr: ?*c.Fl_Input) Input {
return Input{
.inner = ptr,
};
}
pub fn fromWidgetPtr(w: widget.WidgetPtr) Input {
return Input{
.inner = @ptrCast(?*c.Fl_Input, w),
};
}
pub fn fromVoidPtr(ptr: ?*c_void) Input {
return Input{
.inner = @ptrCast(?*c.Fl_Input, ptr),
};
}
pub fn toVoidPtr(self: *Input) ?*c_void {
return @ptrCast(?*c_void, self.inner);
}
pub fn asWidget(self: *const Input) widget.Widget {
return widget.Widget{
.inner = @ptrCast(widget.WidgetPtr, self.inner),
};
}
pub fn handle(self: *Input, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void {
c.Fl_Input_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data);
}
pub fn draw(self: *Input, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void {
c.Fl_Input_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data);
}
pub fn value(self: *const Input) [*c]const u8 {
return c.Fl_Input_value(self.inner);
}
pub fn setValue(self: *Input, val: [*c]const u8) void {
c.Fl_Input_set_value(self.inner, val);
}
pub fn setTextFont(self: *Input, font: enums.Font) void {
c.Fl_Input_set_text_font(self.inner, @enumToInt(font));
}
pub fn setTextColor(self: *Input, col: u32) void {
c.Fl_Input_set_text_color(self.inner, col);
}
pub fn setTextSize(self: *Input, sz: u32) void {
c.Fl_Input_set_text_size(self.inner, sz);
}
};
pub const MultilineInput = struct {
inner: ?*c.Fl_Multiline_Input,
pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) MultilineInput {
const ptr = c.Fl_Multiline_Input_new(x, y, w, h, title);
if (ptr == null) unreachable;
return MultilineInput{
.inner = ptr,
};
}
pub fn raw(self: *MultilineInput) ?*c.Fl_Multiline_Input {
return self.inner;
}
pub fn fromRaw(ptr: ?*c.Fl_Multiline_Input) MultilineInput {
return MultilineInput{
.inner = ptr,
};
}
pub fn fromWidgetPtr(w: widget.WidgetPtr) MultilineInput {
return MultilineInput{
.inner = @ptrCast(?*c.Fl_Multiline_Input, w),
};
}
pub fn fromVoidPtr(ptr: ?*c_void) MultilineInput {
return MultilineInput{
.inner = @ptrCast(?*c.Fl_Multiline_Input, ptr),
};
}
pub fn toVoidPtr(self: *MultilineInput) ?*c_void {
return @ptrCast(?*c_void, self.inner);
}
pub fn asWidget(self: *const MultilineInput) widget.Widget {
return widget.Widget{
.inner = @ptrCast(widget.WidgetPtr, self.inner),
};
}
pub fn asInput(self: *const MultilineInput) Input {
return Input{
.inner = @ptrCast(?*c.Fl_Input, self.inner),
};
}
pub fn handle(self: *MultilineInput, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void {
c.Fl_Multiline_Input_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data);
}
pub fn draw(self: *MultilineInput, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void {
c.Fl_Multiline_Input_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data);
}
};
pub const IntInput = struct {
inner: ?*c.Fl_Int_Input,
pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) IntInput {
const ptr = c.Fl_Int_Input_new(x, y, w, h, title);
if (ptr == null) unreachable;
return IntInput{
.inner = ptr,
};
}
pub fn raw(self: *IntInput) ?*c.Fl_Int_Input {
return self.inner;
}
pub fn fromRaw(ptr: ?*c.Fl_Int_Input) IntInput {
return IntInput{
.inner = ptr,
};
}
pub fn fromWidgetPtr(w: widget.WidgetPtr) IntInput {
return IntInput{
.inner = @ptrCast(?*c.Fl_Int_Input, w),
};
}
pub fn fromVoidPtr(ptr: ?*c_void) IntInput {
return IntInput{
.inner = @ptrCast(?*c.Fl_Int_Input, ptr),
};
}
pub fn toVoidPtr(self: *IntInput) ?*c_void {
return @ptrCast(?*c_void, self.inner);
}
pub fn asWidget(self: *const IntInput) widget.Widget {
return widget.Widget{
.inner = @ptrCast(widget.WidgetPtr, self.inner),
};
}
pub fn asInput(self: *const IntInput) Input {
return Input{
.inner = @ptrCast(?*c.Fl_Input, self.inner),
};
}
pub fn handle(self: *IntInput, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void {
c.Fl_Int_Input_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data);
}
pub fn draw(self: *IntInput, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void {
c.Fl_Int_Input_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data);
}
};
pub const FloatInput = struct {
inner: ?*c.Fl_Float_Input,
pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) FloatInput {
const ptr = c.Fl_Float_Input_new(x, y, w, h, title);
if (ptr == null) unreachable;
return FloatInput{
.inner = ptr,
};
}
pub fn raw(self: *FloatInput) ?*c.Fl_Float_Input {
return self.inner;
}
pub fn fromRaw(ptr: ?*c.Fl_Float_Input) FloatInput {
return FloatInput{
.inner = ptr,
};
}
pub fn fromWidgetPtr(w: widget.WidgetPtr) FloatInput {
return FloatInput{
.inner = @ptrCast(?*c.Fl_Float_Input, w),
};
}
pub fn fromVoidPtr(ptr: ?*c_void) FloatInput {
return FloatInput{
.inner = @ptrCast(?*c.Fl_Float_Input, ptr),
};
}
pub fn toVoidPtr(self: *FloatInput) ?*c_void {
return @ptrCast(?*c_void, self.inner);
}
pub fn asWidget(self: *const FloatInput) widget.Widget {
return widget.Widget{
.inner = @ptrCast(widget.WidgetPtr, self.inner),
};
}
pub fn asInput(self: *const FloatInput) Input {
return Input{
.inner = @ptrCast(?*c.Fl_Input, self.inner),
};
}
pub fn handle(self: *FloatInput, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void {
c.Fl_Float_Input_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data);
}
pub fn draw(self: *FloatInput, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void {
c.Fl_Float_Input_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data);
}
};
pub const SecretInput = struct {
inner: ?*c.Fl_Secret_Input,
pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) SecretInput {
const ptr = c.Fl_Secret_Input_new(x, y, w, h, title);
if (ptr == null) unreachable;
return SecretInput{
.inner = ptr,
};
}
pub fn raw(self: *SecretInput) ?*c.Fl_Secret_Input {
return self.inner;
}
pub fn fromRaw(ptr: ?*c.Fl_Secret_Input) SecretInput {
return SecretInput{
.inner = ptr,
};
}
pub fn fromWidgetPtr(w: widget.WidgetPtr) SecretInput {
return SecretInput{
.inner = @ptrCast(?*c.Fl_Secret_Input, w),
};
}
pub fn fromVoidPtr(ptr: ?*c_void) SecretInput {
return SecretInput{
.inner = @ptrCast(?*c.Fl_Secret_Input, ptr),
};
}
pub fn toVoidPtr(self: *SecretInput) ?*c_void {
return @ptrCast(?*c_void, self.inner);
}
pub fn asWidget(self: *const SecretInput) widget.Widget {
return widget.Widget{
.inner = @ptrCast(widget.WidgetPtr, self.inner),
};
}
pub fn asInput(self: *const SecretInput) Input {
return Input{
.inner = @ptrCast(?*c.Fl_Input, self.inner),
};
}
pub fn handle(self: *SecretInput, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void {
c.Fl_Secret_Input_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data);
}
pub fn draw(self: *SecretInput, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void {
c.Fl_Secret_Input_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data);
}
};
test "" {
@import("std").testing.refAllDecls(@This());
} | src/input.zig |
const Builder = @import("std").build.Builder;
pub fn build(b: *Builder) void {
const mode = b.standardReleaseOptions();
// libgc
const gc = b.addStaticLibrary("gc", null);
{
// TODO(mitchellh): support more complex features that are usually on
// with libgc like threading, parallelization, etc.
const cflags = [_][]const u8{};
const libgc_srcs = [_][]const u8{
"alloc.c", "reclaim.c", "allchblk.c", "misc.c", "mach_dep.c", "os_dep.c",
"mark_rts.c", "headers.c", "mark.c", "obj_map.c", "blacklst.c", "finalize.c",
"new_hblk.c", "dbg_mlc.c", "malloc.c", "dyn_load.c", "typd_mlc.c", "ptr_chck.c",
"mallocx.c",
};
gc.setBuildMode(mode);
gc.linkLibC();
gc.addIncludeDir("vendor/bdwgc/include");
inline for (libgc_srcs) |src| {
gc.addCSourceFile("vendor/bdwgc/" ++ src, &cflags);
}
const gc_step = b.step("libgc", "build libgc");
gc_step.dependOn(&gc.step);
}
// lib for zig
const lib = b.addStaticLibrary("gc", "src/gc.zig");
{
lib.setBuildMode(mode);
var main_tests = b.addTest("src/gc.zig");
main_tests.setBuildMode(mode);
main_tests.linkLibC();
main_tests.addIncludeDir("vendor/bdwgc/include");
main_tests.linkLibrary(gc);
const test_step = b.step("test", "Run library tests");
test_step.dependOn(&main_tests.step);
b.default_step.dependOn(&lib.step);
b.installArtifact(lib);
}
// example app
const exe = b.addExecutable("example", "example/basic.zig");
{
exe.linkLibC();
exe.addIncludeDir("vendor/bdwgc/include");
exe.linkLibrary(gc);
exe.addPackage(.{
.name = "gc",
.path = .{ .path = "src/gc.zig" },
});
exe.install();
const install_cmd = b.addInstallArtifact(exe);
const run_cmd = exe.run();
run_cmd.step.dependOn(&install_cmd.step);
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run_example", "run example");
run_step.dependOn(&run_cmd.step);
}
} | build.zig |
const std = @import("std");
const mem = std.mem;
const EmojiPresentation = @This();
allocator: *mem.Allocator,
array: []bool,
lo: u21 = 8986,
hi: u21 = 129750,
pub fn init(allocator: *mem.Allocator) !EmojiPresentation {
var instance = EmojiPresentation{
.allocator = allocator,
.array = try allocator.alloc(bool, 120765),
};
mem.set(bool, instance.array, false);
var index: u21 = 0;
index = 0;
while (index <= 1) : (index += 1) {
instance.array[index] = true;
}
index = 207;
while (index <= 210) : (index += 1) {
instance.array[index] = true;
}
instance.array[214] = true;
instance.array[217] = true;
index = 739;
while (index <= 740) : (index += 1) {
instance.array[index] = true;
}
index = 762;
while (index <= 763) : (index += 1) {
instance.array[index] = true;
}
index = 814;
while (index <= 825) : (index += 1) {
instance.array[index] = true;
}
instance.array[869] = true;
instance.array[889] = true;
instance.array[903] = true;
index = 912;
while (index <= 913) : (index += 1) {
instance.array[index] = true;
}
index = 931;
while (index <= 932) : (index += 1) {
instance.array[index] = true;
}
index = 938;
while (index <= 939) : (index += 1) {
instance.array[index] = true;
}
instance.array[948] = true;
instance.array[954] = true;
instance.array[976] = true;
index = 984;
while (index <= 985) : (index += 1) {
instance.array[index] = true;
}
instance.array[987] = true;
instance.array[992] = true;
instance.array[995] = true;
instance.array[1003] = true;
index = 1008;
while (index <= 1009) : (index += 1) {
instance.array[index] = true;
}
instance.array[1038] = true;
instance.array[1074] = true;
instance.array[1076] = true;
index = 1081;
while (index <= 1083) : (index += 1) {
instance.array[index] = true;
}
instance.array[1085] = true;
index = 1147;
while (index <= 1149) : (index += 1) {
instance.array[index] = true;
}
instance.array[1174] = true;
instance.array[1189] = true;
index = 2049;
while (index <= 2050) : (index += 1) {
instance.array[index] = true;
}
instance.array[2102] = true;
instance.array[2107] = true;
instance.array[117994] = true;
instance.array[118197] = true;
instance.array[118388] = true;
index = 118391;
while (index <= 118400) : (index += 1) {
instance.array[index] = true;
}
index = 118476;
while (index <= 118501) : (index += 1) {
instance.array[index] = true;
}
instance.array[118503] = true;
instance.array[118528] = true;
instance.array[118549] = true;
index = 118552;
while (index <= 118556) : (index += 1) {
instance.array[index] = true;
}
index = 118558;
while (index <= 118560) : (index += 1) {
instance.array[index] = true;
}
index = 118582;
while (index <= 118583) : (index += 1) {
instance.array[index] = true;
}
index = 118758;
while (index <= 118770) : (index += 1) {
instance.array[index] = true;
}
index = 118771;
while (index <= 118772) : (index += 1) {
instance.array[index] = true;
}
instance.array[118773] = true;
instance.array[118774] = true;
instance.array[118775] = true;
instance.array[118776] = true;
index = 118777;
while (index <= 118779) : (index += 1) {
instance.array[index] = true;
}
index = 118780;
while (index <= 118782) : (index += 1) {
instance.array[index] = true;
}
instance.array[118783] = true;
instance.array[118784] = true;
instance.array[118785] = true;
instance.array[118786] = true;
index = 118787;
while (index <= 118788) : (index += 1) {
instance.array[index] = true;
}
index = 118789;
while (index <= 118790) : (index += 1) {
instance.array[index] = true;
}
index = 118803;
while (index <= 118805) : (index += 1) {
instance.array[index] = true;
}
index = 118806;
while (index <= 118807) : (index += 1) {
instance.array[index] = true;
}
index = 118808;
while (index <= 118809) : (index += 1) {
instance.array[index] = true;
}
index = 118810;
while (index <= 118811) : (index += 1) {
instance.array[index] = true;
}
index = 118813;
while (index <= 118832) : (index += 1) {
instance.array[index] = true;
}
instance.array[118833] = true;
index = 118834;
while (index <= 118837) : (index += 1) {
instance.array[index] = true;
}
instance.array[118838] = true;
index = 118839;
while (index <= 118881) : (index += 1) {
instance.array[index] = true;
}
instance.array[118882] = true;
index = 118884;
while (index <= 118885) : (index += 1) {
instance.array[index] = true;
}
index = 118886;
while (index <= 118905) : (index += 1) {
instance.array[index] = true;
}
index = 118918;
while (index <= 118954) : (index += 1) {
instance.array[index] = true;
}
instance.array[118955] = true;
instance.array[118956] = true;
instance.array[118957] = true;
instance.array[118958] = true;
instance.array[118959] = true;
instance.array[118960] = true;
index = 118965;
while (index <= 118969) : (index += 1) {
instance.array[index] = true;
}
index = 118982;
while (index <= 118985) : (index += 1) {
instance.array[index] = true;
}
instance.array[118986] = true;
index = 118987;
while (index <= 118998) : (index += 1) {
instance.array[index] = true;
}
instance.array[119002] = true;
index = 119006;
while (index <= 119021) : (index += 1) {
instance.array[index] = true;
}
instance.array[119022] = true;
index = 119023;
while (index <= 119025) : (index += 1) {
instance.array[index] = true;
}
index = 119026;
while (index <= 119028) : (index += 1) {
instance.array[index] = true;
}
index = 119029;
while (index <= 119030) : (index += 1) {
instance.array[index] = true;
}
index = 119031;
while (index <= 119032) : (index += 1) {
instance.array[index] = true;
}
instance.array[119033] = true;
instance.array[119034] = true;
instance.array[119035] = true;
instance.array[119036] = true;
index = 119037;
while (index <= 119055) : (index += 1) {
instance.array[index] = true;
}
instance.array[119056] = true;
index = 119057;
while (index <= 119076) : (index += 1) {
instance.array[index] = true;
}
instance.array[119078] = true;
index = 119080;
while (index <= 119114) : (index += 1) {
instance.array[index] = true;
}
instance.array[119115] = true;
index = 119116;
while (index <= 119121) : (index += 1) {
instance.array[index] = true;
}
index = 119122;
while (index <= 119123) : (index += 1) {
instance.array[index] = true;
}
index = 119124;
while (index <= 119186) : (index += 1) {
instance.array[index] = true;
}
instance.array[119187] = true;
index = 119188;
while (index <= 119195) : (index += 1) {
instance.array[index] = true;
}
index = 119196;
while (index <= 119197) : (index += 1) {
instance.array[index] = true;
}
index = 119198;
while (index <= 119249) : (index += 1) {
instance.array[index] = true;
}
index = 119250;
while (index <= 119251) : (index += 1) {
instance.array[index] = true;
}
instance.array[119252] = true;
instance.array[119253] = true;
index = 119254;
while (index <= 119258) : (index += 1) {
instance.array[index] = true;
}
instance.array[119259] = true;
index = 119260;
while (index <= 119261) : (index += 1) {
instance.array[index] = true;
}
instance.array[119262] = true;
index = 119263;
while (index <= 119266) : (index += 1) {
instance.array[index] = true;
}
index = 119269;
while (index <= 119272) : (index += 1) {
instance.array[index] = true;
}
instance.array[119273] = true;
index = 119274;
while (index <= 119277) : (index += 1) {
instance.array[index] = true;
}
instance.array[119278] = true;
instance.array[119279] = true;
index = 119280;
while (index <= 119290) : (index += 1) {
instance.array[index] = true;
}
instance.array[119291] = true;
index = 119292;
while (index <= 119313) : (index += 1) {
instance.array[index] = true;
}
index = 119314;
while (index <= 119315) : (index += 1) {
instance.array[index] = true;
}
index = 119316;
while (index <= 119331) : (index += 1) {
instance.array[index] = true;
}
index = 119345;
while (index <= 119348) : (index += 1) {
instance.array[index] = true;
}
index = 119350;
while (index <= 119361) : (index += 1) {
instance.array[index] = true;
}
index = 119362;
while (index <= 119373) : (index += 1) {
instance.array[index] = true;
}
instance.array[119392] = true;
index = 119419;
while (index <= 119420) : (index += 1) {
instance.array[index] = true;
}
instance.array[119434] = true;
index = 119521;
while (index <= 119525) : (index += 1) {
instance.array[index] = true;
}
instance.array[119526] = true;
index = 119527;
while (index <= 119532) : (index += 1) {
instance.array[index] = true;
}
index = 119533;
while (index <= 119534) : (index += 1) {
instance.array[index] = true;
}
index = 119535;
while (index <= 119539) : (index += 1) {
instance.array[index] = true;
}
instance.array[119540] = true;
instance.array[119541] = true;
instance.array[119542] = true;
instance.array[119543] = true;
index = 119544;
while (index <= 119546) : (index += 1) {
instance.array[index] = true;
}
instance.array[119547] = true;
instance.array[119548] = true;
instance.array[119549] = true;
instance.array[119550] = true;
instance.array[119551] = true;
instance.array[119552] = true;
instance.array[119553] = true;
index = 119554;
while (index <= 119556) : (index += 1) {
instance.array[index] = true;
}
instance.array[119557] = true;
index = 119558;
while (index <= 119563) : (index += 1) {
instance.array[index] = true;
}
index = 119564;
while (index <= 119565) : (index += 1) {
instance.array[index] = true;
}
index = 119566;
while (index <= 119569) : (index += 1) {
instance.array[index] = true;
}
instance.array[119570] = true;
instance.array[119571] = true;
index = 119572;
while (index <= 119573) : (index += 1) {
instance.array[index] = true;
}
index = 119574;
while (index <= 119577) : (index += 1) {
instance.array[index] = true;
}
instance.array[119578] = true;
instance.array[119579] = true;
instance.array[119580] = true;
index = 119581;
while (index <= 119590) : (index += 1) {
instance.array[index] = true;
}
index = 119591;
while (index <= 119594) : (index += 1) {
instance.array[index] = true;
}
index = 119595;
while (index <= 119605) : (index += 1) {
instance.array[index] = true;
}
instance.array[119654] = true;
index = 119655;
while (index <= 119656) : (index += 1) {
instance.array[index] = true;
}
index = 119657;
while (index <= 119659) : (index += 1) {
instance.array[index] = true;
}
instance.array[119660] = true;
instance.array[119661] = true;
instance.array[119662] = true;
instance.array[119663] = true;
index = 119664;
while (index <= 119665) : (index += 1) {
instance.array[index] = true;
}
instance.array[119666] = true;
instance.array[119667] = true;
instance.array[119668] = true;
instance.array[119669] = true;
instance.array[119670] = true;
index = 119671;
while (index <= 119673) : (index += 1) {
instance.array[index] = true;
}
instance.array[119674] = true;
instance.array[119675] = true;
instance.array[119676] = true;
instance.array[119677] = true;
instance.array[119678] = true;
index = 119679;
while (index <= 119680) : (index += 1) {
instance.array[index] = true;
}
index = 119681;
while (index <= 119687) : (index += 1) {
instance.array[index] = true;
}
instance.array[119688] = true;
instance.array[119689] = true;
index = 119690;
while (index <= 119691) : (index += 1) {
instance.array[index] = true;
}
instance.array[119692] = true;
index = 119693;
while (index <= 119699) : (index += 1) {
instance.array[index] = true;
}
index = 119700;
while (index <= 119703) : (index += 1) {
instance.array[index] = true;
}
instance.array[119704] = true;
index = 119705;
while (index <= 119707) : (index += 1) {
instance.array[index] = true;
}
instance.array[119708] = true;
index = 119709;
while (index <= 119710) : (index += 1) {
instance.array[index] = true;
}
index = 119711;
while (index <= 119716) : (index += 1) {
instance.array[index] = true;
}
instance.array[119717] = true;
instance.array[119718] = true;
index = 119719;
while (index <= 119723) : (index += 1) {
instance.array[index] = true;
}
instance.array[119730] = true;
instance.array[119734] = true;
index = 119735;
while (index <= 119736) : (index += 1) {
instance.array[index] = true;
}
instance.array[119739] = true;
index = 119740;
while (index <= 119741) : (index += 1) {
instance.array[index] = true;
}
index = 119761;
while (index <= 119762) : (index += 1) {
instance.array[index] = true;
}
index = 119770;
while (index <= 119772) : (index += 1) {
instance.array[index] = true;
}
index = 119773;
while (index <= 119774) : (index += 1) {
instance.array[index] = true;
}
instance.array[119775] = true;
instance.array[119776] = true;
index = 119777;
while (index <= 119778) : (index += 1) {
instance.array[index] = true;
}
index = 120006;
while (index <= 120017) : (index += 1) {
instance.array[index] = true;
}
instance.array[120306] = true;
index = 120307;
while (index <= 120309) : (index += 1) {
instance.array[index] = true;
}
index = 120310;
while (index <= 120318) : (index += 1) {
instance.array[index] = true;
}
index = 120319;
while (index <= 120324) : (index += 1) {
instance.array[index] = true;
}
instance.array[120325] = true;
index = 120326;
while (index <= 120333) : (index += 1) {
instance.array[index] = true;
}
index = 120334;
while (index <= 120341) : (index += 1) {
instance.array[index] = true;
}
instance.array[120342] = true;
index = 120343;
while (index <= 120344) : (index += 1) {
instance.array[index] = true;
}
index = 120345;
while (index <= 120352) : (index += 1) {
instance.array[index] = true;
}
index = 120354;
while (index <= 120356) : (index += 1) {
instance.array[index] = true;
}
instance.array[120357] = true;
index = 120358;
while (index <= 120363) : (index += 1) {
instance.array[index] = true;
}
index = 120365;
while (index <= 120369) : (index += 1) {
instance.array[index] = true;
}
instance.array[120370] = true;
index = 120371;
while (index <= 120373) : (index += 1) {
instance.array[index] = true;
}
index = 120374;
while (index <= 120388) : (index += 1) {
instance.array[index] = true;
}
index = 120389;
while (index <= 120401) : (index += 1) {
instance.array[index] = true;
}
index = 120402;
while (index <= 120406) : (index += 1) {
instance.array[index] = true;
}
instance.array[120407] = true;
instance.array[120408] = true;
index = 120409;
while (index <= 120412) : (index += 1) {
instance.array[index] = true;
}
index = 120413;
while (index <= 120414) : (index += 1) {
instance.array[index] = true;
}
instance.array[120416] = true;
instance.array[120417] = true;
index = 120418;
while (index <= 120421) : (index += 1) {
instance.array[index] = true;
}
index = 120422;
while (index <= 120426) : (index += 1) {
instance.array[index] = true;
}
index = 120427;
while (index <= 120439) : (index += 1) {
instance.array[index] = true;
}
index = 120440;
while (index <= 120445) : (index += 1) {
instance.array[index] = true;
}
index = 120446;
while (index <= 120456) : (index += 1) {
instance.array[index] = true;
}
index = 120457;
while (index <= 120458) : (index += 1) {
instance.array[index] = true;
}
index = 120459;
while (index <= 120464) : (index += 1) {
instance.array[index] = true;
}
index = 120465;
while (index <= 120467) : (index += 1) {
instance.array[index] = true;
}
index = 120468;
while (index <= 120469) : (index += 1) {
instance.array[index] = true;
}
index = 120470;
while (index <= 120479) : (index += 1) {
instance.array[index] = true;
}
index = 120480;
while (index <= 120485) : (index += 1) {
instance.array[index] = true;
}
instance.array[120486] = true;
index = 120487;
while (index <= 120488) : (index += 1) {
instance.array[index] = true;
}
index = 120489;
while (index <= 120496) : (index += 1) {
instance.array[index] = true;
}
instance.array[120497] = true;
index = 120499;
while (index <= 120501) : (index += 1) {
instance.array[index] = true;
}
index = 120502;
while (index <= 120524) : (index += 1) {
instance.array[index] = true;
}
index = 120525;
while (index <= 120549) : (index += 1) {
instance.array[index] = true;
}
index = 120662;
while (index <= 120665) : (index += 1) {
instance.array[index] = true;
}
instance.array[120666] = true;
index = 120670;
while (index <= 120672) : (index += 1) {
instance.array[index] = true;
}
index = 120678;
while (index <= 120680) : (index += 1) {
instance.array[index] = true;
}
index = 120681;
while (index <= 120684) : (index += 1) {
instance.array[index] = true;
}
index = 120694;
while (index <= 120699) : (index += 1) {
instance.array[index] = true;
}
index = 120700;
while (index <= 120718) : (index += 1) {
instance.array[index] = true;
}
index = 120726;
while (index <= 120732) : (index += 1) {
instance.array[index] = true;
}
index = 120742;
while (index <= 120744) : (index += 1) {
instance.array[index] = true;
}
index = 120758;
while (index <= 120764) : (index += 1) {
instance.array[index] = true;
}
// Placeholder: 0. Struct name, 1. Code point kind
return instance;
}
pub fn deinit(self: *EmojiPresentation) void {
self.allocator.free(self.array);
}
// isEmojiPresentation checks if cp is of the kind Emoji_Presentation.
pub fn isEmojiPresentation(self: EmojiPresentation, cp: u21) bool {
if (cp < self.lo or cp > self.hi) return false;
const index = cp - self.lo;
return if (index >= self.array.len) false else self.array[index];
} | src/components/autogen/emoji-data/EmojiPresentation.zig |
const std = @import("std");
const Vector = std.meta.Vector;
pub const Float4 = Vector(4, f32);
pub const Float3 = [3]f32; // Vector(3, f32) is 16 byte aligned
pub const VFloat3 = Vector(3, f32);
pub const Float2 = Vector(2, f32);
pub const Float4x4 = extern struct {
rows: [4]Float4 = .{
Float4{ 1, 0, 0, 0 },
Float4{ 0, 1, 0, 0 },
Float4{ 0, 0, 1, 0 },
Float4{ 0, 0, 0, 1 },
},
};
pub const Float3x4 = extern struct {
rows: [3]Float4 = .{
Float4{ 1, 0, 0, 0 },
Float4{ 0, 1, 0, 0 },
Float4{ 0, 0, 1, 0 },
},
};
pub const Float3x3 = extern struct {
rows: [3]Float3 = .{
Float3{ 1, 0, 0 },
Float3{ 0, 1, 0 },
Float3{ 0, 0, 1 },
},
};
pub const Transform = extern struct {
const Self = @This();
position: Float3 = Float3{ 0, 0, 0 },
scale: Float3 = Float3{ 1, 1, 1 },
rotation: Float3 = Float3{ 0, 0, 0 },
pub fn translate(self: *Self, p: VFloat3) void {
self.position = @as(VFloat3, self.position) + p;
}
pub fn scaleBy(self: *Self, p: VFloat3) void {
// Note: The original code does += here but that might be a bug.
// This should maybe be *= instead.
self.scale = @as(VFloat3, self.scale) + p;
}
pub fn rotate(self: *Self, p: VFloat3) void {
self.rotation = @as(VFloat3, self.rotation) + p;
}
pub fn toMatrix(self: Self) Float4x4 {
const p: Float4x4 = .{ .rows = .{
.{1, 0, 0, self.position[0]},
.{0, 1, 0, self.position[1]},
.{0, 0, 1, self.position[2]},
.{0, 0, 0, 1},
}};
const r = blk: {
// whee vectors!
const cos = @cos(@as(VFloat3, self.rotation));
const sin = @sin(@as(VFloat3, self.rotation));
var rx: Float4x4 = .{};
rx.rows[1] = .{0, cos[0], -sin[0], 0};
rx.rows[2] = .{0, sin[0], cos[0], 0};
var ry: Float4x4 = .{};
ry.rows[0] = .{cos[1], 0, sin[1], 0};
ry.rows[2] = .{-sin[1], 0, cos[1], 0};
var rz: Float4x4 = .{};
rz.rows[0] = .{cos[2], -sin[2], 0, 0};
rz.rows[1] = .{sin[2], cos[2], 0, 0};
const tmp = mulmf44(rx, ry);
break :blk mulmf44(tmp, rz);
};
var s: Float4x4 = .{ .rows = .{
.{self.scale[0], 0, 0, 0},
.{0, self.scale[1], 0, 0},
.{0, 0, self.scale[2], 0},
.{0, 0, 0, 1},
}};
return mulmf44(s, mulmf44(p, r));
}
};
pub fn f4tof3(f: Float4) VFloat3 {
return .{ f[0], f[1], f[2] };
}
pub fn f3tof4(f: VFloat3, w: f32) Float4 {
return .{ f[0], f[1], f[2], w };
}
pub fn dotf3(a: VFloat3, b: VFloat3) f32 {
return @reduce(.Add, a * b);
}
pub fn dotf4(a: Float4, b: Float4) f32 {
return @reduce(.Add, a * b);
}
pub fn crossf3(a: VFloat3, b: VFloat3) VFloat3 {
const x1 = @shuffle(f32, a, undefined, [_]i32{1, 2, 0});
const x2 = @shuffle(f32, a, undefined, [_]i32{2, 0, 1});
const y1 = @shuffle(f32, b, undefined, [_]i32{2, 0, 1});
const y2 = @shuffle(f32, b, undefined, [_]i32{1, 2, 0});
return x1 * y1 - x2 * y2;
}
pub fn magf3(v: VFloat3) f32 {
return std.math.sqrt(dotf3(v, v));
}
pub fn magsqf3(v: VFloat3) f32 {
return dotf3(v, v);
}
pub fn normf3(v: VFloat3) VFloat3 {
return v / @splat(3, magf3(v));
}
pub fn magf4(v: Float4) f32 {
return std.math.sqrt(dotf4(v, v));
}
pub fn magsqf4(v: Float4) f32 {
return dotf4(v, v);
}
pub fn mulf33(m: *Float3x3, v: VFloat3) void {
m.rows[0] = @as(VFloat3, m.rows[0]) * v;
m.rows[1] = @as(VFloat3, m.rows[1]) * v;
m.rows[2] = @as(VFloat3, m.rows[2]) * v;
}
pub fn mulf34(m: *Float3x4, v: Float4) void {
m.rows[0] *= v;
m.rows[1] *= v;
m.rows[2] *= v;
}
pub fn mulf44(m: *Float4x4, v: Float4) void {
m.rows[0] *= v;
m.rows[1] *= v;
m.rows[2] *= v;
m.rows[3] *= v;
}
pub fn mulmf34(x: Float3x4, y: Float3x4) Float3x4 {
var result: Float3x4 = undefined;
comptime var row = 0;
inline while (row < 3) : (row += 1) {
const a = @splat(4, x.rows[row][0]) * y.rows[0];
const b = @splat(4, x.rows[row][1]) * y.rows[1];
const c = @splat(4, x.rows[row][2]) * y.rows[2];
const d = @splat(4, x.rows[row][3]) * Float4{0,0,0,1};
result.rows[row] = (a + b) + (c + d);
}
return result;
}
pub fn mulmf44(x: Float4x4, y: Float4x4) Float4x4 {
var result: Float4x4 = undefined;
comptime var row = 0;
inline while (row < 4) : (row += 1) {
const a = @splat(4, x.rows[row][0]) * y.rows[0];
const b = @splat(4, x.rows[row][1]) * y.rows[1];
const c = @splat(4, x.rows[row][2]) * y.rows[2];
const d = @splat(4, x.rows[row][3]) * y.rows[3];
result.rows[row] = (a + b) + (c + d);
}
return result;
}
pub fn lookForward(pos: VFloat3, forward: VFloat3, up: VFloat3) Float4x4 {
const norm_forward = normf3(forward);
const norm_right = normf3(crossf3(up, norm_forward));
const norm_up = crossf3(norm_forward, norm_right);
return .{ .rows = .{
f3tof4(norm_right, -dotf3(norm_right, pos)),
f3tof4(norm_up, -dotf3(norm_up, pos)),
f3tof4(norm_forward, -dotf3(norm_forward, pos)),
.{0, 0, 0, 1},
} };
}
pub fn lookAt(pos: VFloat3, target: VFloat3, up: VFloat3) Float4x4 {
return lookForward(pos, pos - target, up);
}
pub fn perspective(fovy: f32, aspect: f32, zn: f32, zf: f32) Float4x4 {
const focal_length = 1 / std.math.tan(fovy * 0.5);
const m00 = focal_length / aspect;
const m11 = -focal_length;
const m22 = zn / (zf - zn);
const m23 = zf * m22;
return .{ .rows = .{
.{m00, 0, 0, 0},
.{0, m11, 0, 0},
.{0, 0, m22, m23},
.{0, 0, -1, 0},
}};
} | src/simd.zig |
const std = @import("std");
const testing = std.testing;
const allocator = std.testing.allocator;
pub const Vent = struct {
pub const Mode = enum {
HorVer,
HorVerDiag,
};
const Pos = struct {
x: usize,
y: usize,
pub fn init(x: usize, y: usize) Pos {
var self = Pos{
.x = x,
.y = y,
};
return self;
}
pub fn equal(self: Pos, other: Pos) bool {
return self.x == other.x and self.y == other.y;
}
};
const Line = struct {
p1: Pos,
p2: Pos,
pub fn init(p1: Pos, p2: Pos) Line {
var self = Line{
.p1 = p1,
.p2 = p2,
};
return self;
}
pub fn get_delta(self: Line) Pos {
const sx1 = @intCast(isize, self.p1.x);
const sx2 = @intCast(isize, self.p2.x);
const sy1 = @intCast(isize, self.p1.y);
const sy2 = @intCast(isize, self.p2.y);
const dx = @intCast(usize, std.math.absInt(sx1 - sx2) catch unreachable);
const dy = @intCast(usize, std.math.absInt(sy1 - sy2) catch unreachable);
return Pos.init(dx, dy);
}
};
mode: Mode,
data: std.AutoHashMap(Pos, usize),
pub fn init(mode: Mode) Vent {
var self = Vent{
.mode = mode,
.data = std.AutoHashMap(Pos, usize).init(allocator),
};
return self;
}
pub fn deinit(self: *Vent) void {
self.data.deinit();
}
pub fn process_line(self: *Vent, data: []const u8) void {
var l: Line = undefined;
var ends: [2]Pos = undefined;
var lpos: usize = 0;
var itl = std.mem.tokenize(u8, data, " -> ");
while (itl.next()) |point| : (lpos += 1) {
var coords: [2]usize = undefined;
var ppos: usize = 0;
var itp = std.mem.tokenize(u8, point, ",");
while (itp.next()) |num| : (ppos += 1) {
const n = std.fmt.parseInt(usize, num, 10) catch unreachable;
coords[ppos] = n;
if (ppos >= 1) {
ends[lpos] = Pos.init(coords[0], coords[1]);
break;
}
}
if (lpos >= 1) {
l = Line.init(ends[0], ends[1]);
break;
}
}
// std.debug.warn("Line {}\n", .{l});
const delta = l.get_delta();
const dx: isize = if (l.p1.x < l.p2.x) 1 else -1;
const dy: isize = if (l.p1.y < l.p2.y) 1 else -1;
if (delta.y == 0) {
// horizontal
self.iterate_line(l, dx, 0);
}
if (delta.x == 0) {
// vertical
self.iterate_line(l, 0, dy);
}
if (self.mode == Mode.HorVer) return;
if (delta.x == delta.y) {
// diagonal at 45 degrees
self.iterate_line(l, dx, dy);
}
}
pub fn count_points_with_n_vents(self: Vent, n: usize) usize {
var count: usize = 0;
var it = self.data.iterator();
while (it.next()) |entry| {
if (entry.value_ptr.* < n) continue;
count += 1;
}
return count;
}
fn iterate_line(self: *Vent, l: Line, dx: isize, dy: isize) void {
var x = @intCast(isize, l.p1.x);
var y = @intCast(isize, l.p1.y);
while (true) {
const p = Pos.init(@intCast(usize, x), @intCast(usize, y));
if (self.data.contains(p)) {
var entry = self.data.getEntry(p).?;
entry.value_ptr.* += 1;
} else {
self.data.put(p, 1) catch unreachable;
}
if (Pos.equal(p, l.p2)) break;
x += dx;
y += dy;
}
}
};
test "sample part a" {
const data: []const u8 =
\\0,9 -> 5,9
\\8,0 -> 0,8
\\9,4 -> 3,4
\\2,2 -> 2,1
\\7,0 -> 7,4
\\6,4 -> 2,0
\\0,9 -> 2,9
\\3,4 -> 1,4
\\0,0 -> 8,8
\\5,5 -> 8,2
;
var vent = Vent.init(Vent.Mode.HorVer);
defer vent.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
vent.process_line(line);
}
const points = vent.count_points_with_n_vents(2);
try testing.expect(points == 5);
}
test "sample part b" {
const data: []const u8 =
\\0,9 -> 5,9
\\8,0 -> 0,8
\\9,4 -> 3,4
\\2,2 -> 2,1
\\7,0 -> 7,4
\\6,4 -> 2,0
\\0,9 -> 2,9
\\3,4 -> 1,4
\\0,0 -> 8,8
\\5,5 -> 8,2
;
var vent = Vent.init(Vent.Mode.HorVerDiag);
defer vent.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
vent.process_line(line);
}
const points = vent.count_points_with_n_vents(2);
try testing.expect(points == 12);
} | 2021/p05/vent.zig |
pub const std = @import("std");
pub const enable = @import("build_options").enable_tracy;
extern fn ___tracy_emit_zone_begin_callstack(
srcloc: *const ___tracy_source_location_data,
depth: c_int,
active: c_int,
) ___tracy_c_zone_context;
extern fn ___tracy_emit_zone_end(ctx: ___tracy_c_zone_context) void;
extern fn ___tracy_emit_frame_mark(name: ?[*:0]const u8) void;
pub const ___tracy_source_location_data = extern struct {
name: ?[*:0]const u8,
function: [*:0]const u8,
file: [*:0]const u8,
line: u32,
color: u32,
};
pub const ___tracy_c_zone_context = extern struct {
id: u32,
active: c_int,
pub inline fn end(self: ___tracy_c_zone_context) void {
___tracy_emit_zone_end(self);
}
};
pub const Ctx = if (enable) ___tracy_c_zone_context else struct {
pub inline fn end(self: Ctx) void {
_ = self;
}
};
pub inline fn zone(
comptime src: std.builtin.SourceLocation,
comptime active: c_int,
) Ctx {
if (!enable) return .{};
const loc = ___tracy_source_location_data{
.name = null,
.function = src.fn_name.ptr,
.file = src.file.ptr,
.line = src.line,
.color = 0,
};
return ___tracy_emit_zone_begin_callstack(&loc, 1, active);
}
pub inline fn zoneN(
comptime src: std.builtin.SourceLocation,
comptime name: ?[*:0]const u8,
comptime active: c_int,
) Ctx {
if (!enable) return .{};
const loc = ___tracy_source_location_data{
.name = name,
.function = src.fn_name.ptr,
.file = src.file.ptr,
.line = src.line,
.color = 0,
};
return ___tracy_emit_zone_begin_callstack(&loc, 1, active);
}
pub inline fn zoneNC(
comptime src: std.builtin.SourceLocation,
comptime name: ?[*:0]const u8,
comptime color: u32,
comptime active: c_int,
) Ctx {
if (!enable) return .{};
const loc = ___tracy_source_location_data{
.name = name,
.function = src.fn_name.ptr,
.file = src.file.ptr,
.line = src.line,
.color = color,
};
return ___tracy_emit_zone_begin_callstack(&loc, 1, active);
}
pub inline fn frameMark() void {
if (!enable) return;
___tracy_emit_frame_mark(null);
}
pub inline fn frameMarkNamed(comptime name: [*:0]const u8) void {
if (!enable) return;
___tracy_emit_frame_mark(name);
} | libs/ztracy/src/ztracy.zig |
const std = @import("std");
const mem = std.mem;
const warn = std.debug.warn;
const c = @import("c.zig");
const irc = @import("client.zig");
const api = @import("api.zig");
const Config = @import("config.zig").Config;
pub const Context = struct {
config: Config,
requests: std.StringHashMap(api.Request),
};
pub const Handler = fn (ctx: Context, sender: ?[]const u8, text: ?[]const u8, buf: ?[]u8) anyerror!?[]const u8;
pub fn uptime(ctx: Context, sender: ?[]const u8, text: ?[]const u8, buf: ?[]u8) anyerror!?[]const u8 {
// TODO: validate buffer is not null
// var buf = _buf orelse return error.MissingBuffer;
if (try get_cached("get_stream", "created_at", ctx, sender, text)) |created_at| {
// TODO: parse time and return difference between now and then
return try std.fmt.bufPrint(buf.?, "live since {}", .{created_at});
}
return "stream is not live"[0..];
}
pub fn bio(ctx: Context, sender: ?[]const u8, text: ?[]const u8, buf: ?[]u8) anyerror!?[]const u8 {
if (try get_cached("get_users", "bio", ctx, sender, text)) |_bio| {
return try std.fmt.bufPrint(buf.?, "{}", .{_bio});
}
return null;
}
pub fn name(ctx: Context, sender: ?[]const u8, text: ?[]const u8, buf: ?[]u8) anyerror!?[]const u8 {
if (try get_cached("get_users", "name", ctx, sender, text)) |_name| {
return try std.fmt.bufPrint(buf.?, "{}", .{_name});
}
return null;
}
// test request with require
pub fn logo(ctx: Context, sender: ?[]const u8, text: ?[]const u8, buf: ?[]u8) anyerror!?[]const u8 {
if (try get_cached("get_user_by_id", "logo", ctx, sender, text)) |_logo| {
return try std.fmt.bufPrint(buf.?, "{}", .{_logo});
}
return null;
}
fn get_cached(req_key: []const u8, cached_key: []const u8, ctx: Context, sender: ?[]const u8, text: ?[]const u8) anyerror!?[]const u8 {
if (ctx.requests.get(req_key)) |request| {
try request.value.fetch(ctx.requests);
// request.value.print();
const cachedkv = request.value.cached.get(cached_key) orelse return null;
switch (cachedkv.value.value orelse return null) {
.String => |s| return s,
else => return error.UnsupportedJsonType,
}
} else return error.KeyNotFound;
return null;
} | src/message_handlers.zig |
pub const cs_generate_mipmaps =
\\ struct Uniforms {
\\ src_mip_level: i32,
\\ num_mip_levels: u32,
\\ }
\\ @group(0) @binding(0) var<uniform> uniforms: Uniforms;
\\
\\ @group(0) @binding(1) var src_image: texture_2d<f32>;
\\ @group(0) @binding(2) var dst_mipmap1: texture_storage_2d<rgba32float, write>;
\\ @group(0) @binding(3) var dst_mipmap2: texture_storage_2d<rgba32float, write>;
\\ @group(0) @binding(4) var dst_mipmap3: texture_storage_2d<rgba32float, write>;
\\ @group(0) @binding(5) var dst_mipmap4: texture_storage_2d<rgba32float, write>;
\\
\\ var<workgroup> red: array<f32, 64>;
\\ var<workgroup> green: array<f32, 64>;
\\ var<workgroup> blue: array<f32, 64>;
\\ var<workgroup> alpha: array<f32, 64>;
\\
\\ fn storeColor(index: u32, color: vec4<f32>) {
\\ red[index] = color.x;
\\ green[index] = color.y;
\\ blue[index] = color.z;
\\ alpha[index] = color.w;
\\ }
\\
\\ fn loadColor(index: u32) -> vec4<f32> {
\\ return vec4(red[index], green[index], blue[index], alpha[index]);
\\ }
\\
\\ @stage(compute) @workgroup_size(8, 8, 1)
\\ fn main(
\\ @builtin(global_invocation_id) global_invocation_id: vec3<u32>,
\\ @builtin(local_invocation_index) local_invocation_index : u32,
\\ ) {
\\ let x = i32(global_invocation_id.x * 2u);
\\ let y = i32(global_invocation_id.y * 2u);
\\
\\ var s00 = textureLoad(src_image, vec2(x, y), uniforms.src_mip_level);
\\ var s10 = textureLoad(src_image, vec2(x + 1, y), uniforms.src_mip_level);
\\ var s01 = textureLoad(src_image, vec2(x, y + 1), uniforms.src_mip_level);
\\ var s11 = textureLoad(src_image, vec2(x + 1, y + 1), uniforms.src_mip_level);
\\ s00 = 0.25 * (s00 + s01 + s10 + s11);
\\
\\ textureStore(dst_mipmap1, vec2<i32>(global_invocation_id.xy), s00);
\\ storeColor(local_invocation_index, s00);
\\ if (uniforms.num_mip_levels == 1u) {
\\ return;
\\ }
\\ workgroupBarrier();
\\
\\ if ((local_invocation_index & 0x9u) == 0u) {
\\ s10 = loadColor(local_invocation_index + 1u);
\\ s01 = loadColor(local_invocation_index + 8u);
\\ s11 = loadColor(local_invocation_index + 9u);
\\ s00 = 0.25 * (s00 + s01 + s10 + s11);
\\ textureStore(dst_mipmap2, vec2<i32>(global_invocation_id.xy / 2u), s00);
\\ storeColor(local_invocation_index, s00);
\\ }
\\ if (uniforms.num_mip_levels == 2u) {
\\ return;
\\ }
\\ workgroupBarrier();
\\
\\ if ((local_invocation_index & 0x1Bu) == 0u) {
\\ s10 = loadColor(local_invocation_index + 2u);
\\ s01 = loadColor(local_invocation_index + 16u);
\\ s11 = loadColor(local_invocation_index + 18u);
\\ s00 = 0.25 * (s00 + s01 + s10 + s11);
\\ textureStore(dst_mipmap3, vec2<i32>(global_invocation_id.xy / 4u), s00);
\\ storeColor(local_invocation_index, s00);
\\ }
\\ if (uniforms.num_mip_levels == 3u) {
\\ return;
\\ }
\\ workgroupBarrier();
\\
\\ if (local_invocation_index == 0u) {
\\ s10 = loadColor(local_invocation_index + 4u);
\\ s01 = loadColor(local_invocation_index + 32u);
\\ s11 = loadColor(local_invocation_index + 36u);
\\ s00 = 0.25 * (s00 + s01 + s10 + s11);
\\ textureStore(dst_mipmap4, vec2<i32>(global_invocation_id.xy / 8u), s00);
\\ storeColor(local_invocation_index, s00);
\\ }
\\ }
;
// zig fmt: on | libs/zgpu/src/common_wgsl.zig |
const std = @import("std");
const sling = @import("sling.zig");
const fmod = @import("fmod.zig");
var sys: ?*fmod.FMOD_STUDIO_SYSTEM = null;
var events = sling.util.HoleQueue(?*fmod.FMOD_STUDIO_EVENTINSTANCE).init(sling.alloc);
var banks = std.ArrayList(Bank).init(sling.alloc);
pub const Bank = struct {
raw: ?*fmod.FMOD_STUDIO_BANK,
pub fn loadImpl(path: []const u8) Bank {
var self = Bank{
.raw = undefined,
};
var res = fmod.FMOD_Studio_System_LoadBankFile(sys, path.ptr, fmod.FMOD_STUDIO_LOAD_BANK_NORMAL, &self.raw);
errCheck(res, "Loading bank");
return self;
}
pub fn freeEvent(self: *Bank, event: Event) void {
_ = self;
_ = event;
}
};
/// Takes a path and adds the contents of the bank to the audio pool.
/// Make sure to add Master.bank and Master.strings.bank.
/// For now you don't have a way to free it, but I'll get to that.
pub fn loadBank(bankPath: []const u8) void {
banks.append(Bank.loadImpl(bankPath)) catch unreachable;
}
/// Given a GUID or a Path identifier inside of the fmod project, creates
/// an event for you to use to trigger sounds.
/// For an example, '{AAAA-AAAA-AAAA-AAAA}'' or 'event:/footsteps'
pub fn makeEvent(eventName: []const u8) Event {
var evt = Event{ .raw = undefined };
var desc: ?*fmod.FMOD_STUDIO_EVENTDESCRIPTION = null;
var res = fmod.FMOD_Studio_System_GetEvent(sys, eventName.ptr, &desc);
errCheck(res, "Getting event from system");
var inst: ?*fmod.FMOD_STUDIO_EVENTINSTANCE = null;
res = fmod.FMOD_Studio_EventDescription_CreateInstance(desc, &inst);
errCheck(res, "Creating an instance");
evt.raw = events.take(inst) catch {
std.debug.panic("Failed to reserve an fmod instance", .{});
};
return evt;
}
pub const Event = struct {
volume: f32 = 1.0,
raw: usize,
/// Where param is the name of the event's parameter, and value is its new value.
/// Note you must provide the enum's index in the case of enum parameter values.
pub fn set(self: *Event, param: []const u8, value: f32) void {
var inst: ?*fmod.FMOD_STUDIO_EVENTINSTANCE = events.getCopy(self.raw);
errCheck(fmod.FMOD_Studio_EventInstance_SetParameterByName(inst, param.ptr, value, 1), "Setting event parameter by name");
}
/// In a timeline event, seek to a certain time.
pub fn seek(self: *Event, timelineMs: i32) void {
var inst: ?*fmod.FMOD_STUDIO_EVENTINSTANCE = events.getCopy(self.raw);
errCheck(fmod.FMOD_Studio_EventInstance_SetTimelinePosition(inst, @intCast(c_int, timelineMs)), "Setting event timeline");
}
/// Triggers a play event, or causes the timeline to start.
pub fn play(self: *Event) void {
var inst: ?*fmod.FMOD_STUDIO_EVENTINSTANCE = events.getCopy(self.raw);
errCheck(fmod.FMOD_Studio_EventInstance_Start(inst), "Playing event instance");
}
pub fn triggerCue(self: *Event) void {
var inst: ?*fmod.FMOD_STUDIO_EVENTINSTANCE = events.getCopy(self.raw);
errCheck(fmod.FMOD_Studio_EventInstance_TriggerCue(inst), "Triggering cue in event instance");
}
/// Stops the current sound (allowing it to fade out if set to do so), but does not release it.
pub fn stop(self: *Event) void {
var inst: ?*fmod.FMOD_STUDIO_EVENTINSTANCE = events.getCopy(self.raw);
errCheck(fmod.FMOD_Studio_EventInstance_Stop(inst, fmod.FMOD_STUDIO_STOP_ALLOWFADEOUT), "Stopping event instance");
}
/// Invalidates the event, and frees it from fmod.
pub fn release(self: *Event) void {
var inst: ?*fmod.FMOD_STUDIO_EVENTINSTANCE = events.getCopy(self.raw);
errCheck(fmod.FMOD_Studio_EventInstance_Release(inst), "Releasing event instance");
events.release(self.raw) catch {
std.debug.panic("Failed to release fmod event", .{});
};
}
/// Immediately ends a sound, without allowing it to fade out. Does not release it.
pub fn halt(self: *Event) void {
var inst: ?*fmod.FMOD_STUDIO_EVENTINSTANCE = events.getCopy(self.raw);
errCheck(fmod.FMOD_Studio_EventInstance_Stop(inst, fmod.FMOD_STUDIO_STOP_IMMEDIATE), "Stopping event instance");
}
/// A value of 1.0 is default volume.
pub fn setVolume(self: *Event, value: f32) void {
if (value == self.volume) {
return;
}
var inst: ?*fmod.FMOD_STUDIO_EVENTINSTANCE = events.getCopy(self.raw);
errCheck(fmod.FMOD_Studio_EventInstance_SetVolume(inst, value), "Changing volume");
self.volume = value;
}
};
fn errCheck(result: fmod.FMOD_RESULT, message: []const u8) void {
if (result != fmod.FMOD_OK) {
std.debug.panic("Fmod error while '{s}'\nError Code: {any}", .{ message, result });
}
}
/// Do not call this, sling handles it for you.
pub fn init() void {
var res: fmod.FMOD_RESULT = undefined;
res = fmod.FMOD_Studio_System_Create(&sys, fmod.FMOD_VERSION);
errCheck(res, "Creating the FMOD Studio System");
if (std.builtin.mode == .Debug) {
res = fmod.FMOD_Studio_System_Initialize(sys, 256, fmod.FMOD_STUDIO_INIT_LIVEUPDATE, fmod.FMOD_INIT_NORMAL, null);
errCheck(res, "Initializing FMOD Studio System");
} else {
res = fmod.FMOD_Studio_System_Initialize(sys, 256, fmod.FMOD_STUDIO_INIT_NORMAL, fmod.FMOD_INIT_NORMAL, null);
errCheck(res, "Initializing FMOD Studio System");
}
}
/// Do not call this, sling handles it for you.
pub fn update() void {
var res = fmod.FMOD_Studio_System_Update(sys);
errCheck(res, "Updating FMOD");
} | src/audio.zig |
const bs = @import("./bitstream.zig");
const hm = @import("./huffman.zig");
const lz = @import("./lz77.zig");
const tables = @import("./tables.zig");
const bits_utils = @import("./bits.zig");
const std = @import("std");
const assert = std.debug.assert;
const mem = std.mem;
const math = std.math;
const UINT8_MAX = math.maxInt(u8);
const UINT16_MAX = math.maxInt(u16);
const BUFFER_CAP = 32 * 1024;
pub const explode_stat_t: type = enum {
HWEXPLODE_OK, // Explode was successful.
HWEXPLODE_ERR, // Error in the input data.
};
pub const implode_state_t: type = struct {
large_wnd: bool,
lit_tree: bool,
buffer: [BUFFER_CAP]struct {
dist: u16, // Backref dist, or 0 for literals.
litlen: u16, // Literal byte (dist=0) or backref length.
},
buffer_size: usize,
buffer_flushed: bool,
lit_freqs: [256]u16,
dist_sym_freqs: [64]u16,
len_sym_freqs: [64]u16,
os: bs.ostream_t,
lit_encoder: hm.huffman_encoder_t,
len_encoder: hm.huffman_encoder_t,
dist_encoder: hm.huffman_encoder_t,
};
fn max_dist(large_wnd: bool) usize {
return if (large_wnd) 8192 else 4096;
}
fn max_len(lit_tree: bool) usize {
return (if (lit_tree) @as(usize, 3) else @as(usize, 2)) + 63 + 255;
}
fn dist_sym(dist_arg: usize, large_wnd: bool) u32 {
var dist: usize = dist_arg;
assert(dist >= 1);
assert(dist <= max_dist(large_wnd));
dist -= 1;
return @intCast(u32, (dist >> (if (large_wnd) @as(u6, 7) else @as(u6, 6))));
}
fn len_sym(len_arg: usize, lit_tree: bool) u32 {
var len: usize = len_arg;
assert(len >= (if (lit_tree) @as(usize, 3) else @as(usize, 2)));
assert(len <= max_len(lit_tree));
len -= (if (lit_tree) @as(usize, 3) else @as(usize, 2));
if (len < 63) {
return @intCast(u32, len);
}
return 63; // The remainder is in a separate byte.
}
fn write_lit(s: *implode_state_t, lit: u8) bool {
// Literal marker bit.
if (!bs.ostream_write(&s.os, 0x1, 1)) {
return false;
}
if (s.lit_tree) {
// Huffman coded literal.
return bs.ostream_write(
&s.os,
s.lit_encoder.codewords[lit],
s.lit_encoder.lengths[lit],
);
}
// Raw literal.
return bs.ostream_write(&s.os, lit, 8);
}
fn write_backref(s: *implode_state_t, dist: usize, len: usize) bool {
var d: u32 = 0;
var l: u32 = 0;
var num_dist_bits: u6 = 0;
var extra_len: usize = 0;
d = dist_sym(dist, s.large_wnd);
l = len_sym(len, s.lit_tree);
// Backref marker bit.
if (!bs.ostream_write(&s.os, 0x0, 1)) {
return false;
}
// Lower dist bits.
assert(dist >= 1);
num_dist_bits = if (s.large_wnd) @as(u6, 7) else @as(u6, 6);
if (!bs.ostream_write(&s.os, bits_utils.lsb(dist - 1, num_dist_bits), num_dist_bits)) {
return false;
}
// Upper 6 dist bits, Huffman coded.
if (!bs.ostream_write(&s.os, s.dist_encoder.codewords[d], s.dist_encoder.lengths[d])) {
return false;
}
// Huffman coded length.
if (!bs.ostream_write(&s.os, s.len_encoder.codewords[l], s.len_encoder.lengths[l])) {
return false;
}
if (l == 63) {
// Extra length byte.
extra_len = len - 63 - (if (s.lit_tree) @as(usize, 3) else @as(usize, 2));
assert(extra_len <= UINT8_MAX);
if (!bs.ostream_write(&s.os, extra_len, 8)) {
return false;
}
}
return true;
}
const rle_t: type = struct {
len: u8,
num: u8,
};
fn write_huffman_code(
os: *bs.ostream_t,
codeword_lengths: [*]const u8,
num_syms: usize,
) bool {
var rle: [256]rle_t = undefined;
var rle_size: usize = 0;
var i: usize = 0;
assert(num_syms > 0);
assert(num_syms <= rle.len);
// Run-length encode the codeword lengths.
rle[0].len = codeword_lengths[0];
rle[0].num = 1;
rle_size = 1;
i = 1;
while (i < num_syms) : (i += 1) {
if (rle[rle_size - 1].len == codeword_lengths[i] and
rle[rle_size - 1].num < 16)
{
rle[rle_size - 1].num += 1;
continue;
}
assert(rle_size < rle.len);
rle[rle_size].len = codeword_lengths[i];
rle[rle_size].num = 1;
rle_size += 1;
}
// Write the number of run-length encoded lengths.
assert(rle_size >= 1);
if (!bs.ostream_write(os, rle_size - 1, 8)) {
return false;
}
// Write the run-length encoded lengths.
i = 0;
while (i < rle_size) : (i += 1) {
assert(rle[i].num >= 1 and rle[i].num <= 16);
assert(rle[i].len >= 1 and rle[i].len <= 16);
if (!bs.ostream_write(os, rle[i].len - 1, 4) or
!bs.ostream_write(os, rle[i].num - 1, 4))
{
return false;
}
}
return true;
}
fn init_encoder(e: *hm.huffman_encoder_t, freqs: [*]u16, n: usize) void {
var i: usize = 0;
var scale_factor: usize = 0;
var freq_sum: u16 = 0;
var zero_freqs: u16 = 0;
assert(BUFFER_CAP <= UINT16_MAX); // "Frequency sum must be guaranteed to fit in 16 bits."
freq_sum = 0;
zero_freqs = 0;
i = 0;
while (i < n) : (i += 1) {
freq_sum += freqs[i];
zero_freqs += if (freqs[i] == 0) @as(u16, 1) else @as(u16, 0);
}
scale_factor = UINT16_MAX / (freq_sum + zero_freqs);
assert(scale_factor >= 1);
i = 0;
while (i < n) : (i += 1) {
if (freqs[i] == 0) {
// The Huffman encoder was designed for Deflate, which
// excludes zero-frequency symbols from the code. That
// doesn't work with Implode, so enforce a minimum
// frequency of one.
freqs[i] = 1;
continue;
}
// Scale up to emphasise difference to the zero-freq symbols.
freqs[i] *= @intCast(u16, scale_factor);
assert(freqs[i] >= 1);
}
hm.huffman_encoder_init(
e,
freqs,
n,
16, //max_codeword_len=16
);
// Flip the bits to get the Implode-style canonical code.
i = 0;
while (i < n) : (i += 1) {
assert(e.lengths[i] >= 1);
e.codewords[i] = @intCast(u16, bits_utils.lsb(~e.codewords[i], @intCast(u6, e.lengths[i])));
}
}
fn flush_buffer(s: *implode_state_t) bool {
var i: usize = 0;
assert(!s.buffer_flushed);
if (s.lit_tree) {
init_encoder(&s.lit_encoder, &s.lit_freqs, 256);
if (!write_huffman_code(&s.os, &s.lit_encoder.lengths, 256)) {
return false;
}
}
init_encoder(&s.len_encoder, &s.len_sym_freqs, 64);
if (!write_huffman_code(&s.os, &s.len_encoder.lengths, 64)) {
return false;
}
init_encoder(&s.dist_encoder, &s.dist_sym_freqs, 64);
if (!write_huffman_code(&s.os, &s.dist_encoder.lengths, 64)) {
return false;
}
i = 0;
while (i < s.buffer_size) : (i += 1) {
if (s.buffer[i].dist == 0) {
if (!write_lit(s, @intCast(u8, s.buffer[i].litlen))) {
return false;
}
} else {
if (!write_backref(s, s.buffer[i].dist, s.buffer[i].litlen)) {
return false;
}
}
}
s.buffer_flushed = true;
return true;
}
fn lit_callback(lit: u8, aux: anytype) bool {
var s: *implode_state_t = aux;
if (s.buffer_flushed) {
return write_lit(s, lit);
}
assert(s.buffer_size < BUFFER_CAP);
s.buffer[s.buffer_size].dist = 0;
s.buffer[s.buffer_size].litlen = lit;
s.buffer_size += 1;
s.lit_freqs[lit] += 1;
if (s.buffer_size == BUFFER_CAP) {
return flush_buffer(s);
}
return true;
}
fn backref_callback(dist: usize, len: usize, aux: anytype) bool {
var s: *implode_state_t = aux;
assert(dist >= 1);
assert(dist <= max_dist(s.large_wnd));
assert(len >= (if (s.lit_tree) @as(usize, 3) else @as(usize, 2)));
assert(len <= max_len(s.lit_tree));
if (s.buffer_flushed) {
return write_backref(s, dist, len);
}
assert(s.buffer_size < BUFFER_CAP);
s.buffer[s.buffer_size].dist = @intCast(u16, dist);
s.buffer[s.buffer_size].litlen = @intCast(u16, len);
s.buffer_size += 1;
s.dist_sym_freqs[dist_sym(dist, s.large_wnd)] += 1;
s.len_sym_freqs[len_sym(len, s.lit_tree)] += 1;
if (s.buffer_size == BUFFER_CAP) {
return flush_buffer(s);
}
return true;
}
// PKZip Method 6: Implode / Explode.
// Compress (implode) the data in src into dst, using a large window and Huffman
// coding of literals as specified by the flags. The number of bytes output, at
// most dst_cap, is stored in *dst_used. Returns false if there is not enough
// room in dst.
pub fn hwimplode(
src: [*]const u8,
src_len: usize,
large_wnd: bool,
lit_tree: bool,
dst: [*]u8,
dst_cap: usize,
dst_used: *usize,
) bool {
var s: implode_state_t = undefined;
s.large_wnd = large_wnd;
s.lit_tree = lit_tree;
s.buffer_size = 0;
s.buffer_flushed = false;
mem.set(u16, s.dist_sym_freqs[0..], 0);
mem.set(u16, s.len_sym_freqs[0..], 0);
mem.set(u16, s.lit_freqs[0..], 0);
bs.ostream_init(&s.os, dst, dst_cap);
if (!lz.lz77_compress(
src,
src_len,
max_dist(large_wnd),
max_len(lit_tree),
true, //allow_overlap=true
lit_callback,
backref_callback,
&s,
)) {
return false;
}
if (!s.buffer_flushed and !flush_buffer(&s)) {
return false;
}
dst_used.* = bs.ostream_bytes_written(&s.os);
return true;
}
// Initialize the Huffman decoder d with num_lens codeword lengths read from is.
// Returns false if the input is invalid.
fn read_huffman_code(
is: *bs.istream_t,
num_lens: usize,
d: *hm.huffman_decoder_t,
) bool {
var lens: [256]u8 = [1]u8{0} ** 256;
var byte: u8 = 0;
var codeword_len: u8 = 0;
var run_length: u8 = 0;
var num_bytes: usize = 0;
var byte_idx: usize = 0;
var codeword_idx: usize = 0;
var i: usize = 0;
var len_count: [17]u16 = [1]u16{0} ** 17;
var avail_codewords: i32 = 0;
var ok: bool = false;
assert(num_lens <= lens.len);
// Number of bytes representing the Huffman code.
byte = @intCast(u8, bits_utils.lsb(bs.istream_bits(is), 8));
num_bytes = @intCast(usize, byte) + 1;
if (!bs.istream_advance(is, 8)) {
return false;
}
codeword_idx = 0;
byte_idx = 0;
while (byte_idx < num_bytes) : (byte_idx += 1) {
byte = @intCast(u8, bits_utils.lsb(bs.istream_bits(is), 8));
if (!bs.istream_advance(is, 8)) {
return false;
}
codeword_len = (byte & 0xf) + 1; // Low four bits plus one.
run_length = (byte >> 4) + 1; // High four bits plus one.
assert(codeword_len >= 1 and codeword_len <= 16);
assert(codeword_len < len_count.len);
len_count[codeword_len] += run_length;
if (codeword_idx + run_length > num_lens) {
return false; // Too many codeword lengths.
}
i = 0;
while (i < run_length) : (i += 1) {
assert(codeword_idx < num_lens);
lens[codeword_idx] = codeword_len;
codeword_idx += 1;
}
}
assert(codeword_idx <= num_lens);
if (codeword_idx < num_lens) {
return false; // Too few codeword lengths.
}
// Check that the Huffman tree is full.
avail_codewords = 1;
i = 1;
while (i <= 16) : (i += 1) {
assert(avail_codewords >= 0);
avail_codewords *= 2;
avail_codewords -= len_count[i];
if (avail_codewords < 0) {
// Higher count than available codewords.
return false;
}
}
if (avail_codewords != 0) {
// Not all codewords were used.
return false;
}
ok = hm.huffman_decoder_init(d, &lens, num_lens);
assert(ok); // "The checks above mean the tree should be valid."
return true;
}
// Decompress (explode) the data in src. The uncompressed data is uncomp_len
// bytes long. large_wnd is true if a large window was used for compression,
// lit_tree is true if literals were Huffman coded, and pk101_bug_compat is
// true if compatibility with PKZip 1.01/1.02 is desired. The number of input
// bytes used, at most src_len, is written to *src_used on success. Output is
// written to dst.
pub fn hwexplode(
src: [*]const u8,
src_len: usize,
uncomp_len: usize,
large_wnd: bool,
lit_tree: bool,
pk101_bug_compat: bool,
src_used: *usize,
dst: [*]u8,
) !explode_stat_t {
var is: bs.istream_t = undefined;
var lit_decoder: hm.huffman_decoder_t = undefined;
var len_decoder: hm.huffman_decoder_t = undefined;
var dist_decoder: hm.huffman_decoder_t = undefined;
var dst_pos: usize = 0;
var used: usize = 0;
var used_tot: usize = 0;
var dist: usize = 0;
var len: usize = 0;
var i: usize = 0;
var bits: u64 = 0;
var sym: u32 = 0;
var min_len: u32 = 0;
bs.istream_init(&is, src, src_len);
if (lit_tree) {
if (!read_huffman_code(&is, 256, &lit_decoder)) {
return explode_stat_t.HWEXPLODE_ERR;
}
}
if (!read_huffman_code(&is, 64, &len_decoder) or
!read_huffman_code(&is, 64, &dist_decoder))
{
return explode_stat_t.HWEXPLODE_ERR;
}
if (pk101_bug_compat) {
min_len = if (large_wnd) 3 else 2;
} else {
min_len = if (lit_tree) 3 else 2;
}
dst_pos = 0;
while (dst_pos < uncomp_len) {
bits = bs.istream_bits(&is);
if (bits_utils.lsb(bits, 1) == 0x1) {
// Literal.
bits >>= 1;
if (lit_tree) {
sym = try hm.huffman_decode(
&lit_decoder,
@truncate(u16, ~bits),
&used,
);
assert(sym >= 0); // "huffman decode successful"
if (!bs.istream_advance(&is, 1 + used)) {
return explode_stat_t.HWEXPLODE_ERR;
}
} else {
sym = @intCast(u32, bits_utils.lsb(bits, 8));
if (!bs.istream_advance(&is, 1 + 8)) {
return explode_stat_t.HWEXPLODE_ERR;
}
}
assert(sym >= 0 and sym <= UINT8_MAX);
dst[dst_pos] = @intCast(u8, sym);
dst_pos += 1;
continue;
}
// Backref.
assert(bits_utils.lsb(bits, 1) == 0x0);
used_tot = 1;
bits >>= 1;
// Read the low dist bits.
if (large_wnd) {
dist = @intCast(usize, bits_utils.lsb(bits, 7));
bits >>= 7;
used_tot += 7;
} else {
dist = @intCast(usize, bits_utils.lsb(bits, 6));
bits >>= 6;
used_tot += 6;
}
// Read the Huffman-encoded high dist bits.
sym = try hm.huffman_decode(&dist_decoder, @truncate(u16, ~bits), &used);
assert(sym >= 0); // "huffman decode successful"
used_tot += used;
bits >>= @intCast(u6, used);
dist |= @intCast(usize, sym) << if (large_wnd) @intCast(u6, 7) else @intCast(u6, 6);
dist += 1;
// Read the Huffman-encoded len.
sym = try hm.huffman_decode(&len_decoder, @truncate(u16, ~bits), &used);
assert(sym >= 0); // "huffman decode successful"
used_tot += used;
bits >>= @intCast(u6, used);
len = @intCast(usize, sym + min_len);
if (sym == 63) {
// Read an extra len byte.
len += @intCast(usize, bits_utils.lsb(bits, 8));
used_tot += 8;
bits >>= 8;
}
assert(used_tot <= bs.ISTREAM_MIN_BITS);
if (!bs.istream_advance(&is, used_tot)) {
return explode_stat_t.HWEXPLODE_ERR;
}
if (bits_utils.round_up(len, 8) <= uncomp_len - dst_pos and
dist <= dst_pos)
{
// Enough room and no implicit zeros; chunked copy.
lz.lz77_output_backref64(dst, dst_pos, dist, len);
dst_pos += len;
} else if (len > uncomp_len - dst_pos) {
// Not enough room.
return explode_stat_t.HWEXPLODE_ERR;
} else {
// Copy, handling overlap and implicit zeros.
i = 0;
while (i < len) : (i += 1) {
if (dist > dst_pos) {
dst[dst_pos] = 0;
dst_pos += 1;
continue;
}
dst[dst_pos] = dst[dst_pos - dist];
dst_pos += 1;
}
}
}
src_used.* = bs.istream_bytes_read(&is);
return explode_stat_t.HWEXPLODE_OK;
} | src/implode.zig |
const std = @import("std");
const assert = std.debug.assert;
const zp = @import("../../zplay.zig");
const stb_image = zp.deps.stb.image;
const Texture = zp.graphics.common.Texture;
const Self = @This();
pub const Error = error{
LoadImageError,
};
/// gpu texture
tex: *Texture,
/// format of image
format: Texture.ImageFormat = undefined,
/// advanced texture creation options
pub const Option = struct {
s_wrap: Texture.WrappingMode = .repeat,
t_wrap: Texture.WrappingMode = .repeat,
mag_filer: Texture.FilteringMode = .linear,
min_filer: Texture.FilteringMode = .linear,
gen_mipmap: bool = false,
border_color: ?[4]f32 = null,
};
/// init 2d texture from pixel data
pub fn init(
allocator: std.mem.Allocator,
pixel_data: ?[]const u8,
format: Texture.ImageFormat,
width: u32,
height: u32,
option: Option,
) !Self {
var tex = try Texture.init(allocator, .texture_2d);
tex.setWrappingMode(.s, option.s_wrap);
tex.setWrappingMode(.t, option.t_wrap);
tex.setFilteringMode(.minifying, option.min_filer);
tex.setFilteringMode(.magnifying, option.mag_filer);
if (option.border_color) |c| {
tex.setBorderColor(c);
}
tex.updateImageData(
.texture_2d,
0,
switch (format) {
.rgb => .rgb,
.rgba => .rgba,
else => unreachable,
},
width,
height,
null,
format,
u8,
if (pixel_data) |data| data.ptr else null,
option.gen_mipmap,
);
return Self{
.tex = tex,
.format = format,
};
}
pub fn deinit(self: Self) void {
self.tex.deinit();
}
/// create 2d texture with path to image file
pub fn fromFilePath(
allocator: std.mem.Allocator,
file_path: [:0]const u8,
flip: bool,
option: Option,
) !Self {
var width: c_int = undefined;
var height: c_int = undefined;
var channels: c_int = undefined;
stb_image.stbi_set_flip_vertically_on_load(@boolToInt(flip));
var image_data = stb_image.stbi_load(
file_path.ptr,
&width,
&height,
&channels,
0,
);
if (image_data == null) {
return error.LoadImageError;
}
defer stb_image.stbi_image_free(image_data);
return Self.init(
allocator,
image_data[0..@intCast(u32, width * height * channels)],
switch (channels) {
3 => .rgb,
4 => .rgba,
else => std.debug.panic(
"unsupported image format: path({s}) width({d}) height({d}) channels({d})",
.{ file_path, width, height, channels },
),
},
@intCast(u32, width),
@intCast(u32, height),
option,
);
}
/// create 2d texture with given file's data buffer
pub fn fromFileData(allocator: std.mem.Allocator, data: []const u8, flip: bool, option: Option) !Self {
var width: c_int = undefined;
var height: c_int = undefined;
var channels: c_int = undefined;
stb_image.stbi_set_flip_vertically_on_load(@boolToInt(flip));
var image_data = stb_image.stbi_load_from_memory(
data.ptr,
@intCast(c_int, data.len),
&width,
&height,
&channels,
0,
);
if (image_data == null) {
return error.LoadImageError;
}
defer stb_image.stbi_image_free(image_data);
return Self.init(
allocator,
image_data[0..@intCast(u32, width * height * channels)],
switch (channels) {
3 => .rgb,
4 => .rgba,
else => std.debug.panic(
"unsupported image format: width({d}) height({d}) channels({d})",
.{ width, height, channels },
),
},
@intCast(u32, width),
@intCast(u32, height),
option,
);
}
/// create 2d texture with pixel data (r8g8b8a8)
pub fn fromPixelData(allocator: std.mem.Allocator, data: []const u8, width: u32, height: u32, option: Option) !Self {
assert(data.len == width * height * 4);
return Self.init(
allocator,
data,
.rgba,
width,
height,
option,
);
} | src/graphics/texture/Texture2D.zig |
const windows = @import("windows.zig");
const IUnknown = windows.IUnknown;
const WINAPI = windows.WINAPI;
const HRESULT = windows.HRESULT;
const GUID = windows.GUID;
const LPCWSTR = windows.LPCWSTR;
const DWORD = windows.DWORD;
const UINT = windows.UINT;
const INT = windows.INT;
const BYTE = windows.BYTE;
pub const PixelFormatGUID = windows.GUID;
pub const Rect = extern struct {
X: INT,
Y: INT,
Width: INT,
Height: INT,
};
pub const DecodeOptions = enum(UINT) {
MetadataCacheOnDemand = 0,
MetadataCacheOnLoad = 0x1,
};
pub const BitmapPaletteType = enum(UINT) {
Custom = 0,
MedianCut = 0x1,
FixedBW = 0x2,
FixedHalftone8 = 0x3,
FixedHalftone27 = 0x4,
FixedHalftone64 = 0x5,
FixedHalftone125 = 0x6,
FixedHalftone216 = 0x7,
FixedHalftone252 = 0x8,
FixedHalftone256 = 0x9,
FixedGray4 = 0xa,
FixedGray16 = 0xb,
FixedGray256 = 0xc,
};
pub const IPalette = extern struct {
const Self = @This();
v: *const extern struct {
unknown: IUnknown.VTable(Self),
palette: VTable(Self),
},
usingnamespace IUnknown.Methods(Self);
usingnamespace Methods(Self);
fn Methods(comptime T: type) type {
_ = T;
return extern struct {};
}
fn VTable(comptime T: type) type {
_ = T;
return extern struct {
InitializePredefined: *anyopaque,
InitializeCustom: *anyopaque,
InitializeFromBitmap: *anyopaque,
InitializeFromPalette: *anyopaque,
GetType: *anyopaque,
GetColorCount: *anyopaque,
GetColors: *anyopaque,
IsBlackWhite: *anyopaque,
IsGrayscale: *anyopaque,
HasAlpha: *anyopaque,
};
}
};
pub const IBitmapDecoder = extern struct {
const Self = @This();
v: *const extern struct {
unknown: IUnknown.VTable(Self),
bmpdecoder: VTable(Self),
},
usingnamespace IUnknown.Methods(Self);
usingnamespace Methods(Self);
fn Methods(comptime T: type) type {
return extern struct {
pub inline fn GetFrame(self: *T, index: UINT, frame: ?*?*IBitmapFrameDecode) HRESULT {
return self.v.bmpdecoder.GetFrame(self, index, frame);
}
};
}
fn VTable(comptime T: type) type {
return extern struct {
QueryCapability: *anyopaque,
Initialize: *anyopaque,
GetContainerFormat: *anyopaque,
GetDecoderInfo: *anyopaque,
CopyPalette: *anyopaque,
GetMetadataQueryReader: *anyopaque,
GetPreview: *anyopaque,
GetColorContexts: *anyopaque,
GetThumbnail: *anyopaque,
GetFrameCount: *anyopaque,
GetFrame: fn (*T, UINT, ?*?*IBitmapFrameDecode) callconv(WINAPI) HRESULT,
};
}
};
pub const IBitmapSource = extern struct {
const Self = @This();
v: *const extern struct {
unknown: IUnknown.VTable(Self),
bmpsource: VTable(Self),
},
usingnamespace IUnknown.Methods(Self);
usingnamespace Methods(Self);
fn Methods(comptime T: type) type {
return extern struct {
pub inline fn GetSize(self: *T, width: *UINT, height: *UINT) HRESULT {
return self.v.bmpsource.GetSize(self, width, height);
}
pub inline fn GetPixelFormat(self: *T, guid: *PixelFormatGUID) HRESULT {
return self.v.bmpsource.GetPixelFormat(self, guid);
}
pub inline fn CopyPixels(self: *T, rect: ?*const Rect, stride: UINT, size: UINT, buffer: [*]BYTE) HRESULT {
return self.v.bmpsource.CopyPixels(self, rect, stride, size, buffer);
}
};
}
fn VTable(comptime T: type) type {
return extern struct {
GetSize: fn (*T, *UINT, *UINT) callconv(WINAPI) HRESULT,
GetPixelFormat: fn (*T, *GUID) callconv(WINAPI) HRESULT,
GetResolution: *anyopaque,
CopyPalette: *anyopaque,
CopyPixels: fn (*T, ?*const Rect, UINT, UINT, [*]BYTE) callconv(WINAPI) HRESULT,
};
}
};
pub const IBitmapFrameDecode = extern struct {
const Self = @This();
v: *const extern struct {
unknown: IUnknown.VTable(Self),
bmpsource: IBitmapSource.VTable(Self),
bmpframedecode: VTable(Self),
},
usingnamespace IUnknown.Methods(Self);
usingnamespace IBitmapSource.Methods(Self);
usingnamespace Methods(Self);
fn Methods(comptime T: type) type {
_ = T;
return extern struct {};
}
fn VTable(comptime T: type) type {
_ = T;
return extern struct {
GetMetadataQueryReader: *anyopaque,
GetColorContexts: *anyopaque,
GetThumbnail: *anyopaque,
};
}
};
pub const IBitmap = extern struct {
const Self = @This();
v: *const extern struct {
unknown: IUnknown.VTable(Self),
bmpsource: IBitmapSource.VTable(Self),
bmp: VTable(Self),
},
usingnamespace IUnknown.Methods(Self);
usingnamespace IBitmapSource.Methods(Self);
usingnamespace Methods(Self);
fn Methods(comptime T: type) type {
_ = T;
return extern struct {};
}
fn VTable(comptime T: type) type {
_ = T;
return extern struct {
Lock: *anyopaque,
SetPalette: *anyopaque,
SetResolution: *anyopaque,
};
}
};
pub const BitmapDitherType = enum(UINT) {
None = 0,
Ordered4x4 = 0x1,
Ordered8x8 = 0x2,
Ordered16x16 = 0x3,
Spiral4x4 = 0x4,
Spiral8x8 = 0x5,
DualSpiral4x4 = 0x6,
DualSpiral8x8 = 0x7,
ErrorDiffusion = 0x8,
};
pub const IFormatConverter = extern struct {
const Self = @This();
v: *const extern struct {
unknown: IUnknown.VTable(Self),
bmpsource: IBitmapSource.VTable(Self),
fmtconv: VTable(Self),
},
usingnamespace IUnknown.Methods(Self);
usingnamespace IBitmapSource.Methods(Self);
usingnamespace Methods(Self);
fn Methods(comptime T: type) type {
return extern struct {
pub inline fn Initialize(
self: *T,
source: ?*IBitmapSource,
dest_format: *const PixelFormatGUID,
dither: BitmapDitherType,
palette: ?*IPalette,
alpha_threshold_percent: f64,
palette_translate: BitmapPaletteType,
) HRESULT {
return self.v.fmtconv.Initialize(
self,
source,
dest_format,
dither,
palette,
alpha_threshold_percent,
palette_translate,
);
}
};
}
fn VTable(comptime T: type) type {
return extern struct {
Initialize: fn (
*T,
?*IBitmapSource,
*const PixelFormatGUID,
BitmapDitherType,
?*IPalette,
f64,
BitmapPaletteType,
) callconv(WINAPI) HRESULT,
CanConvert: *anyopaque,
};
}
};
pub const IImagingFactory = extern struct {
const Self = @This();
v: *const extern struct {
unknown: IUnknown.VTable(Self),
imgfactory: VTable(Self),
},
usingnamespace IUnknown.Methods(Self);
usingnamespace Methods(Self);
fn Methods(comptime T: type) type {
return extern struct {
pub inline fn CreateDecoderFromFilename(
self: *T,
filename: LPCWSTR,
vendor: ?*const GUID,
access: DWORD,
metadata: DecodeOptions,
decoder: ?*?*IBitmapDecoder,
) HRESULT {
return self.v.imgfactory.CreateDecoderFromFilename(self, filename, vendor, access, metadata, decoder);
}
pub inline fn CreateFormatConverter(self: *T, converter: ?*?*IFormatConverter) HRESULT {
return self.v.imgfactory.CreateFormatConverter(self, converter);
}
};
}
fn VTable(comptime T: type) type {
return extern struct {
CreateDecoderFromFilename: fn (
*T,
LPCWSTR,
?*const GUID,
DWORD,
DecodeOptions,
?*?*IBitmapDecoder,
) callconv(WINAPI) HRESULT,
CreateDecoderFromStream: *anyopaque,
CreateDecoderFromFileHandle: *anyopaque,
CreateComponentInfo: *anyopaque,
CreateDecoder: *anyopaque,
CreateEncoder: *anyopaque,
CreatePalette: *anyopaque,
CreateFormatConverter: fn (*T, ?*?*IFormatConverter) callconv(WINAPI) HRESULT,
CreateBitmapScaler: *anyopaque,
CreateBitmapClipper: *anyopaque,
CreateBitmapFlipRotator: *anyopaque,
CreateStream: *anyopaque,
CreateColorContext: *anyopaque,
CreateColorTransformer: *anyopaque,
CreateBitmap: *anyopaque,
CreateBitmapFromSource: *anyopaque,
CreateBitmapFromSourceRect: *anyopaque,
CreateBitmapFromMemory: *anyopaque,
CreateBitmapFromHBITMAP: *anyopaque,
CreateBitmapFromHICON: *anyopaque,
CreateComponentEnumerator: *anyopaque,
CreateFastMetadataEncoderFromDecoder: *anyopaque,
CreateFastMetadataEncoderFromFrameDecode: *anyopaque,
CreateQueryWriter: *anyopaque,
CreateQueryWriterFromReader: *anyopaque,
};
}
};
pub const CLSID_ImagingFactory = GUID{
.Data1 = 0xcacaf262,
.Data2 = 0x9370,
.Data3 = 0x4615,
.Data4 = .{ 0xa1, 0x3b, 0x9f, 0x55, 0x39, 0xda, 0x4c, 0xa },
};
pub const IID_IImagingFactory = GUID{
.Data1 = 0xec5ec8a9,
.Data2 = 0xc395,
.Data3 = 0x4314,
.Data4 = .{ 0x9c, 0x77, 0x54, 0xd7, 0xa9, 0x35, 0xff, 0x70 },
};
pub const GUID_PixelFormat24bppRGB = PixelFormatGUID{
.Data1 = 0x6fddc324,
.Data2 = 0x4e03,
.Data3 = 0x4bfe,
.Data4 = .{ 0xb1, 0x85, 0x3d, 0x77, 0x76, 0x8d, 0xc9, 0x0d },
};
pub const GUID_PixelFormat32bppRGB = PixelFormatGUID{
.Data1 = 0xd98c6b95,
.Data2 = 0x3efe,
.Data3 = 0x47d6,
.Data4 = .{ 0xbb, 0x25, 0xeb, 0x17, 0x48, 0xab, 0x0c, 0xf1 },
};
pub const GUID_PixelFormat32bppRGBA = PixelFormatGUID{
.Data1 = 0xf5c7ad2d,
.Data2 = 0x6a8d,
.Data3 = 0x43dd,
.Data4 = .{ 0xa7, 0xa8, 0xa2, 0x99, 0x35, 0x26, 0x1a, 0xe9 },
};
pub const GUID_PixelFormat32bppPRGBA = PixelFormatGUID{
.Data1 = 0x3cc4a650,
.Data2 = 0xa527,
.Data3 = 0x4d37,
.Data4 = .{ 0xa9, 0x16, 0x31, 0x42, 0xc7, 0xeb, 0xed, 0xba },
};
pub const GUID_PixelFormat24bppBGR = PixelFormatGUID{
.Data1 = 0x6fddc324,
.Data2 = 0x4e03,
.Data3 = 0x4bfe,
.Data4 = .{ 0xb1, 0x85, 0x3d, 0x77, 0x76, 0x8d, 0xc9, 0x0c },
};
pub const GUID_PixelFormat32bppBGR = PixelFormatGUID{
.Data1 = 0x6fddc324,
.Data2 = 0x4e03,
.Data3 = 0x4bfe,
.Data4 = .{ 0xb1, 0x85, 0x3d, 0x77, 0x76, 0x8d, 0xc9, 0x0e },
};
pub const GUID_PixelFormat32bppBGRA = PixelFormatGUID{
.Data1 = 0x6fddc324,
.Data2 = 0x4e03,
.Data3 = 0x4bfe,
.Data4 = .{ 0xb1, 0x85, 0x3d, 0x77, 0x76, 0x8d, 0xc9, 0x0f },
};
pub const GUID_PixelFormat32bppPBGRA = PixelFormatGUID{
.Data1 = 0x6fddc324,
.Data2 = 0x4e03,
.Data3 = 0x4bfe,
.Data4 = .{ 0xb1, 0x85, 0x3d, 0x77, 0x76, 0x8d, 0xc9, 0x10 },
};
pub const GUID_PixelFormat8bppGray = PixelFormatGUID{
.Data1 = 0x6fddc324,
.Data2 = 0x4e03,
.Data3 = 0x4bfe,
.Data4 = .{ 0xb1, 0x85, 0x3d, 0x77, 0x76, 0x8d, 0xc9, 0x08 },
};
pub const GUID_PixelFormat8bppAlpha = PixelFormatGUID{
.Data1 = 0xe6cd0116,
.Data2 = 0xeeba,
.Data3 = 0x4161,
.Data4 = .{ 0xaa, 0x85, 0x27, 0xdd, 0x9f, 0xb3, 0xa8, 0x95 },
}; | modules/platform/vendored/zwin32/src/wincodec.zig |
const std = @import("std");
const link = @import("link.zig");
const Compilation = @import("Compilation.zig");
const Allocator = std.mem.Allocator;
const zir = @import("zir.zig");
const Package = @import("Package.zig");
const introspect = @import("introspect.zig");
const build_options = @import("build_options");
const enable_qemu: bool = build_options.enable_qemu;
const enable_wine: bool = build_options.enable_wine;
const enable_wasmtime: bool = build_options.enable_wasmtime;
const glibc_multi_install_dir: ?[]const u8 = build_options.glibc_multi_install_dir;
const cheader = @embedFile("link/cbe.h");
test "self-hosted" {
var ctx = TestContext.init();
defer ctx.deinit();
try @import("stage2_tests").addCases(&ctx);
try ctx.run();
}
const ErrorMsg = struct {
msg: []const u8,
line: u32,
column: u32,
};
pub const TestContext = struct {
/// TODO: find a way to treat cases as individual tests (shouldn't show "1 test passed" if there are 200 cases)
cases: std.ArrayList(Case),
pub const Update = struct {
/// The input to the current update. We simulate an incremental update
/// with the file's contents changed to this value each update.
///
/// This value can change entirely between updates, which would be akin
/// to deleting the source file and creating a new one from scratch; or
/// you can keep it mostly consistent, with small changes, testing the
/// effects of the incremental compilation.
src: [:0]const u8,
case: union(enum) {
/// A transformation update transforms the input and tests against
/// the expected output ZIR.
Transformation: [:0]const u8,
/// An error update attempts to compile bad code, and ensures that it
/// fails to compile, and for the expected reasons.
/// A slice containing the expected errors *in sequential order*.
Error: []const ErrorMsg,
/// An execution update compiles and runs the input, testing the
/// stdout against the expected results
/// This is a slice containing the expected message.
Execution: []const u8,
},
};
pub const File = struct {
/// Contents of the importable file. Doesn't yet support incremental updates.
src: [:0]const u8,
path: []const u8,
};
pub const TestType = enum {
Zig,
ZIR,
};
/// A Case consists of a set of *updates*. The same Compilation is used for each
/// update, so each update's source is treated as a single file being
/// updated by the test harness and incrementally compiled.
pub const Case = struct {
/// The name of the test case. This is shown if a test fails, and
/// otherwise ignored.
name: []const u8,
/// The platform the test targets. For non-native platforms, an emulator
/// such as QEMU is required for tests to complete.
target: std.zig.CrossTarget,
/// In order to be able to run e.g. Execution updates, this must be set
/// to Executable.
output_mode: std.builtin.OutputMode,
updates: std.ArrayList(Update),
extension: TestType,
cbe: bool = false,
files: std.ArrayList(File),
/// Adds a subcase in which the module is updated with `src`, and the
/// resulting ZIR is validated against `result`.
pub fn addTransform(self: *Case, src: [:0]const u8, result: [:0]const u8) void {
self.updates.append(.{
.src = src,
.case = .{ .Transformation = result },
}) catch unreachable;
}
/// Adds a subcase in which the module is updated with `src`, compiled,
/// run, and the output is tested against `result`.
pub fn addCompareOutput(self: *Case, src: [:0]const u8, result: []const u8) void {
self.updates.append(.{
.src = src,
.case = .{ .Execution = result },
}) catch unreachable;
}
/// Adds a subcase in which the module is updated with `src`, which
/// should contain invalid input, and ensures that compilation fails
/// for the expected reasons, given in sequential order in `errors` in
/// the form `:line:column: error: message`.
pub fn addError(self: *Case, src: [:0]const u8, errors: []const []const u8) void {
var array = self.updates.allocator.alloc(ErrorMsg, errors.len) catch unreachable;
for (errors) |e, i| {
if (e[0] != ':') {
@panic("Invalid test: error must be specified as follows:\n:line:column: error: message\n=========\n");
}
var cur = e[1..];
var line_index = std.mem.indexOf(u8, cur, ":");
if (line_index == null) {
@panic("Invalid test: error must be specified as follows:\n:line:column: error: message\n=========\n");
}
const line = std.fmt.parseInt(u32, cur[0..line_index.?], 10) catch @panic("Unable to parse line number");
cur = cur[line_index.? + 1 ..];
const column_index = std.mem.indexOf(u8, cur, ":");
if (column_index == null) {
@panic("Invalid test: error must be specified as follows:\n:line:column: error: message\n=========\n");
}
const column = std.fmt.parseInt(u32, cur[0..column_index.?], 10) catch @panic("Unable to parse column number");
cur = cur[column_index.? + 2 ..];
if (!std.mem.eql(u8, cur[0..7], "error: ")) {
@panic("Invalid test: error must be specified as follows:\n:line:column: error: message\n=========\n");
}
const msg = cur[7..];
if (line == 0 or column == 0) {
@panic("Invalid test: error line and column must be specified starting at one!");
}
array[i] = .{
.msg = msg,
.line = line - 1,
.column = column - 1,
};
}
self.updates.append(.{ .src = src, .case = .{ .Error = array } }) catch unreachable;
}
/// Adds a subcase in which the module is updated with `src`, and
/// asserts that it compiles without issue
pub fn compiles(self: *Case, src: [:0]const u8) void {
self.addError(src, &[_][]const u8{});
}
};
pub fn addExe(
ctx: *TestContext,
name: []const u8,
target: std.zig.CrossTarget,
T: TestType,
) *Case {
ctx.cases.append(Case{
.name = name,
.target = target,
.updates = std.ArrayList(Update).init(ctx.cases.allocator),
.output_mode = .Exe,
.extension = T,
.files = std.ArrayList(File).init(ctx.cases.allocator),
}) catch unreachable;
return &ctx.cases.items[ctx.cases.items.len - 1];
}
/// Adds a test case for Zig input, producing an executable
pub fn exe(ctx: *TestContext, name: []const u8, target: std.zig.CrossTarget) *Case {
return ctx.addExe(name, target, .Zig);
}
/// Adds a test case for ZIR input, producing an executable
pub fn exeZIR(ctx: *TestContext, name: []const u8, target: std.zig.CrossTarget) *Case {
return ctx.addExe(name, target, .ZIR);
}
pub fn addObj(
ctx: *TestContext,
name: []const u8,
target: std.zig.CrossTarget,
T: TestType,
) *Case {
ctx.cases.append(Case{
.name = name,
.target = target,
.updates = std.ArrayList(Update).init(ctx.cases.allocator),
.output_mode = .Obj,
.extension = T,
.files = std.ArrayList(File).init(ctx.cases.allocator),
}) catch unreachable;
return &ctx.cases.items[ctx.cases.items.len - 1];
}
/// Adds a test case for Zig input, producing an object file
pub fn obj(ctx: *TestContext, name: []const u8, target: std.zig.CrossTarget) *Case {
return ctx.addObj(name, target, .Zig);
}
/// Adds a test case for ZIR input, producing an object file
pub fn objZIR(ctx: *TestContext, name: []const u8, target: std.zig.CrossTarget) *Case {
return ctx.addObj(name, target, .ZIR);
}
pub fn addC(ctx: *TestContext, name: []const u8, target: std.zig.CrossTarget, T: TestType) *Case {
ctx.cases.append(Case{
.name = name,
.target = target,
.updates = std.ArrayList(Update).init(ctx.cases.allocator),
.output_mode = .Obj,
.extension = T,
.cbe = true,
.files = std.ArrayList(File).init(ctx.cases.allocator),
}) catch unreachable;
return &ctx.cases.items[ctx.cases.items.len - 1];
}
pub fn c(ctx: *TestContext, name: []const u8, target: std.zig.CrossTarget, src: [:0]const u8, comptime out: [:0]const u8) void {
ctx.addC(name, target, .Zig).addTransform(src, cheader ++ out);
}
pub fn addCompareOutput(
ctx: *TestContext,
name: []const u8,
T: TestType,
src: [:0]const u8,
expected_stdout: []const u8,
) void {
ctx.addExe(name, .{}, T).addCompareOutput(src, expected_stdout);
}
/// Adds a test case that compiles the Zig source given in `src`, executes
/// it, runs it, and tests the output against `expected_stdout`
pub fn compareOutput(
ctx: *TestContext,
name: []const u8,
src: [:0]const u8,
expected_stdout: []const u8,
) void {
return ctx.addCompareOutput(name, .Zig, src, expected_stdout);
}
/// Adds a test case that compiles the ZIR source given in `src`, executes
/// it, runs it, and tests the output against `expected_stdout`
pub fn compareOutputZIR(
ctx: *TestContext,
name: []const u8,
src: [:0]const u8,
expected_stdout: []const u8,
) void {
ctx.addCompareOutput(name, .ZIR, src, expected_stdout);
}
pub fn addTransform(
ctx: *TestContext,
name: []const u8,
target: std.zig.CrossTarget,
T: TestType,
src: [:0]const u8,
result: [:0]const u8,
) void {
ctx.addObj(name, target, T).addTransform(src, result);
}
/// Adds a test case that compiles the Zig given in `src` to ZIR and tests
/// the ZIR against `result`
pub fn transform(
ctx: *TestContext,
name: []const u8,
target: std.zig.CrossTarget,
src: [:0]const u8,
result: [:0]const u8,
) void {
ctx.addTransform(name, target, .Zig, src, result);
}
/// Adds a test case that cleans up the ZIR source given in `src`, and
/// tests the resulting ZIR against `result`
pub fn transformZIR(
ctx: *TestContext,
name: []const u8,
target: std.zig.CrossTarget,
src: [:0]const u8,
result: [:0]const u8,
) void {
ctx.addTransform(name, target, .ZIR, src, result);
}
pub fn addError(
ctx: *TestContext,
name: []const u8,
target: std.zig.CrossTarget,
T: TestType,
src: [:0]const u8,
expected_errors: []const []const u8,
) void {
ctx.addObj(name, target, T).addError(src, expected_errors);
}
/// Adds a test case that ensures that the Zig given in `src` fails to
/// compile for the expected reasons, given in sequential order in
/// `expected_errors` in the form `:line:column: error: message`.
pub fn compileError(
ctx: *TestContext,
name: []const u8,
target: std.zig.CrossTarget,
src: [:0]const u8,
expected_errors: []const []const u8,
) void {
ctx.addError(name, target, .Zig, src, expected_errors);
}
/// Adds a test case that ensures that the ZIR given in `src` fails to
/// compile for the expected reasons, given in sequential order in
/// `expected_errors` in the form `:line:column: error: message`.
pub fn compileErrorZIR(
ctx: *TestContext,
name: []const u8,
target: std.zig.CrossTarget,
src: [:0]const u8,
expected_errors: []const []const u8,
) void {
ctx.addError(name, target, .ZIR, src, expected_errors);
}
pub fn addCompiles(
ctx: *TestContext,
name: []const u8,
target: std.zig.CrossTarget,
T: TestType,
src: [:0]const u8,
) void {
ctx.addObj(name, target, T).compiles(src);
}
/// Adds a test case that asserts that the Zig given in `src` compiles
/// without any errors.
pub fn compiles(
ctx: *TestContext,
name: []const u8,
target: std.zig.CrossTarget,
src: [:0]const u8,
) void {
ctx.addCompiles(name, target, .Zig, src);
}
/// Adds a test case that asserts that the ZIR given in `src` compiles
/// without any errors.
pub fn compilesZIR(
ctx: *TestContext,
name: []const u8,
target: std.zig.CrossTarget,
src: [:0]const u8,
) void {
ctx.addCompiles(name, target, .ZIR, src);
}
/// Adds a test case that first ensures that the Zig given in `src` fails
/// to compile for the reasons given in sequential order in
/// `expected_errors` in the form `:line:column: error: message`, then
/// asserts that fixing the source (updating with `fixed_src`) isn't broken
/// by incremental compilation.
pub fn incrementalFailure(
ctx: *TestContext,
name: []const u8,
target: std.zig.CrossTarget,
src: [:0]const u8,
expected_errors: []const []const u8,
fixed_src: [:0]const u8,
) void {
var case = ctx.addObj(name, target, .Zig);
case.addError(src, expected_errors);
case.compiles(fixed_src);
}
/// Adds a test case that first ensures that the ZIR given in `src` fails
/// to compile for the reasons given in sequential order in
/// `expected_errors` in the form `:line:column: error: message`, then
/// asserts that fixing the source (updating with `fixed_src`) isn't broken
/// by incremental compilation.
pub fn incrementalFailureZIR(
ctx: *TestContext,
name: []const u8,
target: std.zig.CrossTarget,
src: [:0]const u8,
expected_errors: []const []const u8,
fixed_src: [:0]const u8,
) void {
var case = ctx.addObj(name, target, .ZIR);
case.addError(src, expected_errors);
case.compiles(fixed_src);
}
fn init() TestContext {
const allocator = std.heap.page_allocator;
return .{ .cases = std.ArrayList(Case).init(allocator) };
}
fn deinit(self: *TestContext) void {
for (self.cases.items) |case| {
for (case.updates.items) |u| {
if (u.case == .Error) {
case.updates.allocator.free(u.case.Error);
}
}
case.updates.deinit();
}
self.cases.deinit();
self.* = undefined;
}
fn run(self: *TestContext) !void {
var progress = std.Progress{};
const root_node = try progress.start("tests", self.cases.items.len);
defer root_node.end();
var zig_lib_directory = try introspect.findZigLibDir(std.testing.allocator);
defer zig_lib_directory.handle.close();
defer std.testing.allocator.free(zig_lib_directory.path.?);
const random_seed = blk: {
var random_seed: u64 = undefined;
try std.crypto.randomBytes(std.mem.asBytes(&random_seed));
break :blk random_seed;
};
var default_prng = std.rand.DefaultPrng.init(random_seed);
for (self.cases.items) |case| {
var prg_node = root_node.start(case.name, case.updates.items.len);
prg_node.activate();
defer prg_node.end();
// So that we can see which test case failed when the leak checker goes off,
// or there's an internal error
progress.initial_delay_ns = 0;
progress.refresh_rate_ns = 0;
try self.runOneCase(std.testing.allocator, &prg_node, case, zig_lib_directory, &default_prng.random);
}
}
fn runOneCase(
self: *TestContext,
allocator: *Allocator,
root_node: *std.Progress.Node,
case: Case,
zig_lib_directory: Compilation.Directory,
rand: *std.rand.Random,
) !void {
const target_info = try std.zig.system.NativeTargetInfo.detect(allocator, case.target);
const target = target_info.target;
var arena_allocator = std.heap.ArenaAllocator.init(allocator);
defer arena_allocator.deinit();
const arena = &arena_allocator.allocator;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
var cache_dir = try tmp.dir.makeOpenPath("zig-cache", .{});
defer cache_dir.close();
const tmp_path = try std.fs.path.join(arena, &[_][]const u8{ ".", "zig-cache", "tmp", &tmp.sub_path });
const zig_cache_directory: Compilation.Directory = .{
.handle = cache_dir,
.path = try std.fs.path.join(arena, &[_][]const u8{ tmp_path, "zig-cache" }),
};
const tmp_src_path = switch (case.extension) {
.Zig => "test_case.zig",
.ZIR => "test_case.zir",
};
var root_pkg: Package = .{
.root_src_directory = .{ .path = tmp_path, .handle = tmp.dir },
.root_src_path = tmp_src_path,
};
const ofmt: ?std.builtin.ObjectFormat = if (case.cbe) .c else null;
const bin_name = try std.zig.binNameAlloc(arena, .{
.root_name = "test_case",
.target = target,
.output_mode = case.output_mode,
.object_format = ofmt,
});
const emit_directory: Compilation.Directory = .{
.path = tmp_path,
.handle = tmp.dir,
};
const emit_bin: Compilation.EmitLoc = .{
.directory = emit_directory,
.basename = bin_name,
};
const comp = try Compilation.create(allocator, .{
.local_cache_directory = zig_cache_directory,
.global_cache_directory = zig_cache_directory,
.zig_lib_directory = zig_lib_directory,
.rand = rand,
.root_name = "test_case",
.target = target,
// TODO: support tests for object file building, and library builds
// and linking. This will require a rework to support multi-file
// tests.
.output_mode = case.output_mode,
// TODO: support testing optimizations
.optimize_mode = .Debug,
.emit_bin = emit_bin,
.root_pkg = &root_pkg,
.keep_source_files_loaded = true,
.object_format = ofmt,
.is_native_os = case.target.isNativeOs(),
});
defer comp.destroy();
for (case.files.items) |file| {
try tmp.dir.writeFile(file.path, file.src);
}
for (case.updates.items) |update, update_index| {
var update_node = root_node.start("update", 3);
update_node.activate();
defer update_node.end();
var sync_node = update_node.start("write", null);
sync_node.activate();
try tmp.dir.writeFile(tmp_src_path, update.src);
sync_node.end();
var module_node = update_node.start("parse/analysis/codegen", null);
module_node.activate();
try comp.makeBinFileWritable();
try comp.update();
module_node.end();
if (update.case != .Error) {
var all_errors = try comp.getAllErrorsAlloc();
defer all_errors.deinit(allocator);
if (all_errors.list.len != 0) {
std.debug.print("\nErrors occurred updating the compilation:\n================\n", .{});
for (all_errors.list) |err| {
std.debug.print(":{}:{}: error: {}\n================\n", .{ err.line + 1, err.column + 1, err.msg });
}
if (case.cbe) {
const C = comp.bin_file.cast(link.File.C).?;
std.debug.print("Generated C: \n===============\n{}\n\n===========\n\n", .{C.main.items});
}
std.debug.print("Test failed.\n", .{});
std.process.exit(1);
}
}
switch (update.case) {
.Transformation => |expected_output| {
if (case.cbe) {
// The C file is always closed after an update, because we don't support
// incremental updates
var file = try tmp.dir.openFile(bin_name, .{ .read = true });
defer file.close();
var out = file.reader().readAllAlloc(arena, 1024 * 1024) catch @panic("Unable to read C output!");
if (expected_output.len != out.len) {
std.debug.print("\nTransformed C length differs:\n================\nExpected:\n================\n{}\n================\nFound:\n================\n{}\n================\nTest failed.\n", .{ expected_output, out });
std.process.exit(1);
}
for (expected_output) |e, i| {
if (out[i] != e) {
std.debug.print("\nTransformed C differs:\n================\nExpected:\n================\n{}\n================\nFound:\n================\n{}\n================\nTest failed.\n", .{ expected_output, out });
std.process.exit(1);
}
}
} else {
update_node.estimated_total_items = 5;
var emit_node = update_node.start("emit", null);
emit_node.activate();
var new_zir_module = try zir.emit(allocator, comp.bin_file.options.module.?);
defer new_zir_module.deinit(allocator);
emit_node.end();
var write_node = update_node.start("write", null);
write_node.activate();
var out_zir = std.ArrayList(u8).init(allocator);
defer out_zir.deinit();
try new_zir_module.writeToStream(allocator, out_zir.outStream());
write_node.end();
var test_node = update_node.start("assert", null);
test_node.activate();
defer test_node.end();
if (expected_output.len != out_zir.items.len) {
std.debug.print("{}\nTransformed ZIR length differs:\n================\nExpected:\n================\n{}\n================\nFound:\n================\n{}\n================\nTest failed.\n", .{ case.name, expected_output, out_zir.items });
std.process.exit(1);
}
for (expected_output) |e, i| {
if (out_zir.items[i] != e) {
std.debug.print("{}\nTransformed ZIR differs:\n================\nExpected:\n================\n{}\n================\nFound:\n================\n{}\n================\nTest failed.\n", .{ case.name, expected_output, out_zir.items });
std.process.exit(1);
}
}
}
},
.Error => |e| {
var test_node = update_node.start("assert", null);
test_node.activate();
defer test_node.end();
var handled_errors = try arena.alloc(bool, e.len);
for (handled_errors) |*h| {
h.* = false;
}
var all_errors = try comp.getAllErrorsAlloc();
defer all_errors.deinit(allocator);
for (all_errors.list) |a| {
for (e) |ex, i| {
if (a.line == ex.line and a.column == ex.column and std.mem.eql(u8, ex.msg, a.msg)) {
handled_errors[i] = true;
break;
}
} else {
std.debug.print("{}\nUnexpected error:\n================\n:{}:{}: error: {}\n================\nTest failed.\n", .{ case.name, a.line + 1, a.column + 1, a.msg });
std.process.exit(1);
}
}
for (handled_errors) |h, i| {
if (!h) {
const er = e[i];
std.debug.print("{}\nDid not receive error:\n================\n{}:{}: {}\n================\nTest failed.\n", .{ case.name, er.line, er.column, er.msg });
std.process.exit(1);
}
}
},
.Execution => |expected_stdout| {
std.debug.assert(!case.cbe);
update_node.estimated_total_items = 4;
var exec_result = x: {
var exec_node = update_node.start("execute", null);
exec_node.activate();
defer exec_node.end();
var argv = std.ArrayList([]const u8).init(allocator);
defer argv.deinit();
const exe_path = try std.fmt.allocPrint(arena, "." ++ std.fs.path.sep_str ++ "{}", .{bin_name});
switch (case.target.getExternalExecutor()) {
.native => try argv.append(exe_path),
.unavailable => {
try self.runInterpreterIfAvailable(allocator, &exec_node, case, tmp.dir, bin_name);
return; // Pass test.
},
.qemu => |qemu_bin_name| if (enable_qemu) {
// TODO Ability for test cases to specify whether to link libc.
const need_cross_glibc = false; // target.isGnuLibC() and self.is_linking_libc;
const glibc_dir_arg = if (need_cross_glibc)
glibc_multi_install_dir orelse return // glibc dir not available; pass test
else
null;
try argv.append(qemu_bin_name);
if (glibc_dir_arg) |dir| {
const linux_triple = try target.linuxTriple(arena);
const full_dir = try std.fs.path.join(arena, &[_][]const u8{
dir,
linux_triple,
});
try argv.append("-L");
try argv.append(full_dir);
}
try argv.append(exe_path);
} else {
return; // QEMU not available; pass test.
},
.wine => |wine_bin_name| if (enable_wine) {
try argv.append(wine_bin_name);
try argv.append(exe_path);
} else {
return; // Wine not available; pass test.
},
.wasmtime => |wasmtime_bin_name| if (enable_wasmtime) {
try argv.append(wasmtime_bin_name);
try argv.append("--dir=.");
try argv.append(exe_path);
} else {
return; // wasmtime not available; pass test.
},
}
try comp.makeBinFileExecutable();
break :x try std.ChildProcess.exec(.{
.allocator = allocator,
.argv = argv.items,
.cwd_dir = tmp.dir,
});
};
var test_node = update_node.start("test", null);
test_node.activate();
defer test_node.end();
defer allocator.free(exec_result.stdout);
defer allocator.free(exec_result.stderr);
switch (exec_result.term) {
.Exited => |code| {
if (code != 0) {
std.debug.print("elf file exited with code {}\n", .{code});
return error.BinaryBadExitCode;
}
},
else => return error.BinaryCrashed,
}
if (!std.mem.eql(u8, expected_stdout, exec_result.stdout)) {
std.debug.panic(
"update index {}, mismatched stdout\n====Expected (len={}):====\n{}\n====Actual (len={}):====\n{}\n========\n",
.{ update_index, expected_stdout.len, expected_stdout, exec_result.stdout.len, exec_result.stdout },
);
}
},
}
}
}
fn runInterpreterIfAvailable(
self: *TestContext,
gpa: *Allocator,
node: *std.Progress.Node,
case: Case,
tmp_dir: std.fs.Dir,
bin_name: []const u8,
) !void {
const arch = case.target.cpu_arch orelse return;
switch (arch) {
.spu_2 => return self.runSpu2Interpreter(gpa, node, case, tmp_dir, bin_name),
else => return,
}
}
fn runSpu2Interpreter(
self: *TestContext,
gpa: *Allocator,
update_node: *std.Progress.Node,
case: Case,
tmp_dir: std.fs.Dir,
bin_name: []const u8,
) !void {
const spu = @import("codegen/spu-mk2.zig");
if (case.target.os_tag) |os| {
if (os != .freestanding) {
std.debug.panic("Only freestanding makes sense for SPU-II tests!", .{});
}
} else {
std.debug.panic("SPU_2 has no native OS, check the test!", .{});
}
var interpreter = spu.Interpreter(struct {
RAM: [0x10000]u8 = undefined,
pub fn read8(bus: @This(), addr: u16) u8 {
return bus.RAM[addr];
}
pub fn read16(bus: @This(), addr: u16) u16 {
return std.mem.readIntLittle(u16, bus.RAM[addr..][0..2]);
}
pub fn write8(bus: *@This(), addr: u16, val: u8) void {
bus.RAM[addr] = val;
}
pub fn write16(bus: *@This(), addr: u16, val: u16) void {
std.mem.writeIntLittle(u16, bus.RAM[addr..][0..2], val);
}
}){
.bus = .{},
};
{
var load_node = update_node.start("load", null);
load_node.activate();
defer load_node.end();
var file = try tmp_dir.openFile(bin_name, .{ .read = true });
defer file.close();
const header = try std.elf.readHeader(file);
var iterator = header.program_header_iterator(file);
var none_loaded = true;
while (try iterator.next()) |phdr| {
if (phdr.p_type != std.elf.PT_LOAD) {
std.debug.print("Encountered unexpected ELF program header: type {}\n", .{phdr.p_type});
std.process.exit(1);
}
if (phdr.p_paddr != phdr.p_vaddr) {
std.debug.print("Physical address does not match virtual address in ELF header!\n", .{});
std.process.exit(1);
}
if (phdr.p_filesz != phdr.p_memsz) {
std.debug.print("Physical size does not match virtual size in ELF header!\n", .{});
std.process.exit(1);
}
if ((try file.pread(interpreter.bus.RAM[phdr.p_paddr .. phdr.p_paddr + phdr.p_filesz], phdr.p_offset)) != phdr.p_filesz) {
std.debug.print("Read less than expected from ELF file!", .{});
std.process.exit(1);
}
std.log.scoped(.spu2_test).debug("Loaded 0x{x} bytes to 0x{x:0<4}\n", .{ phdr.p_filesz, phdr.p_paddr });
none_loaded = false;
}
if (none_loaded) {
std.debug.print("No data found in ELF file!\n", .{});
std.process.exit(1);
}
}
var exec_node = update_node.start("execute", null);
exec_node.activate();
defer exec_node.end();
var blocks: u16 = 1000;
const block_size = 1000;
while (!interpreter.undefined0) {
const pre_ip = interpreter.ip;
if (blocks > 0) {
blocks -= 1;
try interpreter.ExecuteBlock(block_size);
if (pre_ip == interpreter.ip) {
std.debug.print("Infinite loop detected in SPU II test!\n", .{});
std.process.exit(1);
}
}
}
}
}; | src/test.zig |
const std = @import("index.zig");
const assert = std.debug.assert;
const mem = std.mem; // For mem.Compare
const Color = enum(u1) {
Black,
Red,
};
const Red = Color.Red;
const Black = Color.Black;
const ReplaceError = error{NotEqual};
/// Insert this into your struct that you want to add to a red-black tree.
/// Do not use a pointer. Turn the *rb.Node results of the functions in rb
/// (after resolving optionals) to your structure using @fieldParentPtr(). Example:
///
/// const Number = struct {
/// node: rb.Node,
/// value: i32,
/// };
/// fn number(node: *rb.Node) Number {
/// return @fieldParentPtr(Number, "node", node);
/// }
pub const Node = struct {
left: ?*Node,
right: ?*Node,
/// parent | color
parent_and_color: usize,
pub fn next(constnode: *Node) ?*Node {
var node = constnode;
if (node.right) |right| {
var n = right;
while (n.left) |left|
n = left;
return n;
}
while (true) {
var parent = node.get_parent();
if (parent) |p| {
if (node != p.right)
return p;
node = p;
} else
return null;
}
}
pub fn prev(constnode: *Node) ?*Node {
var node = constnode;
if (node.left) |left| {
var n = left;
while (n.right) |right|
n = right;
return n;
}
while (true) {
var parent = node.get_parent();
if (parent) |p| {
if (node != p.left)
return p;
node = p;
} else
return null;
}
}
pub fn is_root(node: *Node) bool {
return node.get_parent() == null;
}
fn is_red(node: *Node) bool {
return node.get_color() == Red;
}
fn is_black(node: *Node) bool {
return node.get_color() == Black;
}
fn set_parent(node: *Node, parent: ?*Node) void {
node.parent_and_color = @ptrToInt(parent) | (node.parent_and_color & 1);
}
fn get_parent(node: *Node) ?*Node {
const mask: usize = 1;
comptime {
assert(@alignOf(*Node) >= 2);
}
return @intToPtr(*Node, node.parent_and_color & ~mask);
}
fn set_color(node: *Node, color: Color) void {
const mask: usize = 1;
node.parent_and_color = (node.parent_and_color & ~mask) | @enumToInt(color);
}
fn get_color(node: *Node) Color {
return @intToEnum(Color, @intCast(u1, node.parent_and_color & 1));
}
fn set_child(node: *Node, child: ?*Node, is_left: bool) void {
if (is_left) {
node.left = child;
} else {
node.right = child;
}
}
fn get_first(nodeconst: *Node) *Node {
var node = nodeconst;
while (node.left) |left| {
node = left;
}
return node;
}
fn get_last(node: *Node) *Node {
while (node.right) |right| {
node = right;
}
return node;
}
};
pub const Tree = struct {
root: ?*Node,
compareFn: fn (*Node, *Node) mem.Compare,
/// If you have a need for a version that caches this, please file a bug.
pub fn first(tree: *Tree) ?*Node {
var node: *Node = tree.root orelse return null;
while (node.left) |left| {
node = left;
}
return node;
}
pub fn last(tree: *Tree) ?*Node {
var node: *Node = tree.root orelse return null;
while (node.right) |right| {
node = right;
}
return node;
}
/// Duplicate keys are not allowed. The item with the same key already in the
/// tree will be returned, and the item will not be inserted.
pub fn insert(tree: *Tree, node_const: *Node) ?*Node {
var node = node_const;
var maybe_key: ?*Node = undefined;
var maybe_parent: ?*Node = undefined;
var is_left: bool = undefined;
maybe_key = do_lookup(node, tree, &maybe_parent, &is_left);
if (maybe_key) |key| {
return key;
}
node.left = null;
node.right = null;
node.set_color(Red);
node.set_parent(maybe_parent);
if (maybe_parent) |parent| {
parent.set_child(node, is_left);
} else {
tree.root = node;
}
while (node.get_parent()) |*parent| {
if (parent.*.is_black())
break;
// the root is always black
var grandpa = parent.*.get_parent() orelse unreachable;
if (parent.* == grandpa.left) {
var maybe_uncle = grandpa.right;
if (maybe_uncle) |uncle| {
if (uncle.is_black())
break;
parent.*.set_color(Black);
uncle.set_color(Black);
grandpa.set_color(Red);
node = grandpa;
} else {
if (node == parent.*.right) {
rotate_left(parent.*, tree);
node = parent.*;
parent.* = node.get_parent().?; // Just rotated
}
parent.*.set_color(Black);
grandpa.set_color(Red);
rotate_right(grandpa, tree);
}
} else {
var maybe_uncle = grandpa.left;
if (maybe_uncle) |uncle| {
if (uncle.is_black())
break;
parent.*.set_color(Black);
uncle.set_color(Black);
grandpa.set_color(Red);
node = grandpa;
} else {
if (node == parent.*.left) {
rotate_right(parent.*, tree);
node = parent.*;
parent.* = node.get_parent().?; // Just rotated
}
parent.*.set_color(Black);
grandpa.set_color(Red);
rotate_left(grandpa, tree);
}
}
}
// This was an insert, there is at least one node.
tree.root.?.set_color(Black);
return null;
}
pub fn lookup(tree: *Tree, key: *Node) ?*Node {
var parent: *Node = undefined;
var is_left: bool = undefined;
return do_lookup(key, tree, &parent, &is_left);
}
pub fn remove(tree: *Tree, nodeconst: *Node) void {
var node = nodeconst;
// as this has the same value as node, it is unsafe to access node after newnode
var newnode: ?*Node = nodeconst;
var maybe_parent: ?*Node = node.get_parent();
var color: Color = undefined;
var next: *Node = undefined;
// This clause is to avoid optionals
if (node.left == null and node.right == null) {
if (maybe_parent) |parent| {
parent.set_child(null, parent.left == node);
} else
tree.root = null;
color = node.get_color();
newnode = null;
} else {
if (node.left == null) {
next = node.right.?; // Not both null as per above
} else if (node.right == null) {
next = node.left.?; // Not both null as per above
} else
next = node.right.?.get_first(); // Just checked for null above
if (maybe_parent) |parent| {
parent.set_child(next, parent.left == node);
} else
tree.root = next;
if (node.left != null and node.right != null) {
const left = node.left.?;
const right = node.right.?;
color = next.get_color();
next.set_color(node.get_color());
next.left = left;
left.set_parent(next);
if (next != right) {
var parent = next.get_parent().?; // Was traversed via child node (right/left)
next.set_parent(node.get_parent());
newnode = next.right;
parent.left = node;
next.right = right;
right.set_parent(next);
} else {
next.set_parent(maybe_parent);
maybe_parent = next;
newnode = next.right;
}
} else {
color = node.get_color();
newnode = next;
}
}
if (newnode) |n|
n.set_parent(maybe_parent);
if (color == Red)
return;
if (newnode) |n| {
n.set_color(Black);
return;
}
while (node == tree.root) {
// If not root, there must be parent
var parent = maybe_parent.?;
if (node == parent.left) {
var sibling = parent.right.?; // Same number of black nodes.
if (sibling.is_red()) {
sibling.set_color(Black);
parent.set_color(Red);
rotate_left(parent, tree);
sibling = parent.right.?; // Just rotated
}
if ((if (sibling.left) |n| n.is_black() else true) and
(if (sibling.right) |n| n.is_black() else true))
{
sibling.set_color(Red);
node = parent;
maybe_parent = parent.get_parent();
continue;
}
if (if (sibling.right) |n| n.is_black() else true) {
sibling.left.?.set_color(Black); // Same number of black nodes.
sibling.set_color(Red);
rotate_right(sibling, tree);
sibling = parent.right.?; // Just rotated
}
sibling.set_color(parent.get_color());
parent.set_color(Black);
sibling.right.?.set_color(Black); // Same number of black nodes.
rotate_left(parent, tree);
newnode = tree.root;
break;
} else {
var sibling = parent.left.?; // Same number of black nodes.
if (sibling.is_red()) {
sibling.set_color(Black);
parent.set_color(Red);
rotate_right(parent, tree);
sibling = parent.left.?; // Just rotated
}
if ((if (sibling.left) |n| n.is_black() else true) and
(if (sibling.right) |n| n.is_black() else true))
{
sibling.set_color(Red);
node = parent;
maybe_parent = parent.get_parent();
continue;
}
if (if (sibling.left) |n| n.is_black() else true) {
sibling.right.?.set_color(Black); // Same number of black nodes
sibling.set_color(Red);
rotate_left(sibling, tree);
sibling = parent.left.?; // Just rotated
}
sibling.set_color(parent.get_color());
parent.set_color(Black);
sibling.left.?.set_color(Black); // Same number of black nodes
rotate_right(parent, tree);
newnode = tree.root;
break;
}
if (node.is_red())
break;
}
if (newnode) |n|
n.set_color(Black);
}
/// This is a shortcut to avoid removing and re-inserting an item with the same key.
pub fn replace(tree: *Tree, old: *Node, newconst: *Node) !void {
var new = newconst;
// I assume this can get optimized out if the caller already knows.
if (tree.compareFn(old, new) != mem.Compare.Equal) return ReplaceError.NotEqual;
if (old.get_parent()) |parent| {
parent.set_child(new, parent.left == old);
} else
tree.root = new;
if (old.left) |left|
left.set_parent(new);
if (old.right) |right|
right.set_parent(new);
new.* = old.*;
}
pub fn init(tree: *Tree, f: fn (*Node, *Node) mem.Compare) void {
tree.root = null;
tree.compareFn = f;
}
};
fn rotate_left(node: *Node, tree: *Tree) void {
var p: *Node = node;
var q: *Node = node.right orelse unreachable;
var parent: *Node = undefined;
if (!p.is_root()) {
parent = p.get_parent().?;
if (parent.left == p) {
parent.left = q;
} else {
parent.right = q;
}
q.set_parent(parent);
} else {
tree.root = q;
q.set_parent(null);
}
p.set_parent(q);
p.right = q.left;
if (p.right) |right| {
right.set_parent(p);
}
q.left = p;
}
fn rotate_right(node: *Node, tree: *Tree) void {
var p: *Node = node;
var q: *Node = node.left orelse unreachable;
var parent: *Node = undefined;
if (!p.is_root()) {
parent = p.get_parent().?;
if (parent.left == p) {
parent.left = q;
} else {
parent.right = q;
}
q.set_parent(parent);
} else {
tree.root = q;
q.set_parent(null);
}
p.set_parent(q);
p.left = q.right;
if (p.left) |left| {
left.set_parent(p);
}
q.right = p;
}
fn do_lookup(key: *Node, tree: *Tree, pparent: *?*Node, is_left: *bool) ?*Node {
var maybe_node: ?*Node = tree.root;
pparent.* = null;
is_left.* = false;
while (maybe_node) |node| {
var res: mem.Compare = tree.compareFn(node, key);
if (res == mem.Compare.Equal) {
return node;
}
pparent.* = node;
if (res == mem.Compare.GreaterThan) {
is_left.* = true;
maybe_node = node.left;
} else if (res == mem.Compare.LessThan) {
is_left.* = false;
maybe_node = node.right;
} else {
unreachable;
}
}
return null;
}
const testNumber = struct {
node: Node,
value: usize,
};
fn testGetNumber(node: *Node) *testNumber {
return @fieldParentPtr(testNumber, "node", node);
}
fn testCompare(l: *Node, r: *Node) mem.Compare {
var left = testGetNumber(l);
var right = testGetNumber(r);
if (left.value < right.value) {
return mem.Compare.LessThan;
} else if (left.value == right.value) {
return mem.Compare.Equal;
} else if (left.value > right.value) {
return mem.Compare.GreaterThan;
}
unreachable;
}
test "rb" {
var tree: Tree = undefined;
var ns: [10]testNumber = undefined;
ns[0].value = 42;
ns[1].value = 41;
ns[2].value = 40;
ns[3].value = 39;
ns[4].value = 38;
ns[5].value = 39;
ns[6].value = 3453;
ns[7].value = 32345;
ns[8].value = 392345;
ns[9].value = 4;
var dup: testNumber = undefined;
dup.value = 32345;
tree.init(testCompare);
_ = tree.insert(&ns[1].node);
_ = tree.insert(&ns[2].node);
_ = tree.insert(&ns[3].node);
_ = tree.insert(&ns[4].node);
_ = tree.insert(&ns[5].node);
_ = tree.insert(&ns[6].node);
_ = tree.insert(&ns[7].node);
_ = tree.insert(&ns[8].node);
_ = tree.insert(&ns[9].node);
tree.remove(&ns[3].node);
assert(tree.insert(&dup.node) == &ns[7].node);
try tree.replace(&ns[7].node, &dup.node);
var num: *testNumber = undefined;
num = testGetNumber(tree.first().?);
while (num.node.next() != null) {
assert(testGetNumber(num.node.next().?).value > num.value);
num = testGetNumber(num.node.next().?);
}
} | std/rb.zig |
const std = @import("std");
const fmt = std.fmt;
/// Group operations over Edwards25519.
pub const Edwards25519 = struct {
/// The underlying prime field.
pub const Fe = @import("field.zig").Fe;
/// Field arithmetic mod the order of the main subgroup.
pub const scalar = @import("scalar.zig");
x: Fe,
y: Fe,
z: Fe,
t: Fe,
is_base: bool = false,
/// Decode an Edwards25519 point from its compressed (Y+sign) coordinates.
pub fn fromBytes(s: [32]u8) !Edwards25519 {
const z = Fe.one;
const y = Fe.fromBytes(s);
var u = y.sq();
var v = u.mul(Fe.edwards25519d);
u = u.sub(z);
v = v.add(z);
const v3 = v.sq().mul(v);
var x = v3.sq().mul(v).mul(u).pow2523().mul(v3).mul(u);
const vxx = x.sq().mul(v);
const has_m_root = vxx.sub(u).isZero();
const has_p_root = vxx.add(u).isZero();
if ((@boolToInt(has_m_root) | @boolToInt(has_p_root)) == 0) { // best-effort to avoid two conditional branches
return error.InvalidEncoding;
}
x.cMov(x.mul(Fe.sqrtm1), 1 - @boolToInt(has_m_root));
x.cMov(x.neg(), @boolToInt(x.isNegative()) ^ (s[31] >> 7));
const t = x.mul(y);
return Edwards25519{ .x = x, .y = y, .z = z, .t = t };
}
/// Encode an Edwards25519 point.
pub fn toBytes(p: Edwards25519) [32]u8 {
const zi = p.z.invert();
var s = p.y.mul(zi).toBytes();
s[31] ^= @as(u8, @boolToInt(p.x.mul(zi).isNegative())) << 7;
return s;
}
/// Check that the encoding of a point is canonical.
pub fn rejectNonCanonical(s: [32]u8) !void {
return Fe.rejectNonCanonical(s, true);
}
/// The edwards25519 base point.
pub const basePoint = Edwards25519{
.x = Fe{ .limbs = .{ 3990542415680775, 3398198340507945, 4322667446711068, 2814063955482877, 2839572215813860 } },
.y = Fe{ .limbs = .{ 1801439850948184, 1351079888211148, 450359962737049, 900719925474099, 1801439850948198 } },
.z = Fe.one,
.t = Fe{ .limbs = .{ 1841354044333475, 16398895984059, 755974180946558, 900171276175154, 1821297809914039 } },
.is_base = true,
};
const identityElement = Edwards25519{ .x = Fe.zero, .y = Fe.one, .z = Fe.one, .t = Fe.zero };
/// Reject the neutral element.
pub fn rejectIdentity(p: Edwards25519) !void {
if (p.x.isZero()) {
return error.IdentityElement;
}
}
/// Flip the sign of the X coordinate.
pub inline fn neg(p: Edwards25519) Edwards25519 {
return .{ .x = p.x.neg(), .y = p.y, .z = p.z, .t = p.t.neg() };
}
/// Double an Edwards25519 point.
pub fn dbl(p: Edwards25519) Edwards25519 {
const t0 = p.x.add(p.y).sq();
var x = p.x.sq();
var z = p.y.sq();
const y = z.add(x);
z = z.sub(x);
x = t0.sub(y);
const t = p.z.sq2().sub(z);
return .{
.x = x.mul(t),
.y = y.mul(z),
.z = z.mul(t),
.t = x.mul(y),
};
}
/// Add two Edwards25519 points.
pub fn add(p: Edwards25519, q: Edwards25519) Edwards25519 {
const a = p.y.sub(p.x).mul(q.y.sub(q.x));
const b = p.x.add(p.y).mul(q.x.add(q.y));
const c = p.t.mul(q.t).mul(Fe.edwards25519d2);
var d = p.z.mul(q.z);
d = d.add(d);
const x = b.sub(a);
const y = b.add(a);
const z = d.add(c);
const t = d.sub(c);
return .{
.x = x.mul(t),
.y = y.mul(z),
.z = z.mul(t),
.t = x.mul(y),
};
}
inline fn cMov(p: *Edwards25519, a: Edwards25519, c: u64) void {
p.x.cMov(a.x, c);
p.y.cMov(a.y, c);
p.z.cMov(a.z, c);
p.t.cMov(a.t, c);
}
inline fn pcSelect(pc: [16]Edwards25519, b: u8) Edwards25519 {
var t = Edwards25519.identityElement;
comptime var i: u8 = 0;
inline while (i < 16) : (i += 1) {
t.cMov(pc[i], ((@as(usize, b ^ i) -% 1) >> 8) & 1);
}
return t;
}
fn pcMul(pc: [16]Edwards25519, s: [32]u8) !Edwards25519 {
var q = Edwards25519.identityElement;
var pos: usize = 252;
while (true) : (pos -= 4) {
q = q.dbl().dbl().dbl().dbl();
const bit = (s[pos >> 3] >> @truncate(u3, pos)) & 0xf;
q = q.add(pcSelect(pc, bit));
if (pos == 0) break;
}
try q.rejectIdentity();
return q;
}
fn precompute(p: Edwards25519) [16]Edwards25519 {
var pc: [16]Edwards25519 = undefined;
pc[0] = Edwards25519.identityElement;
pc[1] = p;
var i: usize = 2;
while (i < 16) : (i += 1) {
pc[i] = pc[i - 1].add(p);
}
return pc;
}
/// Multiply an Edwards25519 point by a scalar without clamping it.
/// Return error.WeakPublicKey if the resulting point is
/// the identity element.
pub fn mul(p: Edwards25519, s: [32]u8) !Edwards25519 {
var pc: [16]Edwards25519 = undefined;
if (p.is_base) {
@setEvalBranchQuota(10000);
pc = comptime precompute(Edwards25519.basePoint);
} else {
pc = precompute(p);
pc[4].rejectIdentity() catch |_| return error.WeakPublicKey;
}
return pcMul(pc, s);
}
/// Multiply an Edwards25519 point by a scalar after "clamping" it.
/// Clamping forces the scalar to be a multiple of the cofactor in
/// order to prevent small subgroups attacks.
/// This is strongly recommended for DH operations.
/// Return error.WeakPublicKey if the resulting point is
/// the identity element.
pub fn clampedMul(p: Edwards25519, s: [32]u8) !Edwards25519 {
var t: [32]u8 = s;
scalar.clamp(&t);
return mul(p, t);
}
};
test "edwards25519 packing/unpacking" {
const s = [_]u8{170} ++ [_]u8{0} ** 31;
var b = Edwards25519.basePoint;
const pk = try b.mul(s);
var buf: [128]u8 = undefined;
std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{pk.toBytes()}), "074BC7E0FCBD587FDBC0969444245FADC562809C8F6E97E949AF62484B5B81A6");
const small_order_ss: [7][32]u8 = .{
.{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 0 (order 4)
},
.{
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 1 (order 1)
},
.{
0x26, 0xe8, 0x95, 0x8f, 0xc2, 0xb2, 0x27, 0xb0, 0x45, 0xc3, 0xf4, 0x89, 0xf2, 0xef, 0x98, 0xf0, 0xd5, 0xdf, 0xac, 0x05, 0xd3, 0xc6, 0x33, 0x39, 0xb1, 0x38, 0x02, 0x88, 0x6d, 0x53, 0xfc, 0x05, // 270738550114484064931822528722565878893680426757531351946374360975030340202(order 8)
},
.{
0xc7, 0x17, 0x6a, 0x70, 0x3d, 0x4d, 0xd8, 0x4f, 0xba, 0x3c, 0x0b, 0x76, 0x0d, 0x10, 0x67, 0x0f, 0x2a, 0x20, 0x53, 0xfa, 0x2c, 0x39, 0xcc, 0xc6, 0x4e, 0xc7, 0xfd, 0x77, 0x92, 0xac, 0x03, 0x7a, // 55188659117513257062467267217118295137698188065244968500265048394206261417927 (order 8)
},
.{
0xec, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, // p-1 (order 2)
},
.{
0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, // p (=0, order 4)
},
.{
0xee, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, // p+1 (=1, order 1)
},
};
for (small_order_ss) |small_order_s| {
const small_p = try Edwards25519.fromBytes(small_order_s);
std.testing.expectError(error.WeakPublicKey, small_p.mul(s));
}
} | lib/std/crypto/25519/edwards25519.zig |
const std = @import("std");
const Type = @import("type.zig").Type;
const Value = @import("value.zig").Value;
const Module = @import("Module.zig");
const Allocator = std.mem.Allocator;
const TypedValue = @This();
const Target = std.Target;
ty: Type,
val: Value,
/// Memory management for TypedValue. The main purpose of this type
/// is to be small and have a deinit() function to free associated resources.
pub const Managed = struct {
/// If the tag value is less than Tag.no_payload_count, then no pointer
/// dereference is needed.
typed_value: TypedValue,
/// If this is `null` then there is no memory management needed.
arena: ?*std.heap.ArenaAllocator.State = null,
pub fn deinit(self: *Managed, allocator: Allocator) void {
if (self.arena) |a| a.promote(allocator).deinit();
self.* = undefined;
}
};
/// Assumes arena allocation. Does a recursive copy.
pub fn copy(self: TypedValue, arena: Allocator) error{OutOfMemory}!TypedValue {
return TypedValue{
.ty = try self.ty.copy(arena),
.val = try self.val.copy(arena),
};
}
pub fn eql(a: TypedValue, b: TypedValue, mod: *Module) bool {
if (!a.ty.eql(b.ty, mod)) return false;
return a.val.eql(b.val, a.ty, mod);
}
pub fn hash(tv: TypedValue, hasher: *std.hash.Wyhash, mod: *Module) void {
return tv.val.hash(tv.ty, hasher, mod);
}
pub fn enumToInt(tv: TypedValue, buffer: *Value.Payload.U64) Value {
return tv.val.enumToInt(tv.ty, buffer);
}
const max_aggregate_items = 100;
const FormatContext = struct {
tv: TypedValue,
mod: *Module,
};
pub fn format(
ctx: FormatContext,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = options;
comptime std.debug.assert(fmt.len == 0);
return ctx.tv.print(writer, 3, ctx.mod);
}
/// Prints the Value according to the Type, not according to the Value Tag.
pub fn print(
tv: TypedValue,
writer: anytype,
level: u8,
mod: *Module,
) @TypeOf(writer).Error!void {
const target = mod.getTarget();
var val = tv.val;
var ty = tv.ty;
while (true) switch (val.tag()) {
.u1_type => return writer.writeAll("u1"),
.u8_type => return writer.writeAll("u8"),
.i8_type => return writer.writeAll("i8"),
.u16_type => return writer.writeAll("u16"),
.i16_type => return writer.writeAll("i16"),
.u32_type => return writer.writeAll("u32"),
.i32_type => return writer.writeAll("i32"),
.u64_type => return writer.writeAll("u64"),
.i64_type => return writer.writeAll("i64"),
.u128_type => return writer.writeAll("u128"),
.i128_type => return writer.writeAll("i128"),
.isize_type => return writer.writeAll("isize"),
.usize_type => return writer.writeAll("usize"),
.c_short_type => return writer.writeAll("c_short"),
.c_ushort_type => return writer.writeAll("c_ushort"),
.c_int_type => return writer.writeAll("c_int"),
.c_uint_type => return writer.writeAll("c_uint"),
.c_long_type => return writer.writeAll("c_long"),
.c_ulong_type => return writer.writeAll("c_ulong"),
.c_longlong_type => return writer.writeAll("c_longlong"),
.c_ulonglong_type => return writer.writeAll("c_ulonglong"),
.c_longdouble_type => return writer.writeAll("c_longdouble"),
.f16_type => return writer.writeAll("f16"),
.f32_type => return writer.writeAll("f32"),
.f64_type => return writer.writeAll("f64"),
.f80_type => return writer.writeAll("f80"),
.f128_type => return writer.writeAll("f128"),
.anyopaque_type => return writer.writeAll("anyopaque"),
.bool_type => return writer.writeAll("bool"),
.void_type => return writer.writeAll("void"),
.type_type => return writer.writeAll("type"),
.anyerror_type => return writer.writeAll("anyerror"),
.comptime_int_type => return writer.writeAll("comptime_int"),
.comptime_float_type => return writer.writeAll("comptime_float"),
.noreturn_type => return writer.writeAll("noreturn"),
.null_type => return writer.writeAll("@Type(.Null)"),
.undefined_type => return writer.writeAll("@Type(.Undefined)"),
.fn_noreturn_no_args_type => return writer.writeAll("fn() noreturn"),
.fn_void_no_args_type => return writer.writeAll("fn() void"),
.fn_naked_noreturn_no_args_type => return writer.writeAll("fn() callconv(.Naked) noreturn"),
.fn_ccc_void_no_args_type => return writer.writeAll("fn() callconv(.C) void"),
.single_const_pointer_to_comptime_int_type => return writer.writeAll("*const comptime_int"),
.anyframe_type => return writer.writeAll("anyframe"),
.const_slice_u8_type => return writer.writeAll("[]const u8"),
.const_slice_u8_sentinel_0_type => return writer.writeAll("[:0]const u8"),
.anyerror_void_error_union_type => return writer.writeAll("anyerror!void"),
.enum_literal_type => return writer.writeAll("@Type(.EnumLiteral)"),
.manyptr_u8_type => return writer.writeAll("[*]u8"),
.manyptr_const_u8_type => return writer.writeAll("[*]const u8"),
.manyptr_const_u8_sentinel_0_type => return writer.writeAll("[*:0]const u8"),
.atomic_order_type => return writer.writeAll("std.builtin.AtomicOrder"),
.atomic_rmw_op_type => return writer.writeAll("std.builtin.AtomicRmwOp"),
.calling_convention_type => return writer.writeAll("std.builtin.CallingConvention"),
.address_space_type => return writer.writeAll("std.builtin.AddressSpace"),
.float_mode_type => return writer.writeAll("std.builtin.FloatMode"),
.reduce_op_type => return writer.writeAll("std.builtin.ReduceOp"),
.call_options_type => return writer.writeAll("std.builtin.CallOptions"),
.prefetch_options_type => return writer.writeAll("std.builtin.PrefetchOptions"),
.export_options_type => return writer.writeAll("std.builtin.ExportOptions"),
.extern_options_type => return writer.writeAll("std.builtin.ExternOptions"),
.type_info_type => return writer.writeAll("std.builtin.Type"),
.empty_struct_value => return writer.writeAll(".{}"),
.aggregate => {
if (level == 0) {
return writer.writeAll(".{ ... }");
}
const vals = val.castTag(.aggregate).?.data;
if (ty.zigTypeTag() == .Struct) {
try writer.writeAll(".{ ");
const struct_fields = ty.structFields();
const len = struct_fields.count();
const max_len = std.math.min(len, max_aggregate_items);
const field_names = struct_fields.keys();
const fields = struct_fields.values();
var i: u32 = 0;
while (i < max_len) : (i += 1) {
if (i != 0) try writer.writeAll(", ");
try writer.print(".{s} = ", .{field_names[i]});
try print(.{
.ty = fields[i].ty,
.val = vals[i],
}, writer, level - 1, mod);
}
if (len > max_aggregate_items) {
try writer.writeAll(", ...");
}
return writer.writeAll(" }");
} else {
try writer.writeAll(".{ ");
const elem_ty = ty.elemType2();
const len = ty.arrayLen();
const max_len = std.math.min(len, max_aggregate_items);
var i: u32 = 0;
while (i < max_len) : (i += 1) {
if (i != 0) try writer.writeAll(", ");
try print(.{
.ty = elem_ty,
.val = vals[i],
}, writer, level - 1, mod);
}
if (len > max_aggregate_items) {
try writer.writeAll(", ...");
}
return writer.writeAll(" }");
}
},
.@"union" => {
if (level == 0) {
return writer.writeAll(".{ ... }");
}
const union_val = val.castTag(.@"union").?.data;
try writer.writeAll(".{ ");
try print(.{
.ty = ty.unionTagType().?,
.val = union_val.tag,
}, writer, level - 1, mod);
try writer.writeAll(" = ");
try print(.{
.ty = ty.unionFieldType(union_val.tag, mod),
.val = union_val.val,
}, writer, level - 1, mod);
return writer.writeAll(" }");
},
.null_value => return writer.writeAll("null"),
.undef => return writer.writeAll("undefined"),
.zero => return writer.writeAll("0"),
.one => return writer.writeAll("1"),
.void_value => return writer.writeAll("{}"),
.unreachable_value => return writer.writeAll("unreachable"),
.the_only_possible_value => {
val = ty.onePossibleValue().?;
},
.bool_true => return writer.writeAll("true"),
.bool_false => return writer.writeAll("false"),
.ty => return val.castTag(.ty).?.data.print(writer, mod),
.int_type => {
const int_type = val.castTag(.int_type).?.data;
return writer.print("{s}{d}", .{
if (int_type.signed) "s" else "u",
int_type.bits,
});
},
.int_u64 => return std.fmt.formatIntValue(val.castTag(.int_u64).?.data, "", .{}, writer),
.int_i64 => return std.fmt.formatIntValue(val.castTag(.int_i64).?.data, "", .{}, writer),
.int_big_positive => return writer.print("{}", .{val.castTag(.int_big_positive).?.asBigInt()}),
.int_big_negative => return writer.print("{}", .{val.castTag(.int_big_negative).?.asBigInt()}),
.lazy_align => {
const sub_ty = val.castTag(.lazy_align).?.data;
const x = sub_ty.abiAlignment(target);
return writer.print("{d}", .{x});
},
.lazy_size => {
const sub_ty = val.castTag(.lazy_size).?.data;
const x = sub_ty.abiSize(target);
return writer.print("{d}", .{x});
},
.function => return writer.print("(function '{s}')", .{
mod.declPtr(val.castTag(.function).?.data.owner_decl).name,
}),
.extern_fn => return writer.writeAll("(extern function)"),
.variable => return writer.writeAll("(variable)"),
.decl_ref_mut => {
const decl_index = val.castTag(.decl_ref_mut).?.data.decl_index;
const decl = mod.declPtr(decl_index);
if (level == 0) {
return writer.print("(decl ref mut '{s}')", .{decl.name});
}
return print(.{
.ty = decl.ty,
.val = decl.val,
}, writer, level - 1, mod);
},
.decl_ref => {
const decl_index = val.castTag(.decl_ref).?.data;
const decl = mod.declPtr(decl_index);
if (level == 0) {
return writer.print("(decl ref '{s}')", .{decl.name});
}
return print(.{
.ty = decl.ty,
.val = decl.val,
}, writer, level - 1, mod);
},
.elem_ptr => {
const elem_ptr = val.castTag(.elem_ptr).?.data;
try writer.writeAll("&");
try print(.{
.ty = elem_ptr.elem_ty,
.val = elem_ptr.array_ptr,
}, writer, level - 1, mod);
return writer.print("[{}]", .{elem_ptr.index});
},
.field_ptr => {
const field_ptr = val.castTag(.field_ptr).?.data;
try writer.writeAll("&");
try print(.{
.ty = field_ptr.container_ty,
.val = field_ptr.container_ptr,
}, writer, level - 1, mod);
if (field_ptr.container_ty.zigTypeTag() == .Struct) {
const field_name = field_ptr.container_ty.structFields().keys()[field_ptr.field_index];
return writer.print(".{s}", .{field_name});
} else if (field_ptr.container_ty.zigTypeTag() == .Union) {
const field_name = field_ptr.container_ty.unionFields().keys()[field_ptr.field_index];
return writer.print(".{s}", .{field_name});
} else unreachable;
},
.empty_array => return writer.writeAll(".{}"),
.enum_literal => return writer.print(".{}", .{std.zig.fmtId(val.castTag(.enum_literal).?.data)}),
.enum_field_index => {
return writer.print(".{s}", .{ty.enumFieldName(val.castTag(.enum_field_index).?.data)});
},
.bytes => return writer.print("\"{}\"", .{std.zig.fmtEscapes(val.castTag(.bytes).?.data)}),
.repeated => {
if (level == 0) {
return writer.writeAll(".{ ... }");
}
var i: u32 = 0;
try writer.writeAll(".{ ");
const elem_tv = TypedValue{
.ty = ty.elemType2(),
.val = val.castTag(.repeated).?.data,
};
const len = ty.arrayLen();
const max_len = std.math.min(len, max_aggregate_items);
while (i < max_len) : (i += 1) {
if (i != 0) try writer.writeAll(", ");
try print(elem_tv, writer, level - 1, mod);
}
if (len > max_aggregate_items) {
try writer.writeAll(", ...");
}
return writer.writeAll(" }");
},
.empty_array_sentinel => {
if (level == 0) {
return writer.writeAll(".{ (sentinel) }");
}
try writer.writeAll(".{ ");
try print(.{
.ty = ty.elemType2(),
.val = ty.sentinel().?,
}, writer, level - 1, mod);
return writer.writeAll(" }");
},
.slice => {
const payload = val.castTag(.slice).?.data;
try writer.writeAll(".{ ");
const elem_ty = ty.elemType2();
const len = payload.len.toUnsignedInt(target);
const max_len = std.math.min(len, max_aggregate_items);
var i: u32 = 0;
while (i < max_len) : (i += 1) {
if (i != 0) try writer.writeAll(", ");
var buf: Value.ElemValueBuffer = undefined;
try print(.{
.ty = elem_ty,
.val = payload.ptr.elemValueBuffer(mod, i, &buf),
}, writer, level - 1, mod);
}
if (len > max_aggregate_items) {
try writer.writeAll(", ...");
}
return writer.writeAll(" }");
},
.float_16 => return writer.print("{}", .{val.castTag(.float_16).?.data}),
.float_32 => return writer.print("{}", .{val.castTag(.float_32).?.data}),
.float_64 => return writer.print("{}", .{val.castTag(.float_64).?.data}),
.float_80 => return writer.print("{}", .{val.castTag(.float_80).?.data}),
.float_128 => return writer.print("{}", .{val.castTag(.float_128).?.data}),
.@"error" => return writer.print("error.{s}", .{val.castTag(.@"error").?.data.name}),
.eu_payload => {
val = val.castTag(.eu_payload).?.data;
},
.opt_payload => {
val = val.castTag(.opt_payload).?.data;
},
.eu_payload_ptr => {
try writer.writeAll("&");
val = val.castTag(.eu_payload_ptr).?.data.container_ptr;
},
.opt_payload_ptr => {
try writer.writeAll("&");
val = val.castTag(.opt_payload_ptr).?.data.container_ptr;
},
// TODO these should not appear in this function
.inferred_alloc => return writer.writeAll("(inferred allocation value)"),
.inferred_alloc_comptime => return writer.writeAll("(inferred comptime allocation value)"),
.bound_fn => {
const bound_func = val.castTag(.bound_fn).?.data;
return writer.print("(bound_fn %{}(%{})", .{ bound_func.func_inst, bound_func.arg0_inst });
},
.generic_poison_type => return writer.writeAll("(generic poison type)"),
.generic_poison => return writer.writeAll("(generic poison)"),
};
} | src/TypedValue.zig |
const std = @import("std");
const App = @import("app");
const Engine = @import("../Engine.zig");
const structs = @import("../structs.zig");
const enums = @import("../enums.zig");
const js = struct {
extern fn machCanvasInit(width: u32, height: u32, selector_id: *u8) CanvasId;
extern fn machCanvasDeinit(canvas: CanvasId) void;
extern fn machCanvasSetTitle(canvas: CanvasId, title: [*]const u8, len: u32) void;
extern fn machCanvasSetSize(canvas: CanvasId, width: u32, height: u32) void;
extern fn machCanvasGetWindowWidth(canvas: CanvasId) u32;
extern fn machCanvasGetWindowHeight(canvas: CanvasId) u32;
extern fn machCanvasGetFramebufferWidth(canvas: CanvasId) u32;
extern fn machCanvasGetFramebufferHeight(canvas: CanvasId) u32;
extern fn machEmitCloseEvent() void;
extern fn machEventShift() i32;
extern fn machEventShiftFloat() f64;
extern fn machChangeShift() u32;
extern fn machPerfNow() f64;
extern fn machLog(str: [*]const u8, len: u32) void;
extern fn machLogWrite(str: [*]const u8, len: u32) void;
extern fn machLogFlush() void;
extern fn machPanic(str: [*]const u8, len: u32) void;
};
pub const CanvasId = u32;
pub const Platform = struct {
id: CanvasId,
selector_id: []const u8,
last_window_size: structs.Size,
last_framebuffer_size: structs.Size,
pub fn init(allocator: std.mem.Allocator, eng: *Engine) !Platform {
const options = eng.options;
var selector = [1]u8{0} ** 15;
const id = js.machCanvasInit(options.width, options.height, &selector[0]);
const title = std.mem.span(options.title);
js.machCanvasSetTitle(id, title.ptr, title.len);
return Platform{
.id = id,
.selector_id = try allocator.dupe(u8, selector[0 .. selector.len - @as(u32, if (selector[selector.len - 1] == 0) 1 else 0)]),
.last_window_size = .{
.width = js.machCanvasGetWindowWidth(id),
.height = js.machCanvasGetWindowHeight(id),
},
.last_framebuffer_size = .{
.width = js.machCanvasGetFramebufferWidth(id),
.height = js.machCanvasGetFramebufferHeight(id),
},
};
}
pub fn setOptions(platform: *Platform, options: structs.Options) !void {
// NOTE: size limits do not exists on wasm
js.machCanvasSetSize(platform.id, options.width, options.height);
const title = std.mem.span(options.title);
js.machCanvasSetTitle(platform.id, title.ptr, title.len);
}
pub fn setShouldClose(_: *Platform, value: bool) void {
if (value) js.machEmitCloseEvent();
}
pub fn getFramebufferSize(platform: *Platform) structs.Size {
return platform.last_framebuffer_size;
}
pub fn getWindowSize(platform: *Platform) structs.Size {
return platform.last_window_size;
}
fn pollChanges(platform: *Platform) void {
const change_type = js.machChangeShift();
switch (change_type) {
1 => {
const width = js.machChangeShift();
const height = js.machChangeShift();
const device_pixel_ratio = js.machChangeShift();
platform.last_window_size = .{
.width = @divFloor(width, device_pixel_ratio),
.height = @divFloor(height, device_pixel_ratio),
};
platform.last_framebuffer_size = .{
.width = width,
.height = height,
};
},
else => {},
}
}
pub fn pollEvent(_: *Platform) ?structs.Event {
const event_type = js.machEventShift();
return switch (event_type) {
1 => structs.Event{
.key_press = .{ .key = @intToEnum(enums.Key, js.machEventShift()) },
},
2 => structs.Event{
.key_release = .{ .key = @intToEnum(enums.Key, js.machEventShift()) },
},
3 => structs.Event{
.mouse_motion = .{
.x = @intToFloat(f64, js.machEventShift()),
.y = @intToFloat(f64, js.machEventShift()),
},
},
4 => structs.Event{
.mouse_press = .{
.button = toMachButton(js.machEventShift()),
},
},
5 => structs.Event{
.mouse_release = .{
.button = toMachButton(js.machEventShift()),
},
},
6 => structs.Event{
.mouse_scroll = .{
.xoffset = @floatCast(f32, sign(js.machEventShiftFloat())),
.yoffset = @floatCast(f32, sign(js.machEventShiftFloat())),
},
},
else => null,
};
}
inline fn sign(val: f64) f64 {
return switch (val) {
0.0 => 0.0,
else => -val,
};
}
fn toMachButton(button: i32) enums.MouseButton {
return switch (button) {
0 => .left,
1 => .middle,
2 => .right,
3 => .four,
4 => .five,
else => unreachable,
};
}
};
pub const BackingTimer = struct {
initial: f64 = undefined,
const WasmTimer = @This();
pub fn start() !WasmTimer {
return WasmTimer{ .initial = js.machPerfNow() };
}
pub fn read(timer: *WasmTimer) u64 {
return timeToNs(js.machPerfNow() - timer.initial);
}
pub fn reset(timer: *WasmTimer) void {
timer.initial = js.machPerfNow();
}
pub fn lap(timer: *WasmTimer) u64 {
const now = js.machPerfNow();
const initial = timer.initial;
timer.initial = now;
return timeToNs(now - initial);
}
fn timeToNs(t: f64) u64 {
return @floatToInt(u64, t) * 1000000;
}
};
const common = @import("common.zig");
comptime {
common.checkApplication(App);
}
var app: App = undefined;
var engine: Engine = undefined;
export fn wasmInit() void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
engine = Engine.init(allocator) catch unreachable;
app.init(&engine) catch {};
}
export fn wasmUpdate() void {
// Poll internal events, like resize
engine.internal.pollChanges();
engine.delta_time_ns = engine.timer.lapPrecise();
engine.delta_time = @intToFloat(f32, engine.delta_time_ns) / @intToFloat(f32, std.time.ns_per_s);
app.update(&engine) catch engine.setShouldClose(true);
}
export fn wasmDeinit() void {
app.deinit(&engine);
}
pub const log_level = .info;
const LogError = error{};
const LogWriter = std.io.Writer(void, LogError, writeLog);
fn writeLog(_: void, msg: []const u8) LogError!usize {
js.machLogWrite(msg.ptr, msg.len);
return msg.len;
}
pub fn log(
comptime message_level: std.log.Level,
comptime scope: @Type(.EnumLiteral),
comptime format: []const u8,
args: anytype,
) void {
const prefix = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): ";
const writer = LogWriter{ .context = {} };
writer.print(message_level.asText() ++ prefix ++ format ++ "\n", args) catch return;
js.machLogFlush();
}
pub fn panic(msg: []const u8, _: ?*std.builtin.StackTrace) noreturn {
js.machPanic(msg.ptr, msg.len);
unreachable;
} | src/platform/wasm.zig |
const std = @import("std");
const input = @import("input.zig");
pub fn run(stdout: anytype) anyerror!void {
{
var input_ = try input.readFile("inputs/day13");
defer input_.deinit();
var paper = Paper.init(0) catch unreachable;
const result = try part1(&input_, &paper);
try stdout.print("13a: {}\n", .{ result });
std.debug.assert(result == 781);
}
{
var input_ = try input.readFile("inputs/day13");
defer input_.deinit();
var paper = Paper.init(0) catch unreachable;
try part2(&input_, &paper);
try stdout.print("13b: ", .{});
try printPaper(paper.constSlice(), stdout);
try assertEqual(
\\###..####.###...##...##....##.###..###.
\\#..#.#....#..#.#..#.#..#....#.#..#.#..#
\\#..#.###..#..#.#....#.......#.#..#.###.
\\###..#....###..#....#.##....#.###..#..#
\\#....#....#.#..#..#.#..#.#..#.#....#..#
\\#....####.#..#..##...###..##..#....###.
,
paper.slice(),
);
}
}
const max_num_points = 1000;
const Paper = std.BoundedArray(Point, max_num_points);
const Point = struct {
y: usize,
x: usize,
};
fn part1(input_: anytype, paper: *Paper) !usize {
try parsePaper(input_, paper);
const folded_once = try step(input_, paper);
if (!folded_once) {
return error.InvalidInput;
}
return paper.len;
}
fn part2(input_: anytype, paper: *Paper) !void {
try parsePaper(input_, paper);
while (try step(input_, paper)) {}
std.sort.sort(Point, paper.slice(), {}, sortPoint);
}
fn printPaper(paper: []const Point, stdout: anytype) !void {
var y_max: usize = 0;
var x_max: usize = 0;
for (paper) |point| {
y_max = std.math.max(y_max, point.y);
x_max = std.math.max(x_max, point.x);
}
{
try stdout.print("\u{2554}\u{2550}", .{});
var x_i: usize = 0;
while (x_i <= x_max) : (x_i += 1) {
try stdout.print("\u{2550}\u{2550}", .{});
}
try stdout.print("\u{2550}\u{2557}\n", .{});
}
{
var next_point_i: usize = 0;
var y_i: usize = 0;
while (y_i <= y_max) : (y_i += 1) {
try stdout.print(" \u{2551} ", .{});
var x_i: usize = 0;
while (x_i <= x_max) : (x_i += 1) {
if (next_point_i < paper.len) {
const point = paper[next_point_i];
if (point.y == y_i and point.x == x_i) {
try stdout.print("##", .{});
next_point_i += 1;
}
else {
try stdout.print(" ", .{});
}
}
else {
try stdout.print(" ", .{});
}
}
try stdout.print(" \u{2551}\n", .{});
}
}
{
try stdout.print(" \u{255a}\u{2550}", .{});
var x_i: usize = 0;
while (x_i <= x_max) : (x_i += 1) {
try stdout.print("\u{2550}\u{2550}", .{});
}
try stdout.print("\u{2550}\u{255d}\n", .{});
}
}
fn assertEqual(
expected_paper_s: []const u8,
actual_paper: []const Point,
) !void {
var expected_paper = Paper.init(0) catch unreachable;
{
var y_i: usize = 0;
var lines = std.mem.split(u8, expected_paper_s, "\n");
while (lines.next()) |line| : (y_i += 1) {
for (line) |c, x_i| {
if (c == '#') {
try append(&expected_paper, .{ .y = y_i, .x = x_i });
}
}
}
}
std.debug.assert(expected_paper.len == actual_paper.len);
for (expected_paper.constSlice()) |expected_point, point_i| {
const actual_point = actual_paper[point_i];
std.debug.assert(expected_point.y == actual_point.y and expected_point.x == actual_point.x);
}
}
fn sortPoint(context: void, a: Point, b: Point) bool {
_ = context;
return switch (std.math.order(a.y, b.y)) {
.lt => true,
.eq => a.x < b.x,
.gt => false,
};
}
fn parsePaper(input_: anytype, paper: *Paper) !void {
while (try input_.next()) |line| {
if (line.len == 0) {
break;
}
var line_parts = std.mem.split(u8, line, ",");
const x_s = line_parts.next() orelse return error.InvalidInput;
const x = try std.fmt.parseInt(usize, x_s, 10);
const y_s = line_parts.next() orelse return error.InvalidInput;
const y = try std.fmt.parseInt(usize, y_s, 10);
try append(paper, .{ .y = y, .x = x });
}
}
fn append(paper: *Paper, new_point: Point) !void {
for (paper.constSlice()) |point| {
if (point.y == new_point.y and point.x == new_point.x) {
return;
}
}
try paper.append(new_point);
}
fn step(input_: anytype, paper: *Paper) !bool {
const FoldAxis = enum {
y,
x,
};
const line = (try input_.next()) orelse return false;
if (!std.mem.startsWith(u8, line, "fold along ")) {
return error.InvalidInput;
}
var fold_line_parts = std.mem.split(u8, line[("fold along ".len)..], "=");
const axis_s = fold_line_parts.next() orelse return error.InvalidInput;
const axis = std.meta.stringToEnum(FoldAxis, axis_s) orelse return error.InvalidInput;
const distance_s = fold_line_parts.next() orelse return error.InvalidInput;
const distance = try std.fmt.parseInt(usize, distance_s, 10);
var point_i: usize = 0;
while (point_i < paper.len) {
var point = paper.constSlice()[point_i];
const new_point = switch (axis) {
.y => if (point.y > distance) Point { .y = point.y - (point.y - distance) * 2, .x = point.x } else null,
.x => if (point.x > distance) Point { .y = point.y, .x = point.x - (point.x - distance) * 2 } else null,
};
if (new_point) |new_point_| {
_ = paper.swapRemove(point_i);
try append(paper, new_point_);
}
else {
point_i += 1;
}
}
return true;
}
test "day 13 example 1" {
const input_ =
\\6,10
\\0,14
\\9,10
\\0,3
\\10,4
\\4,11
\\6,0
\\6,12
\\4,1
\\0,13
\\10,12
\\3,4
\\3,0
\\8,4
\\1,10
\\2,14
\\8,10
\\9,0
\\
\\fold along y=7
\\fold along x=5
;
{
var paper = Paper.init(0) catch unreachable;
try std.testing.expectEqual(@as(usize, 17), try part1(&input.readString(input_), &paper));
}
{
var paper = Paper.init(0) catch unreachable;
try part2(&input.readString(input_), &paper);
try assertEqual(
\\#####
\\#...#
\\#...#
\\#...#
\\#####
\\.....
\\.....
,
paper.slice(),
);
}
} | src/day13.zig |
const std = @import("std");
const helper = @import("helper.zig");
const Allocator = std.mem.Allocator;
const HashMap = std.AutoHashMap;
const input = @embedFile("../inputs/day14.txt");
pub fn run(alloc: Allocator, stdout_: anytype) !void {
var polymer = try Polymer.init(alloc, input);
defer polymer.deinit();
var i: usize = 0;
while (i < 10) : (i += 1) {
try polymer.step();
}
const res1 = try polymer.getMostLeastDiff(alloc);
while (i < 40) : (i += 1) { // the 40 here is not a bug
try polymer.step();
}
const res2 = try polymer.getMostLeastDiff(alloc);
if (stdout_) |stdout| {
try stdout.print("Part 1: {}\n", .{res1});
try stdout.print("Part 2: {}\n", .{res2});
}
}
const Polymer = struct {
current: HashMap([2]u8, i64),
buffer: HashMap([2]u8, i64),
rules: HashMap([2]u8, u8),
last: u8,
const Self = @This();
pub fn init(alloc: Allocator, inp: []const u8) !Self {
var current = HashMap([2]u8, i64).init(alloc);
var rules = HashMap([2]u8, u8).init(alloc);
var lines = tokenize(u8, inp, "\r\n");
const fst = lines.next().?;
try Self.addInitial(fst, ¤t);
while (lines.next()) |line| {
const rule = Rule.parse(line);
try rules.put(rule.pattern, rule.char);
}
return Self{
.current = current,
.buffer = HashMap([2]u8, i64).init(alloc),
.rules = rules,
.last = fst[fst.len - 1],
};
}
pub fn step(self: *Self) !void {
self.buffer.clearRetainingCapacity();
var iter = self.current.iterator();
while (iter.next()) |entry| {
const key = entry.key_ptr.*;
const mid = self.rules.get(key).?;
const key1 = .{ key[0], mid };
const key2 = .{ mid, key[1] };
const keys: [2][2]u8 = .{ key1, key2 };
for (keys) |newkey| {
var newentry = try self.buffer.getOrPutValue(newkey, 0);
newentry.value_ptr.* += entry.value_ptr.*;
}
}
std.mem.swap(HashMap([2]u8, i64), &self.buffer, &self.current);
}
pub fn getMostLeastDiff(self: Self, alloc: Allocator) !i64 {
var count_map = HashMap(u8, i64).init(alloc);
defer count_map.deinit();
try count_map.put(self.last, 1);
var iter = self.current.iterator();
while (iter.next()) |entry| {
const val = entry.value_ptr.*;
// we're only considering the first char of each pair because
// they're overlapping and we don't want to count a character twice.
const ch = entry.key_ptr.*[0];
const newentry = try count_map.getOrPutValue(ch, 0);
newentry.value_ptr.* += val;
}
var min: i64 = math.maxInt(i64);
var max: i64 = math.minInt(i64);
var counts = count_map.valueIterator();
while (counts.next()) |cnt| {
min = math.min(min, cnt.*);
max = math.max(max, cnt.*);
}
return max - min;
}
pub fn deinit(self: *Self) void {
self.current.deinit();
self.buffer.deinit();
self.rules.deinit();
}
fn addInitial(line: []const u8, map: *HashMap([2]u8, i64)) !void {
var i: usize = 0;
while (i + 1 < line.len) : (i += 1) {
var entry = try map.getOrPutValue(.{ line[i], line[i + 1] }, 0);
entry.value_ptr.* += 1;
}
}
};
const Rule = struct {
pattern: [2]u8,
char: u8,
const Self = @This();
pub fn parse(line: []const u8) Self {
// 0123456
// AB -> C
return Self{
.pattern = .{ line[0], line[1] },
.char = line[6],
};
}
};
const eql = std.mem.eql;
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const count = std.mem.count;
const parseUnsigned = std.fmt.parseUnsigned;
const parseInt = std.fmt.parseInt;
const sort = std.sort.sort;
const math = std.math; | src/day14.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const wcwidth = @import("zig-wcwidth/src/main.zig").wcwidth;
const Style = @import("zig-ansi-term/src/style.zig").Style;
pub const Cell = struct {
ch: u21,
style: Style,
const Self = @This();
pub fn eql(self: Self, other: Self) bool {
return self.ch == other.ch and self.style.eql(other.style);
}
};
pub const CellBuffer = struct {
alloc: *Allocator,
width: usize,
height: usize,
cells: []Cell,
const Self = @This();
pub fn init(allocator: *Allocator, w: usize, h: usize) !Self {
return Self{
.alloc = allocator,
.width = w,
.height = h,
.cells = try allocator.alloc(Cell, w * h),
};
}
pub fn deinit(self: *Self) void {
self.alloc.free(self.cells);
}
pub fn resize(self: *Self, w: usize, h: usize) !void {
const old_width = self.width;
const old_height = self.height;
const old_buf = self.cells;
self.width = w;
self.height = h;
self.cells = try allocator.alloc(Cell, w * h);
const min_w = if (w < old_width) w else old_width;
const min_h = if (h < old_height) h else old_height;
var i: usize = 0;
while (i < min_h) : (i += 1) {
const src = i * old_width;
const dest = i * w;
std.mem.copy(u8, old_buf[src .. src + min_w], self.cells[dest .. dest + min_w]);
}
self.alloc.free(old_buf);
}
pub fn clear(self: *Self, style: Style) void {
for (self.cells) |*cell| {
cell.ch = ' ';
cell.style = style;
}
}
pub fn get(self: *Self, x: usize, y: usize) *Cell {
return &self.cells[y * self.width + x];
}
pub const Anchor = struct {
cell_buffer: *Self,
pos: usize,
const Error = error{InvalidUtf8};
pub fn write(context: *Anchor, bytes: []const u8) Error!usize {
const utf8_view = try std.unicode.Utf8View.init(bytes);
var iter = utf8_view.iterator();
while (iter.nextCodepoint()) |c| {
context.cell_buffer.cells[context.pos].ch = c;
context.pos += @intCast(usize, wcwidth(c));
}
return bytes.len;
}
pub fn move(self: *Anchor, x: usize, y: usize) void {
self.pos = y * self.cell_buffer.width + x;
}
pub fn writer(self: *Anchor) std.io.Writer(*Anchor, Anchor.Error, Anchor.write) {
return .{ .context = self };
}
};
pub fn anchor(self: *Self, x: usize, y: usize) Anchor {
return Anchor{
.cell_buffer = self,
.pos = y * self.width + x,
};
}
}; | src/cellbuffer.zig |
const std = @import("std");
const ArrayList = std.ArrayList;
const Allocator = std.mem.Allocator;
const BufferedWriter = std.io.BufferedWriter;
const File = std.fs.File;
const Fifo = std.fifo.LinearFifo(u8, .{ .Static = 512 });
const bufferedWriter = std.io.bufferedWriter;
const wcwidth = @import("zig-wcwidth/src/main.zig").wcwidth;
const updateStyle = @import("zig-ansi-term/src/format.zig").updateStyle;
const writeCursor = @import("zig-ansi-term/src/cursor.zig").setCursor;
pub const Style = @import("zig-ansi-term/src/style.zig").Style;
pub const Color = @import("zig-ansi-term/src/style.zig").Color;
pub const ColorRGB = @import("zig-ansi-term/src/style.zig").ColorRGB;
pub const FontStyle = @import("zig-ansi-term/src/style.zig").FontStyle;
const term = @import("term.zig");
const cellbuffer = @import("cellbuffer.zig");
pub const Cell = cellbuffer.Cell;
pub const CellBuffer = cellbuffer.CellBuffer;
const cursor = @import("cursor.zig");
pub const Pos = cursor.Pos;
pub const CursorState = cursor.CursorState;
pub const Cursor = cursor.Cursor;
const input = @import("input.zig");
pub const Event = input.Event;
pub const InputSettings = input.InputSettings;
const OutputMode = enum {
Normal,
Output256,
Output216,
Grayscale,
};
pub const Termbox = struct {
allocator: *Allocator,
orig_tios: std.os.termios,
inout: File,
winch_fds: [2]std.os.fd_t,
back_buffer: CellBuffer,
front_buffer: CellBuffer,
output_buffer: BufferedWriter(4096, File.Writer),
input_buffer: Fifo,
term: term.Term,
term_w: usize,
term_h: usize,
input_settings: InputSettings,
output_mode: OutputMode,
cursor: Cursor,
cursor_state: CursorState,
current_style: Style,
const Self = @This();
pub fn initFile(allocator: *Allocator, file: File) !Self {
var self = Self{
.allocator = allocator,
.orig_tios = try std.os.tcgetattr(file.handle),
.inout = file,
.winch_fds = try std.os.pipe(),
.back_buffer = undefined,
.front_buffer = undefined,
.output_buffer = bufferedWriter(file.writer()),
.input_buffer = Fifo.init(),
.term = try term.Term.initTerm(allocator),
.term_w = 0,
.term_h = 0,
.input_settings = InputSettings{},
.output_mode = OutputMode.Normal,
.cursor = Cursor.Hidden,
.cursor_state = CursorState{},
.current_style = Style{},
};
var tios = self.orig_tios;
const tcflag_t = std.os.tcflag_t;
tios.iflag &= ~(@intCast(tcflag_t, std.os.IGNBRK) | @intCast(tcflag_t, std.os.BRKINT) |
@intCast(tcflag_t, std.os.PARMRK) | @intCast(tcflag_t, std.os.ISTRIP) |
@intCast(tcflag_t, std.os.INLCR) | @intCast(tcflag_t, std.os.IGNCR) |
@intCast(tcflag_t, std.os.ICRNL) | @intCast(tcflag_t, std.os.IXON));
tios.oflag &= ~(@intCast(tcflag_t, std.os.OPOST));
tios.lflag &= ~(@intCast(tcflag_t, std.os.ECHO) | @intCast(tcflag_t, std.os.ECHONL) |
@intCast(tcflag_t, std.os.ICANON) | @intCast(tcflag_t, std.os.ISIG) |
@intCast(tcflag_t, std.os.IEXTEN));
tios.cflag &= ~(@intCast(tcflag_t, std.os.CSIZE) | @intCast(tcflag_t, std.os.PARENB));
tios.cflag |= @intCast(tcflag_t, std.os.CS8);
// FIXME
const VMIN = 6;
const VTIME = 5;
tios.cc[VMIN] = 0;
tios.cc[VTIME] = 0;
try std.os.tcsetattr(self.inout.handle, std.os.TCSA.FLUSH, tios);
try self.output_buffer.writer().writeAll(self.term.funcs.get(.EnterCa));
try self.output_buffer.writer().writeAll(self.term.funcs.get(.EnterKeypad));
try self.output_buffer.writer().writeAll(self.term.funcs.get(.HideCursor));
try self.sendClear();
self.updateTermSize();
self.back_buffer = try CellBuffer.init(allocator, self.term_w, self.term_h);
self.front_buffer = try CellBuffer.init(allocator, self.term_w, self.term_h);
self.back_buffer.clear(self.current_style);
self.front_buffer.clear(self.current_style);
return self;
}
pub fn initPath(allocator: *Allocator, path: []const u8) !Self {
return try initFile(allocator, try std.fs.openFileAbsolute(path, .{ .read = true, .write = true }));
}
pub fn init(allocator: *Allocator) !Self {
return try initPath(allocator, "/dev/tty");
}
pub fn shutdown(self: *Self) !void {
const writer = self.output_buffer.writer();
try writer.writeAll(self.term.funcs.get(.ShowCursor));
try writer.writeAll(self.term.funcs.get(.Sgr0));
try writer.writeAll(self.term.funcs.get(.ClearScreen));
try writer.writeAll(self.term.funcs.get(.ExitCa));
try writer.writeAll(self.term.funcs.get(.ExitKeypad));
try writer.writeAll(self.term.funcs.get(.ExitMouse));
try self.output_buffer.flush();
try std.os.tcsetattr(self.inout.handle, std.os.TCSA.FLUSH, self.orig_tios);
self.term.deinit();
self.inout.close();
std.os.close(self.winch_fds[0]);
std.os.close(self.winch_fds[1]);
self.back_buffer.deinit();
self.front_buffer.deinit();
self.input_buffer.deinit();
}
pub fn present(self: *Self) !void {
self.cursor_state.pos = null;
var y: usize = 0;
while (y < self.front_buffer.height) : (y += 1) {
var x: usize = 0;
while (x < self.front_buffer.width) {
const back = self.back_buffer.get(x, y);
const front = self.front_buffer.get(x, y);
const wcw = wcwidth(back.ch);
const w = if (wcw >= 0) @intCast(usize, wcw) else 1;
if (front.eql(back.*)) {
x += w;
continue;
}
front.* = back.*;
try updateStyle(self.output_buffer.writer(), back.style, self.current_style);
self.current_style = back.style;
if (x + w - 1 >= self.front_buffer.width) {
var i = x;
while (i < self.front_buffer.width) : (i += 1) {
try self.sendChar(i, y, ' ');
}
} else {
try self.sendChar(x, y, back.ch);
var i = x + 1;
while (i < x + w) : (i += 1) {
self.front_buffer.get(i, y).* = Cell{
.ch = 0,
.style = back.style,
};
}
}
x += w;
}
}
switch (self.cursor) {
.Visible => |pos| try writeCursor(self.output_buffer.writer(), pos.x, pos.y),
else => {},
}
try self.output_buffer.flush();
}
pub fn setCursor(self: *Self, new: Cursor) !void {
const writer = self.output_buffer.writer();
switch (new) {
.Hidden => {
if (self.cursor == .Visible) {
try writer.writeAll(self.term.funcs.get(.HideCursor));
}
},
.Visible => |pos| {
if (self.cursor == .Hidden) {
try writer.writeAll(self.term.funcs.get(.ShowCursor));
}
try writeCursor(writer, pos.x, pos.y);
self.cursor_state.pos = pos;
},
}
self.cursor = new;
}
// Tries to read an event if available.
pub fn getEvent(self: *Self) !?Event {
return try input.getEvent(self.inout, &self.input_buffer, self.term, self.input_settings);
}
// Poll and wait for the next event.
pub fn pollEvent(self: *Self) !Event {
return try input.waitFillEvent(self.inout, &self.input_buffer, self.term, self.input_settings);
}
pub fn clear(self: *Self) void {
self.current_style = Style{};
self.back_buffer.clear(self.current_style);
}
pub fn selectInputSettings(self: *Self, input_settings: InputSettings) !void {
try input_settings.applySettings(self.term, self.output_buffer.writer());
self.input_settings = input_settings;
}
fn updateTermSize(self: *Self) void {
var sz = std.mem.zeroes(std.os.linux.winsize);
_ = std.os.linux.ioctl(self.inout.handle, std.os.linux.TIOCGWINSZ, @ptrToInt(&sz));
self.term_w = sz.ws_col;
self.term_h = sz.ws_row;
}
fn sendChar(self: *Self, x: usize, y: usize, c: u21) !void {
const wanted_pos = Pos{ .x = x, .y = y };
if (self.cursor_state.pos == null or !std.meta.eql(self.cursor_state.pos, @as(?Pos, wanted_pos))) {
try writeCursor(self.output_buffer.writer(), x, y);
self.cursor_state.pos = Pos{ .x = x, .y = y };
}
var buf: [7]u8 = undefined;
const len = std.unicode.utf8Encode(@intCast(u21, c), &buf) catch 0;
try self.output_buffer.writer().writeAll(buf[0..len]);
}
fn sendClear(self: *Self) !void {
try self.output_buffer.writer().writeAll(self.term.funcs.get(.ClearScreen));
try self.output_buffer.flush();
}
fn updateSize(self: *Self) !void {
self.updateTermSize();
self.back_buffer.resize(self.term_w, self.term_h);
self.front_buffer.resize(self.term_w, self.term_h);
self.front_buffer.clear();
try self.sendClear();
}
}; | src/main.zig |
const std = @import("std");
pub fn build(b: *std.build.Builder) void {
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
// Standard release options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
const mode = b.standardReleaseOptions();
// For library
// const lib = b.addSharedLibrary("dross-zig", "src/dross_zig.zig", .unversioned);
const ft2 = b.addStaticLibrary("ft2", null);
ft2.addIncludeDir("libs/freetype");
ft2.addIncludeDir("libs/freetype/include");
//ft2.addLibPath("libs/freetype/x64_win");
//ft2.linkSystemLibrary("libs/freetype/x64_win/freetype");
ft2.addCSourceFile("libs/freetype/freetype_impl.c", &[_][]const u8{"--std=c17"});
ft2.setBuildMode(mode);
// For executable
const exe = b.addExecutable("dross-zig", "src/main.zig");
exe.setTarget(target);
exe.setBuildMode(mode);
// GLFW
exe.addIncludeDir("libs/glfw/include");
exe.addLibPath("libs/glfw/x64");
exe.linkSystemLibrary("glfw3");
b.installBinFile("libs/glfw/x64/glfw3.dll", "glfw3.dll");
// GLAD
exe.addIncludeDir("libs/glad");
exe.addCSourceFile("libs/glad/src/glad.c", &[_][]const u8{"--std=c99"});
// STB
exe.addIncludeDir("libs/stb");
// STB_IMAGE
exe.addCSourceFile("libs/stb/stb_image_impl.c", &[_][]const u8{"--std=c17"});
// STB_TRUETYPE
exe.addCSourceFile("libs/stb/stb_truetype_impl.c", &[_][]const u8{"--std=c17"});
// FREETYPE
exe.addIncludeDir("libs/freetype");
exe.addIncludeDir("libs/freetype/include");
//exe.linkLibrary(ft2);
exe.linkSystemLibrary("libs/freetype/x64_win/freetype");
// MINIAUDIO
exe.addIncludeDir("libs/miniaudio");
exe.addCSourceFile("libs/miniaudio/miniaudio_impl.c", &[_][]const u8{
if (target.getOsTag() == .windows) "-D__INTRIN_H" else "",
"--std=c17",
});
// ZALGEBRA
exe.addPackage(.{
.name = "zalgebra",
.path = "libs/zalgebra/src/main.zig",
});
exe.linkSystemLibrary("opengl32");
// Copy over the resource code
//b.installBinFile("src/renderer/shaders/default_shader.vs", "assets/shaders/default_shader.vs");
//b.installBinFile("src/renderer/shaders/default_shader.fs", "assets/shaders/default_shader.fs");
//b.installBinFile("src/renderer/shaders/screenbuffer_shader.vs", "assets/shaders/screenbuffer_shader.vs");
//b.installBinFile("src/renderer/shaders/screenbuffer_shader.fs", "assets/shaders/screenbuffer_shader.fs");
//b.installBinFile("assets/textures/t_default.png", "assets/textures/t_default.png");
exe.linkLibC();
exe.install();
const run_cmd = exe.run();
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);
} | build.zig |
const Allocator = struct {};
const CompanyInfo = struct {
name: []const u8,
};
const TrainNetwork = struct {
const Logistics = struct {
const Station = struct {using allocator: *Allocator,};
const Train = struct {using allocator: *Allocator,};
const Scheduler = struct {using allocator: *Allocator,};
scheduler: Scheduler,
stations: [5]Station,
trains: [17]Train,
pub fn firstStation(self: *Logistics) Station {} // hidden parameter injections required (1 *Allocator)
pub fn lastStation(self: *Logistics) Station {} // hidden parameter injections required (1 *Allocator)
pub fn nextStation(self: *Logistics) Station {} // hidden parameter injections required (1 *Allocator)
pub fn prevStation(self: *Logistics) Station {} // hidden parameter injections required (1 *Allocator)
pub fn getTrain(self: *Logistics) Train {} // hidden parameter injections required (1 *Allocator)
};
const Publisher = struct {using allocator: *Allocator, using company_info: *const CompanyInfo,};
const Region = struct {
d: Logistics,
e: Publisher,
};
using allocator: *Allocator
@providing(.{
.{"c[]|c_byname().", .{
"d.scheduler|stations|trains|()Station|()Train.allocator",
"e.allocator",
}},
.{"z.allocator"},
}),
c: Region,
z: TimeVarianceAuthority,
fn c_byname(self: *TrainNetwork, name: []const u8) Region {} // hidden parameter injections required (1 *Allocator, 1 *const CompanyInfo)
fn operate(self: *TrainNetwork) void {} // hidden parameter injections required (1 *Allocator, 1 *const CompanyInfo)
};
const TransportationAuthority = struct {
const company_info = CompanyInfo {
.name = "Earth Transportation Authority",
};
t: [4]TrainNetwork @usingDeclFor(company_info, .{".**"}),
pub fn at(self: *TransportationAuthority, i: u3) TrainNetwork { // hidden parameter injections required (1 *Allocator, 1 *const CompanyInfo)
return self.t[i];
}
};
const A = struct {
a: Allocator
@providing(.{"b.at().allocator"}),
b: TransportationAuthority,
};
const TimeVarianceAuthority = struct {using allocator: Allocator, const info = "redacted";};
fn runTrains(tn: *TrainNetwork) void { // hidden parameter injections required (1 *Allocator, 1 *const CompanyInfo)
tn.operate();
}
fn operateTA(ta: *TransportationAuthority) void { // hidden parameter injections required (1 *Allocator)
ta.at(2).runTrains();
}
test "" {
var a = A{};
a.b.operateTA();
} | stringly.zig |
Subsets and Splits