code
stringlengths
38
801k
repo_path
stringlengths
6
263
const std = @import("std"); const mem = std.mem; const ast = @import("ast.zig"); pub const Node = struct { value: NodeValue, start_line: u32 = 0, content: std.ArrayList(u8), open: bool = true, last_line_blank: bool = false, pub fn deinit(self: *Node, allocator: *mem.Allocator) void { self.content.deinit(); self.value.deinit(allocator); } }; pub const AstNode = ast.Ast(Node); pub const NodeValue = union(enum) { Document, BlockQuote, List: NodeList, Item: NodeList, // DescriptionList // DescriptionItem // DescriptionTerm // DescriptionDetails CodeBlock: NodeCodeBlock, HtmlBlock: NodeHtmlBlock, Paragraph, Heading: NodeHeading, ThematicBreak, // FootnoteDefinition Table: []TableAlignment, TableRow: TableHeader, TableCell, Text: []u8, // TaskItem SoftBreak, LineBreak, Code: []u8, HtmlInline: []u8, Emph, Strong, Strikethrough, Link: NodeLink, Image: NodeLink, // FootnoteReference pub fn deinit(self: *NodeValue, allocator: *mem.Allocator) void { switch (self.*) { .Text, .HtmlInline, .Code => |content| { allocator.free(content); }, .CodeBlock => |ncb| { ncb.literal.deinit(); }, .HtmlBlock => |nhb| { nhb.literal.deinit(); }, .Table => |aligns| { allocator.free(aligns); }, .Link, .Image => |nl| { allocator.free(nl.title); allocator.free(nl.url); }, else => {}, } } pub fn acceptsLines(self: NodeValue) bool { return switch (self) { .Paragraph, .Heading, .CodeBlock => true, else => false, }; } pub fn canContainType(self: NodeValue, child: NodeValue) bool { if (child == .Document) { return false; } return switch (self) { .Document, .BlockQuote, .Item => child.block() and switch (child) { .Item => false, else => true, }, .List => switch (child) { .Item => true, else => false, }, .Paragraph, .Heading, .Emph, .Strong, .Link, .Image => !child.block(), .Table => switch (child) { .TableRow => true, else => false, }, .TableRow => switch (child) { .TableCell => true, else => false, }, .TableCell => switch (child) { .Text, .Code, .Emph, .Strong, .Link, .Image, .Strikethrough, .HtmlInline => true, else => false, }, else => false, }; } pub fn containsInlines(self: NodeValue) bool { return switch (self) { .Paragraph, .Heading, .TableCell => true, else => false, }; } pub fn block(self: NodeValue) bool { return switch (self) { .Document, .BlockQuote, .List, .Item, .CodeBlock, .HtmlBlock, .Paragraph, .Heading, .ThematicBreak, .Table, .TableRow, .TableCell => true, else => false, }; } pub fn text(self: NodeValue) ?[]const u8 { return switch (self) { .Text => |t| t, else => null, }; } pub fn text_mut(self: *NodeValue) ?*[]u8 { return switch (self.*) { .Text => |*t| t, else => null, }; } }; pub const NodeLink = struct { url: []u8, title: []u8, }; pub const ListType = enum { Bullet, Ordered, }; pub const ListDelimType = enum { Period, Paren, }; pub const NodeList = struct { list_type: ListType, marker_offset: usize, padding: usize, start: usize, delimiter: ListDelimType, bullet_char: u8, tight: bool, }; pub const NodeHtmlBlock = struct { block_type: u8, literal: std.ArrayList(u8), }; pub const NodeCodeBlock = struct { fenced: bool, fence_char: u8, fence_length: usize, fence_offset: usize, info: ?[]u8, literal: std.ArrayList(u8), }; pub const NodeHeading = struct { level: u8 = 0, setext: bool = false, }; pub const AutolinkType = enum { URI, Email, }; pub const TableAlignment = enum { None, Left, Center, Right, }; pub const TableHeader = enum { Header, Body, };
src/nodes.zig
const builtin = @import("builtin"); const std = @import("std"); const Builder = std.build.Builder; const upaya_build = @import("src/build.zig"); pub fn build(b: *Builder) void { const target = b.standardTargetOptions(.{}); // use a different cache folder for macos arm builds b.cache_root = if (std.builtin.os.tag == .macos and std.builtin.cpu.arch == std.Target.Cpu.Arch.aarch64) "zig-arm-cache" else "zig-cache"; // first item in list will be added as "run" so `zig build run` will always work const examples = [_][2][]const u8{ [_][]const u8{ "empty", "examples/empty.zig" }, [_][]const u8{ "texture_packer", "examples/texture_packer.zig" }, [_][]const u8{ "generator_sokol", "examples/generator_sokol.zig" }, [_][]const u8{ "generator_zip", "examples/generator_zip.zig" }, [_][]const u8{ "editor", "examples/editor/editor_main.zig" }, [_][]const u8{ "tilemap", "examples/tilemap/tilemap_main.zig" }, [_][]const u8{ "offscreen_rendering", "examples/offscreen_rendering.zig" }, [_][]const u8{ "tilescript", "tilescript/ts_main.zig" }, [_][]const u8{ "texture_packer_cli", "examples/texture_packer_cli.zig" }, [_][]const u8{ "todo", "examples/todo.zig" }, [_][]const u8{ "docking", "examples/docking.zig" }, }; for (examples) |example, i| { createExe(b, target, example[0], example[1]) catch unreachable; // first element in the list is added as "run" so "zig build run" works if (i == 0) createExe(b, target, "run", example[1]) catch unreachable; } upaya_build.addTests(b, target); } /// creates an exe with all the required dependencies fn createExe(b: *Builder, target: std.build.Target, name: []const u8, source: []const u8) !void { const is_cli = std.mem.endsWith(u8, name, "cli"); var exe = b.addExecutable(name, source); exe.setBuildMode(b.standardReleaseOptions()); exe.setOutputDir(std.fs.path.join(b.allocator, &[_][]const u8{ b.cache_root, "bin" }) catch unreachable); exe.setTarget(target); if (is_cli) { upaya_build.linkCommandLineArtifact(b, exe, target, ""); } else { addUpayaToArtifact(b, exe, target, ""); } const run_cmd = exe.run(); const exe_step = b.step(name, b.fmt("run {s}.zig", .{name})); exe_step.dependOn(&run_cmd.step); b.default_step.dependOn(&exe.step); b.installArtifact(exe); } pub fn addUpayaToArtifact(b: *Builder, exe: *std.build.LibExeObjStep, target: std.build.Target, comptime prefix_path: []const u8) void { if (prefix_path.len > 0 and !std.mem.endsWith(u8, prefix_path, "/")) @panic("prefix-path must end with '/' if it is not empty"); upaya_build.linkArtifact(b, exe, target, prefix_path); }
build.zig
const assert = @import("std").debug.assert; test "nullable type" { const x : ?bool = true; if (x) |y| { if (y) { // OK } else { unreachable; } } else { unreachable; } const next_x : ?i32 = null; const z = next_x ?? 1234; assert(z == 1234); const final_x : ?i32 = 13; const num = final_x ?? unreachable; assert(num == 13); } test "test maybe object and get a pointer to the inner value" { var maybe_bool: ?bool = true; if (maybe_bool) |*b| { *b = false; } assert(??maybe_bool == false); } test "rhs maybe unwrap return" { const x: ?bool = true; const y = x ?? return; } test "maybe return" { maybeReturnImpl(); comptime maybeReturnImpl(); } fn maybeReturnImpl() void { assert(??foo(1235)); if (foo(null) != null) unreachable; assert(!??foo(1234)); } fn foo(x: ?i32) ?bool { const value = x ?? return null; return value > 1234; } test "if var maybe pointer" { assert(shouldBeAPlus1(Particle {.a = 14, .b = 1, .c = 1, .d = 1}) == 15); } fn shouldBeAPlus1(p: &const Particle) u64 { var maybe_particle: ?Particle = *p; if (maybe_particle) |*particle| { particle.a += 1; } if (maybe_particle) |particle| { return particle.a; } return 0; } const Particle = struct { a: u64, b: u64, c: u64, d: u64, }; test "null literal outside function" { const is_null = here_is_a_null_literal.context == null; assert(is_null); const is_non_null = here_is_a_null_literal.context != null; assert(!is_non_null); } const SillyStruct = struct { context: ?i32, }; const here_is_a_null_literal = SillyStruct { .context = null, }; test "test null runtime" { testTestNullRuntime(null); } fn testTestNullRuntime(x: ?i32) void { assert(x == null); assert(!(x != null)); } test "nullable void" { nullableVoidImpl(); comptime nullableVoidImpl(); } fn nullableVoidImpl() void { assert(bar(null) == null); assert(bar({}) != null); } fn bar(x: ?void) ?void { if (x) |_| { return {}; } else { return null; } } const StructWithNullable = struct { field: ?i32, }; var struct_with_nullable: StructWithNullable = undefined; test "unwrap nullable which is field of global var" { struct_with_nullable.field = null; if (struct_with_nullable.field) |payload| { unreachable; } struct_with_nullable.field = 1234; if (struct_with_nullable.field) |payload| { assert(payload == 1234); } else { unreachable; } } test "null with default unwrap" { const x: i32 = null ?? 1; assert(x == 1); }
test/cases/null.zig
const std = @import("std"); pub const cache = ".zigmod/deps"; pub fn addAllTo(exe: *std.build.LibExeObjStep) void { @setEvalBranchQuota(1_000_000); for (packages) |pkg| { exe.addPackage(pkg); } if (c_include_dirs.len > 0 or c_source_files.len > 0) { exe.linkLibC(); } for (c_include_dirs) |dir| { exe.addIncludeDir(dir); } inline for (c_source_files) |fpath| { exe.addCSourceFile(fpath[1], @field(c_source_flags, fpath[0])); } for (system_libs) |lib| { exe.linkSystemLibrary(lib); } } fn get_flags(comptime index: usize) []const u8 { return @field(c_source_flags, _paths[index]); } pub const _ids = .{ "89ujp8gq842x", "8mdbh0zuneb0", "s84v9o48ucb0", "2ta738wrqbaq", "0npcrzfdlrvk", "ejw82j2ipa0e", "9k24gimke1an", "csbnipaad8n7", "yyhw90zkzgmu", "u9w9dpp6p804", "ocmr9rtohgcc", "tnj3qf44tpeq", }; pub const _paths = .{ "/../../", "/v/git/github.com/yaml/libyaml/tag-0.2.5/", "/git/github.com/nektro/zig-ansi/", "/git/github.com/ziglibs/known-folders/", "/git/github.com/nektro/zig-licenses/", "/git/github.com/truemedian/zfetch/", "/git/github.com/truemedian/hzzp/", "/git/github.com/alexnask/iguanaTLS/", "/git/github.com/MasterQ32/zig-network/", "/git/github.com/MasterQ32/zig-uri/", "/git/github.com/nektro/zig-json/", "/v/http/aquila.red/1/nektro/range/v0.1.tar.gz/d2f72fdd/", }; pub const package_data = struct { pub const _s84v9o48ucb0 = std.build.Pkg{ .name = "ansi", .path = std.build.FileSource{ .path = cache ++ "/git/github.com/nektro/zig-ansi/src/lib.zig" }, .dependencies = &[_]std.build.Pkg{ } }; pub const _2ta738wrqbaq = std.build.Pkg{ .name = "known-folders", .path = std.build.FileSource{ .path = cache ++ "/git/github.com/ziglibs/known-folders/known-folders.zig" }, .dependencies = &[_]std.build.Pkg{ } }; pub const _0npcrzfdlrvk = std.build.Pkg{ .name = "licenses", .path = std.build.FileSource{ .path = cache ++ "/git/github.com/nektro/zig-licenses/src/lib.zig" }, .dependencies = &[_]std.build.Pkg{ } }; pub const _9k24gimke1an = std.build.Pkg{ .name = "hzzp", .path = std.build.FileSource{ .path = cache ++ "/git/github.com/truemedian/hzzp/src/main.zig" }, .dependencies = &[_]std.build.Pkg{ } }; pub const _csbnipaad8n7 = std.build.Pkg{ .name = "iguanaTLS", .path = std.build.FileSource{ .path = cache ++ "/git/github.com/alexnask/iguanaTLS/src/main.zig" }, .dependencies = &[_]std.build.Pkg{ } }; pub const _yyhw90zkzgmu = std.build.Pkg{ .name = "network", .path = std.build.FileSource{ .path = cache ++ "/git/github.com/MasterQ32/zig-network/network.zig" }, .dependencies = &[_]std.build.Pkg{ } }; pub const _u9w9dpp6p804 = std.build.Pkg{ .name = "uri", .path = std.build.FileSource{ .path = cache ++ "/git/github.com/MasterQ32/zig-uri/uri.zig" }, .dependencies = &[_]std.build.Pkg{ } }; pub const _ejw82j2ipa0e = std.build.Pkg{ .name = "zfetch", .path = std.build.FileSource{ .path = cache ++ "/git/github.com/truemedian/zfetch/src/main.zig" }, .dependencies = &[_]std.build.Pkg{ _9k24gimke1an, _csbnipaad8n7, _yyhw90zkzgmu, _u9w9dpp6p804, } }; pub const _ocmr9rtohgcc = std.build.Pkg{ .name = "json", .path = std.build.FileSource{ .path = cache ++ "/git/github.com/nektro/zig-json/src/lib.zig" }, .dependencies = &[_]std.build.Pkg{ } }; pub const _tnj3qf44tpeq = std.build.Pkg{ .name = "range", .path = std.build.FileSource{ .path = cache ++ "/v/http/aquila.red/1/nektro/range/v0.1.tar.gz/d2f72fdd/src/lib.zig" }, .dependencies = &[_]std.build.Pkg{ } }; pub const _89ujp8gq842x = std.build.Pkg{ .name = "zigmod", .path = std.build.FileSource{ .path = cache ++ "/../../src/lib.zig" }, .dependencies = &[_]std.build.Pkg{ _s84v9o48ucb0, _2ta738wrqbaq, _0npcrzfdlrvk, _ejw82j2ipa0e, _ocmr9rtohgcc, _tnj3qf44tpeq, } }; }; pub const packages = &[_]std.build.Pkg{ package_data._89ujp8gq842x, }; pub const pkgs = struct { pub const zigmod = packages[0]; }; pub const c_include_dirs = &[_][]const u8{ cache ++ _paths[1] ++ "include", }; pub const c_source_flags = struct { pub const @"8mdbh0zuneb0" = &.{"-DYAML_VERSION_MAJOR=0","-DYAML_VERSION_MINOR=2","-DYAML_VERSION_PATCH=5","-DYAML_VERSION_STRING=\"0.2.5\"","-DYAML_DECLARE_STATIC=1",}; }; pub const c_source_files = &[_][2][]const u8{ [_][]const u8{_ids[1], cache ++ _paths[1] ++ "src/api.c"}, [_][]const u8{_ids[1], cache ++ _paths[1] ++ "src/dumper.c"}, [_][]const u8{_ids[1], cache ++ _paths[1] ++ "src/emitter.c"}, [_][]const u8{_ids[1], cache ++ _paths[1] ++ "src/loader.c"}, [_][]const u8{_ids[1], cache ++ _paths[1] ++ "src/parser.c"}, [_][]const u8{_ids[1], cache ++ _paths[1] ++ "src/reader.c"}, [_][]const u8{_ids[1], cache ++ _paths[1] ++ "src/scanner.c"}, [_][]const u8{_ids[1], cache ++ _paths[1] ++ "src/writer.c"}, }; pub const system_libs = &[_][]const u8{ };
deps.zig
const std = @import("std"); const mode = @import("builtin").mode; // Checked arithmetic is disabled in non-debug modes to avoid side channels inline fn cast(comptime DestType: type, target: anytype) DestType { if (@typeInfo(@TypeOf(target)) == .Int) { const dest = @typeInfo(DestType).Int; const source = @typeInfo(@TypeOf(target)).Int; if (dest.bits < source.bits) { return @bitCast(DestType, @truncate(std.meta.Int(source.signedness, dest.bits), target)); } else { return @bitCast(DestType, @as(std.meta.Int(source.signedness, dest.bits), target)); } } return @as(DestType, target); } // The type LooseFieldElement is a field element with loose bounds. // Bounds: [[0x0 ~> 0xc000000], [0x0 ~> 0xc000000], [0x0 ~> 0xc000000], [0x0 ~> 0xc000000], [0x0 ~> 0xc000000]] pub const LooseFieldElement = [5]u32; // The type TightFieldElement is a field element with tight bounds. // Bounds: [[0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000], [0x0 ~> 0x4000000]] pub const TightFieldElement = [5]u32; /// The function addcarryxU26 is an addition with carry. /// /// Postconditions: /// out1 = (arg1 + arg2 + arg3) mod 2^26 /// out2 = ⌊(arg1 + arg2 + arg3) / 2^26βŒ‹ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0x3ffffff] /// arg3: [0x0 ~> 0x3ffffff] /// Output Bounds: /// out1: [0x0 ~> 0x3ffffff] /// out2: [0x0 ~> 0x1] inline fn addcarryxU26(out1: *u32, out2: *u1, arg1: u1, arg2: u32, arg3: u32) void { @setRuntimeSafety(mode == .Debug); const x1 = ((cast(u32, arg1) + arg2) + arg3); const x2 = (x1 & 0x3ffffff); const x3 = cast(u1, (x1 >> 26)); out1.* = x2; out2.* = x3; } /// The function subborrowxU26 is a subtraction with borrow. /// /// Postconditions: /// out1 = (-arg1 + arg2 + -arg3) mod 2^26 /// out2 = -⌊(-arg1 + arg2 + -arg3) / 2^26βŒ‹ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0x3ffffff] /// arg3: [0x0 ~> 0x3ffffff] /// Output Bounds: /// out1: [0x0 ~> 0x3ffffff] /// out2: [0x0 ~> 0x1] inline fn subborrowxU26(out1: *u32, out2: *u1, arg1: u1, arg2: u32, arg3: u32) void { @setRuntimeSafety(mode == .Debug); const x1 = cast(i32, (cast(i64, cast(i32, (cast(i64, arg2) - cast(i64, arg1)))) - cast(i64, arg3))); const x2 = cast(i1, (x1 >> 26)); const x3 = cast(u32, (cast(i64, x1) & cast(i64, 0x3ffffff))); out1.* = x3; out2.* = cast(u1, (cast(i2, 0x0) - cast(i2, x2))); } /// The function cmovznzU32 is a single-word conditional move. /// /// Postconditions: /// out1 = (if arg1 = 0 then arg2 else arg3) /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffff] /// arg3: [0x0 ~> 0xffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffff] inline fn cmovznzU32(out1: *u32, arg1: u1, arg2: u32, arg3: u32) void { @setRuntimeSafety(mode == .Debug); const x1 = (~(~arg1)); const x2 = cast(u32, (cast(i64, cast(i1, (cast(i2, 0x0) - cast(i2, x1)))) & cast(i64, 0xffffffff))); const x3 = ((x2 & arg3) | ((~x2) & arg2)); out1.* = x3; } /// The function carryMul multiplies two field elements and reduces the result. /// /// Postconditions: /// eval out1 mod m = (eval arg1 * eval arg2) mod m /// pub fn carryMul(out1: *TightFieldElement, arg1: LooseFieldElement, arg2: LooseFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = (cast(u64, (arg1[4])) * cast(u64, ((arg2[4]) * 0x5))); const x2 = (cast(u64, (arg1[4])) * cast(u64, ((arg2[3]) * 0x5))); const x3 = (cast(u64, (arg1[4])) * cast(u64, ((arg2[2]) * 0x5))); const x4 = (cast(u64, (arg1[4])) * cast(u64, ((arg2[1]) * 0x5))); const x5 = (cast(u64, (arg1[3])) * cast(u64, ((arg2[4]) * 0x5))); const x6 = (cast(u64, (arg1[3])) * cast(u64, ((arg2[3]) * 0x5))); const x7 = (cast(u64, (arg1[3])) * cast(u64, ((arg2[2]) * 0x5))); const x8 = (cast(u64, (arg1[2])) * cast(u64, ((arg2[4]) * 0x5))); const x9 = (cast(u64, (arg1[2])) * cast(u64, ((arg2[3]) * 0x5))); const x10 = (cast(u64, (arg1[1])) * cast(u64, ((arg2[4]) * 0x5))); const x11 = (cast(u64, (arg1[4])) * cast(u64, (arg2[0]))); const x12 = (cast(u64, (arg1[3])) * cast(u64, (arg2[1]))); const x13 = (cast(u64, (arg1[3])) * cast(u64, (arg2[0]))); const x14 = (cast(u64, (arg1[2])) * cast(u64, (arg2[2]))); const x15 = (cast(u64, (arg1[2])) * cast(u64, (arg2[1]))); const x16 = (cast(u64, (arg1[2])) * cast(u64, (arg2[0]))); const x17 = (cast(u64, (arg1[1])) * cast(u64, (arg2[3]))); const x18 = (cast(u64, (arg1[1])) * cast(u64, (arg2[2]))); const x19 = (cast(u64, (arg1[1])) * cast(u64, (arg2[1]))); const x20 = (cast(u64, (arg1[1])) * cast(u64, (arg2[0]))); const x21 = (cast(u64, (arg1[0])) * cast(u64, (arg2[4]))); const x22 = (cast(u64, (arg1[0])) * cast(u64, (arg2[3]))); const x23 = (cast(u64, (arg1[0])) * cast(u64, (arg2[2]))); const x24 = (cast(u64, (arg1[0])) * cast(u64, (arg2[1]))); const x25 = (cast(u64, (arg1[0])) * cast(u64, (arg2[0]))); const x26 = (x25 + (x10 + (x9 + (x7 + x4)))); const x27 = (x26 >> 26); const x28 = cast(u32, (x26 & cast(u64, 0x3ffffff))); const x29 = (x21 + (x17 + (x14 + (x12 + x11)))); const x30 = (x22 + (x18 + (x15 + (x13 + x1)))); const x31 = (x23 + (x19 + (x16 + (x5 + x2)))); const x32 = (x24 + (x20 + (x8 + (x6 + x3)))); const x33 = (x27 + x32); const x34 = (x33 >> 26); const x35 = cast(u32, (x33 & cast(u64, 0x3ffffff))); const x36 = (x34 + x31); const x37 = (x36 >> 26); const x38 = cast(u32, (x36 & cast(u64, 0x3ffffff))); const x39 = (x37 + x30); const x40 = (x39 >> 26); const x41 = cast(u32, (x39 & cast(u64, 0x3ffffff))); const x42 = (x40 + x29); const x43 = cast(u32, (x42 >> 26)); const x44 = cast(u32, (x42 & cast(u64, 0x3ffffff))); const x45 = (cast(u64, x43) * cast(u64, 0x5)); const x46 = (cast(u64, x28) + x45); const x47 = cast(u32, (x46 >> 26)); const x48 = cast(u32, (x46 & cast(u64, 0x3ffffff))); const x49 = (x47 + x35); const x50 = cast(u1, (x49 >> 26)); const x51 = (x49 & 0x3ffffff); const x52 = (cast(u32, x50) + x38); out1[0] = x48; out1[1] = x51; out1[2] = x52; out1[3] = x41; out1[4] = x44; } /// The function carrySquare squares a field element and reduces the result. /// /// Postconditions: /// eval out1 mod m = (eval arg1 * eval arg1) mod m /// pub fn carrySquare(out1: *TightFieldElement, arg1: LooseFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = ((arg1[4]) * 0x5); const x2 = (x1 * 0x2); const x3 = ((arg1[4]) * 0x2); const x4 = ((arg1[3]) * 0x5); const x5 = (x4 * 0x2); const x6 = ((arg1[3]) * 0x2); const x7 = ((arg1[2]) * 0x2); const x8 = ((arg1[1]) * 0x2); const x9 = (cast(u64, (arg1[4])) * cast(u64, x1)); const x10 = (cast(u64, (arg1[3])) * cast(u64, x2)); const x11 = (cast(u64, (arg1[3])) * cast(u64, x4)); const x12 = (cast(u64, (arg1[2])) * cast(u64, x2)); const x13 = (cast(u64, (arg1[2])) * cast(u64, x5)); const x14 = (cast(u64, (arg1[2])) * cast(u64, (arg1[2]))); const x15 = (cast(u64, (arg1[1])) * cast(u64, x2)); const x16 = (cast(u64, (arg1[1])) * cast(u64, x6)); const x17 = (cast(u64, (arg1[1])) * cast(u64, x7)); const x18 = (cast(u64, (arg1[1])) * cast(u64, (arg1[1]))); const x19 = (cast(u64, (arg1[0])) * cast(u64, x3)); const x20 = (cast(u64, (arg1[0])) * cast(u64, x6)); const x21 = (cast(u64, (arg1[0])) * cast(u64, x7)); const x22 = (cast(u64, (arg1[0])) * cast(u64, x8)); const x23 = (cast(u64, (arg1[0])) * cast(u64, (arg1[0]))); const x24 = (x23 + (x15 + x13)); const x25 = (x24 >> 26); const x26 = cast(u32, (x24 & cast(u64, 0x3ffffff))); const x27 = (x19 + (x16 + x14)); const x28 = (x20 + (x17 + x9)); const x29 = (x21 + (x18 + x10)); const x30 = (x22 + (x12 + x11)); const x31 = (x25 + x30); const x32 = (x31 >> 26); const x33 = cast(u32, (x31 & cast(u64, 0x3ffffff))); const x34 = (x32 + x29); const x35 = (x34 >> 26); const x36 = cast(u32, (x34 & cast(u64, 0x3ffffff))); const x37 = (x35 + x28); const x38 = (x37 >> 26); const x39 = cast(u32, (x37 & cast(u64, 0x3ffffff))); const x40 = (x38 + x27); const x41 = cast(u32, (x40 >> 26)); const x42 = cast(u32, (x40 & cast(u64, 0x3ffffff))); const x43 = (cast(u64, x41) * cast(u64, 0x5)); const x44 = (cast(u64, x26) + x43); const x45 = cast(u32, (x44 >> 26)); const x46 = cast(u32, (x44 & cast(u64, 0x3ffffff))); const x47 = (x45 + x33); const x48 = cast(u1, (x47 >> 26)); const x49 = (x47 & 0x3ffffff); const x50 = (cast(u32, x48) + x36); out1[0] = x46; out1[1] = x49; out1[2] = x50; out1[3] = x39; out1[4] = x42; } /// The function carry reduces a field element. /// /// Postconditions: /// eval out1 mod m = eval arg1 mod m /// pub fn carry(out1: *TightFieldElement, arg1: LooseFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[0]); const x2 = ((x1 >> 26) + (arg1[1])); const x3 = ((x2 >> 26) + (arg1[2])); const x4 = ((x3 >> 26) + (arg1[3])); const x5 = ((x4 >> 26) + (arg1[4])); const x6 = ((x1 & 0x3ffffff) + ((x5 >> 26) * 0x5)); const x7 = (cast(u32, cast(u1, (x6 >> 26))) + (x2 & 0x3ffffff)); const x8 = (x6 & 0x3ffffff); const x9 = (x7 & 0x3ffffff); const x10 = (cast(u32, cast(u1, (x7 >> 26))) + (x3 & 0x3ffffff)); const x11 = (x4 & 0x3ffffff); const x12 = (x5 & 0x3ffffff); out1[0] = x8; out1[1] = x9; out1[2] = x10; out1[3] = x11; out1[4] = x12; } /// The function add adds two field elements. /// /// Postconditions: /// eval out1 mod m = (eval arg1 + eval arg2) mod m /// pub fn add(out1: *LooseFieldElement, arg1: TightFieldElement, arg2: TightFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = ((arg1[0]) + (arg2[0])); const x2 = ((arg1[1]) + (arg2[1])); const x3 = ((arg1[2]) + (arg2[2])); const x4 = ((arg1[3]) + (arg2[3])); const x5 = ((arg1[4]) + (arg2[4])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; } /// The function sub subtracts two field elements. /// /// Postconditions: /// eval out1 mod m = (eval arg1 - eval arg2) mod m /// pub fn sub(out1: *LooseFieldElement, arg1: TightFieldElement, arg2: TightFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = ((0x7fffff6 + (arg1[0])) - (arg2[0])); const x2 = ((0x7fffffe + (arg1[1])) - (arg2[1])); const x3 = ((0x7fffffe + (arg1[2])) - (arg2[2])); const x4 = ((0x7fffffe + (arg1[3])) - (arg2[3])); const x5 = ((0x7fffffe + (arg1[4])) - (arg2[4])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; } /// The function opp negates a field element. /// /// Postconditions: /// eval out1 mod m = -eval arg1 mod m /// pub fn opp(out1: *LooseFieldElement, arg1: TightFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = (0x7fffff6 - (arg1[0])); const x2 = (0x7fffffe - (arg1[1])); const x3 = (0x7fffffe - (arg1[2])); const x4 = (0x7fffffe - (arg1[3])); const x5 = (0x7fffffe - (arg1[4])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; } /// The function selectznz is a multi-limb conditional select. /// /// Postconditions: /// out1 = (if arg1 = 0 then arg2 else arg3) /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg3: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn selectznz(out1: *[5]u32, arg1: u1, arg2: [5]u32, arg3: [5]u32) void { @setRuntimeSafety(mode == .Debug); var x1: u32 = undefined; cmovznzU32(&x1, arg1, (arg2[0]), (arg3[0])); var x2: u32 = undefined; cmovznzU32(&x2, arg1, (arg2[1]), (arg3[1])); var x3: u32 = undefined; cmovznzU32(&x3, arg1, (arg2[2]), (arg3[2])); var x4: u32 = undefined; cmovznzU32(&x4, arg1, (arg2[3]), (arg3[3])); var x5: u32 = undefined; cmovznzU32(&x5, arg1, (arg2[4]), (arg3[4])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; } /// The function toBytes serializes a field element to bytes in little-endian order. /// /// Postconditions: /// out1 = map (Ξ» x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)βŒ‹) [0..16] /// /// Output Bounds: /// out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x3]] pub fn toBytes(out1: *[17]u8, arg1: TightFieldElement) void { @setRuntimeSafety(mode == .Debug); var x1: u32 = undefined; var x2: u1 = undefined; subborrowxU26(&x1, &x2, 0x0, (arg1[0]), 0x3fffffb); var x3: u32 = undefined; var x4: u1 = undefined; subborrowxU26(&x3, &x4, x2, (arg1[1]), 0x3ffffff); var x5: u32 = undefined; var x6: u1 = undefined; subborrowxU26(&x5, &x6, x4, (arg1[2]), 0x3ffffff); var x7: u32 = undefined; var x8: u1 = undefined; subborrowxU26(&x7, &x8, x6, (arg1[3]), 0x3ffffff); var x9: u32 = undefined; var x10: u1 = undefined; subborrowxU26(&x9, &x10, x8, (arg1[4]), 0x3ffffff); var x11: u32 = undefined; cmovznzU32(&x11, x10, cast(u32, 0x0), 0xffffffff); var x12: u32 = undefined; var x13: u1 = undefined; addcarryxU26(&x12, &x13, 0x0, x1, (x11 & 0x3fffffb)); var x14: u32 = undefined; var x15: u1 = undefined; addcarryxU26(&x14, &x15, x13, x3, (x11 & 0x3ffffff)); var x16: u32 = undefined; var x17: u1 = undefined; addcarryxU26(&x16, &x17, x15, x5, (x11 & 0x3ffffff)); var x18: u32 = undefined; var x19: u1 = undefined; addcarryxU26(&x18, &x19, x17, x7, (x11 & 0x3ffffff)); var x20: u32 = undefined; var x21: u1 = undefined; addcarryxU26(&x20, &x21, x19, x9, (x11 & 0x3ffffff)); const x22 = (x18 << 6); const x23 = (x16 << 4); const x24 = (x14 << 2); const x25 = cast(u8, (x12 & cast(u32, 0xff))); const x26 = (x12 >> 8); const x27 = cast(u8, (x26 & cast(u32, 0xff))); const x28 = (x26 >> 8); const x29 = cast(u8, (x28 & cast(u32, 0xff))); const x30 = cast(u8, (x28 >> 8)); const x31 = (x24 + cast(u32, x30)); const x32 = cast(u8, (x31 & cast(u32, 0xff))); const x33 = (x31 >> 8); const x34 = cast(u8, (x33 & cast(u32, 0xff))); const x35 = (x33 >> 8); const x36 = cast(u8, (x35 & cast(u32, 0xff))); const x37 = cast(u8, (x35 >> 8)); const x38 = (x23 + cast(u32, x37)); const x39 = cast(u8, (x38 & cast(u32, 0xff))); const x40 = (x38 >> 8); const x41 = cast(u8, (x40 & cast(u32, 0xff))); const x42 = (x40 >> 8); const x43 = cast(u8, (x42 & cast(u32, 0xff))); const x44 = cast(u8, (x42 >> 8)); const x45 = (x22 + cast(u32, x44)); const x46 = cast(u8, (x45 & cast(u32, 0xff))); const x47 = (x45 >> 8); const x48 = cast(u8, (x47 & cast(u32, 0xff))); const x49 = (x47 >> 8); const x50 = cast(u8, (x49 & cast(u32, 0xff))); const x51 = cast(u8, (x49 >> 8)); const x52 = cast(u8, (x20 & cast(u32, 0xff))); const x53 = (x20 >> 8); const x54 = cast(u8, (x53 & cast(u32, 0xff))); const x55 = (x53 >> 8); const x56 = cast(u8, (x55 & cast(u32, 0xff))); const x57 = cast(u8, (x55 >> 8)); out1[0] = x25; out1[1] = x27; out1[2] = x29; out1[3] = x32; out1[4] = x34; out1[5] = x36; out1[6] = x39; out1[7] = x41; out1[8] = x43; out1[9] = x46; out1[10] = x48; out1[11] = x50; out1[12] = x51; out1[13] = x52; out1[14] = x54; out1[15] = x56; out1[16] = x57; } /// The function fromBytes deserializes a field element from bytes in little-endian order. /// /// Postconditions: /// eval out1 mod m = bytes_eval arg1 mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x3]] pub fn fromBytes(out1: *TightFieldElement, arg1: [17]u8) void { @setRuntimeSafety(mode == .Debug); const x1 = (cast(u32, (arg1[16])) << 24); const x2 = (cast(u32, (arg1[15])) << 16); const x3 = (cast(u32, (arg1[14])) << 8); const x4 = (arg1[13]); const x5 = (cast(u32, (arg1[12])) << 18); const x6 = (cast(u32, (arg1[11])) << 10); const x7 = (cast(u32, (arg1[10])) << 2); const x8 = (cast(u32, (arg1[9])) << 20); const x9 = (cast(u32, (arg1[8])) << 12); const x10 = (cast(u32, (arg1[7])) << 4); const x11 = (cast(u32, (arg1[6])) << 22); const x12 = (cast(u32, (arg1[5])) << 14); const x13 = (cast(u32, (arg1[4])) << 6); const x14 = (cast(u32, (arg1[3])) << 24); const x15 = (cast(u32, (arg1[2])) << 16); const x16 = (cast(u32, (arg1[1])) << 8); const x17 = (arg1[0]); const x18 = (x16 + cast(u32, x17)); const x19 = (x15 + x18); const x20 = (x14 + x19); const x21 = (x20 & 0x3ffffff); const x22 = cast(u8, (x20 >> 26)); const x23 = (x13 + cast(u32, x22)); const x24 = (x12 + x23); const x25 = (x11 + x24); const x26 = (x25 & 0x3ffffff); const x27 = cast(u8, (x25 >> 26)); const x28 = (x10 + cast(u32, x27)); const x29 = (x9 + x28); const x30 = (x8 + x29); const x31 = (x30 & 0x3ffffff); const x32 = cast(u8, (x30 >> 26)); const x33 = (x7 + cast(u32, x32)); const x34 = (x6 + x33); const x35 = (x5 + x34); const x36 = (x3 + cast(u32, x4)); const x37 = (x2 + x36); const x38 = (x1 + x37); out1[0] = x21; out1[1] = x26; out1[2] = x31; out1[3] = x35; out1[4] = x38; } /// The function relax is the identity function converting from tight field elements to loose field elements. /// /// Postconditions: /// out1 = arg1 /// pub fn relax(out1: *LooseFieldElement, arg1: TightFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[0]); const x2 = (arg1[1]); const x3 = (arg1[2]); const x4 = (arg1[3]); const x5 = (arg1[4]); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; }
fiat-zig/src/poly1305_32.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const c = @import("c.zig"); const odbc = @import("types.zig"); const HandleType = odbc.HandleType; const SqlReturn = odbc.SqlReturn; const odbc_error = @import("error.zig"); const ReturnError = odbc_error.ReturnError; const OdbcError = odbc_error.OdbcError; // @todo persistent FixedBufferAllocator for errors? pub const Environment = struct { pub const Attribute = odbc.EnvironmentAttribute; pub const AttributeValue = odbc.EnvironmentAttributeValue; handle: *c_void, pub fn init() ReturnError!Environment { var result: Environment = undefined; const alloc_result = c.SQLAllocHandle(@enumToInt(HandleType.Environment), null, @ptrCast([*c]?*c_void, &result.handle)); return switch (@intToEnum(SqlReturn, alloc_result)) { .InvalidHandle => @panic("Environment init passed invalid handle type"), .Error => error.Error, else => result, }; } /// Free the environment handle. If this succeeds, then it's invalid to try to use this environment /// again. If this fails, then the environment handle will still be active and must be deinitialized /// again after fixing the errors. pub fn deinit(self: *Environment) ReturnError!void { const result = c.SQLFreeHandle(@enumToInt(HandleType.Environment), self.handle); return switch (@intToEnum(SqlReturn, result)) { .InvalidHandle => @panic("Environment deinit passed invalid handle type"), // Handle type is hardcoded above, this should never be reached .Error => error.Error, else => {} }; } pub fn getDataSource(self: *Environment, allocator: *Allocator, direction: odbc.Direction) !?odbc.DataSource { var server_name_buf = try allocator.alloc(u8, 100); var description_buf = try allocator.alloc(u8, 100); var server_name_len: i16 = 0; var description_len: i16 = 0; run_loop: while (true) { const result = c.SQLDataSources(self.handle, @enumToInt(direction), server_name_buf.ptr, @intCast(i16, server_name_buf.len), &server_name_len, description_buf.ptr, @intCast(i16, description_buf.len), &description_len); switch (@intToEnum(SqlReturn, result)) { .Success => return odbc.DataSource{ .server_name = server_name_buf[0..@intCast(usize, server_name_len)], .description = description_buf[0..@intCast(usize, description_len)], }, .SuccessWithInfo => { const errors = try self.getErrors(); for (errors) |err| { if (err == .StringRightTrunc) { server_name_buf = try allocator.resize(server_name_buf, @intCast(usize, server_name_len + 1)); description_buf = try allocator.resize(description_buf, @intCast(usize, description_len + 1)); continue :run_loop; } } return error.Error; }, .NoData => return null, else => return error.Error } } } pub fn getDriver(self: *Environment, allocator: *Allocator, direction: odbc.Direction) !?odbc.Driver { var description_buf = try allocator.alloc(u8, 100); var attribute_buf = try allocator.alloc(u8, 100); var description_len: i16 = 0; var attributes_len: i16 = 0; run_loop: while (true) { const result = c.SQLDrivers(self.handle, @enumToInt(direction), description_buf.ptr, @intCast(i16, description_buf.len), &description_len, attribute_buf.ptr, @intCast(i16, attribute_buf.len), &attributes_len); switch (@intToEnum(SqlReturn, result)) { .Success => return odbc.Driver{ .description = description_buf[0..@intCast(usize, description_len)], .attributes = attribute_buf[0..@intCast(usize, attributes_len)] }, .NoData => return null, .SuccessWithInfo => { const errors = try self.getErrors(); for (errors) |err| { if (err == .StringRightTrunc) { description_buf = try allocator.resize(description_buf, @intCast(usize, description_len + 1)); attribute_buf = try allocator.resize(attribute_buf, @intCast(usize, attributes_len + 1)); continue :run_loop; } } return error.Error; }, else => return error.Error } } } pub fn getAllDrivers(self: *Environment, allocator: *Allocator) ![]odbc.Driver { var driver_list = std.ArrayList(odbc.Driver).init(allocator); var direction: odbc.Direction = .FetchFirst; while (true) { const driver = self.getDriver(allocator, direction) catch break; if (driver) |d| { try driver_list.append(d); direction = .FetchNext; } else break; } return driver_list.toOwnedSlice(); } pub fn getAttribute(self: *Environment, attribute: Attribute) ReturnError!AttributeValue { var value: i32 = 0; const result = c.SQLGetEnvAttr(self.handle, @enumToInt(attribute), &value, 0, null); return switch (@intToEnum(SqlReturn, result)) { .Success, .SuccessWithInfo => attribute.getAttributeValue(value), else => error.Error }; } pub fn setAttribute(self: *Environment, value: AttributeValue) ReturnError!void { const result = c.SQLSetEnvAttr(self.handle, @enumToInt(std.meta.activeTag(value)), @intToPtr(*c_void, value.getValue()), 0); return switch (@intToEnum(SqlReturn, result)) { .Success, .SuccessWithInfo => {}, else => error.Error }; } /// Set the OdbcVersion attribute for this environment. You must set the version immediately after /// allocating an environment, either using this function or `setAttribute(.{ .OdbcVersion = <version> })`. pub fn setOdbcVersion(self: *Environment, version: AttributeValue.OdbcVersion) !void { try self.setAttribute(.{ .OdbcVersion = version }); } pub fn getOdbcVersion(self: *Environment) !AttributeValue.OdbcVersion { const attr = try self.getAttribute(.OdbcVersion); return attr.OdbcVersion; } pub fn getErrors(self: *Environment, allocator: *Allocator) ![]odbc_error.SqlState { return try odbc_error.getErrors(allocator, HandleType.Environment, self.handle); } pub fn getDiagnosticRecords(self: *Environment, allocator: *Allocator) ![]odbc_error.DiagnosticRecord { return try odbc_error.getDiagnosticRecords(allocator, HandleType.Environment, self.handle); } };
src/environment.zig
const std = @import("std"); const cast = std.meta.cast; const mode = std.builtin.mode; // Checked arithmetic is disabled in non-debug modes to avoid side channels /// The function addcarryxU44 is an addition with carry. /// Postconditions: /// out1 = (arg1 + arg2 + arg3) mod 2^44 /// out2 = ⌊(arg1 + arg2 + arg3) / 2^44βŒ‹ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xfffffffffff] /// arg3: [0x0 ~> 0xfffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xfffffffffff] /// out2: [0x0 ~> 0x1] fn addcarryxU44(out1: *u64, out2: *u1, arg1: u1, arg2: u64, arg3: u64) callconv(.Inline) void { @setRuntimeSafety(mode == .Debug); const x1 = ((cast(u64, arg1) + arg2) + arg3); const x2 = (x1 & 0xfffffffffff); const x3 = cast(u1, (x1 >> 44)); out1.* = x2; out2.* = x3; } /// The function subborrowxU44 is a subtraction with borrow. /// Postconditions: /// out1 = (-arg1 + arg2 + -arg3) mod 2^44 /// out2 = -⌊(-arg1 + arg2 + -arg3) / 2^44βŒ‹ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xfffffffffff] /// arg3: [0x0 ~> 0xfffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xfffffffffff] /// out2: [0x0 ~> 0x1] fn subborrowxU44(out1: *u64, out2: *u1, arg1: u1, arg2: u64, arg3: u64) callconv(.Inline) void { @setRuntimeSafety(mode == .Debug); const x1 = cast(i64, (cast(i128, cast(i64, (cast(i128, arg2) - cast(i128, arg1)))) - cast(i128, arg3))); const x2 = cast(i1, (x1 >> 44)); const x3 = cast(u64, (cast(i128, x1) & cast(i128, 0xfffffffffff))); out1.* = x3; out2.* = cast(u1, (cast(i2, 0x0) - cast(i2, x2))); } /// The function addcarryxU43 is an addition with carry. /// Postconditions: /// out1 = (arg1 + arg2 + arg3) mod 2^43 /// out2 = ⌊(arg1 + arg2 + arg3) / 2^43βŒ‹ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0x7ffffffffff] /// arg3: [0x0 ~> 0x7ffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0x7ffffffffff] /// out2: [0x0 ~> 0x1] fn addcarryxU43(out1: *u64, out2: *u1, arg1: u1, arg2: u64, arg3: u64) callconv(.Inline) void { @setRuntimeSafety(mode == .Debug); const x1 = ((cast(u64, arg1) + arg2) + arg3); const x2 = (x1 & 0x7ffffffffff); const x3 = cast(u1, (x1 >> 43)); out1.* = x2; out2.* = x3; } /// The function subborrowxU43 is a subtraction with borrow. /// Postconditions: /// out1 = (-arg1 + arg2 + -arg3) mod 2^43 /// out2 = -⌊(-arg1 + arg2 + -arg3) / 2^43βŒ‹ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0x7ffffffffff] /// arg3: [0x0 ~> 0x7ffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0x7ffffffffff] /// out2: [0x0 ~> 0x1] fn subborrowxU43(out1: *u64, out2: *u1, arg1: u1, arg2: u64, arg3: u64) callconv(.Inline) void { @setRuntimeSafety(mode == .Debug); const x1 = cast(i64, (cast(i128, cast(i64, (cast(i128, arg2) - cast(i128, arg1)))) - cast(i128, arg3))); const x2 = cast(i1, (x1 >> 43)); const x3 = cast(u64, (cast(i128, x1) & cast(i128, 0x7ffffffffff))); out1.* = x3; out2.* = cast(u1, (cast(i2, 0x0) - cast(i2, x2))); } /// The function cmovznzU64 is a single-word conditional move. /// Postconditions: /// out1 = (if arg1 = 0 then arg2 else arg3) /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffffffffffff] /// arg3: [0x0 ~> 0xffffffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] fn cmovznzU64(out1: *u64, arg1: u1, arg2: u64, arg3: u64) callconv(.Inline) void { @setRuntimeSafety(mode == .Debug); const x1 = (~(~arg1)); const x2 = cast(u64, (cast(i128, cast(i1, (cast(i2, 0x0) - cast(i2, x1)))) & cast(i128, 0xffffffffffffffff))); const x3 = ((x2 & arg3) | ((~x2) & arg2)); out1.* = x3; } /// The function carryMul multiplies two field elements and reduces the result. /// Postconditions: /// eval out1 mod m = (eval arg1 * eval arg2) mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0x300000000000], [0x0 ~> 0x180000000000], [0x0 ~> 0x180000000000]] /// arg2: [[0x0 ~> 0x300000000000], [0x0 ~> 0x180000000000], [0x0 ~> 0x180000000000]] /// Output Bounds: /// out1: [[0x0 ~> 0x100000000000], [0x0 ~> 0x80000000000], [0x0 ~> 0x80000000000]] pub fn carryMul(out1: *[3]u64, arg1: [3]u64, arg2: [3]u64) void { @setRuntimeSafety(mode == .Debug); const x1 = (cast(u128, (arg1[2])) * cast(u128, ((arg2[2]) * 0x5))); const x2 = (cast(u128, (arg1[2])) * cast(u128, ((arg2[1]) * 0xa))); const x3 = (cast(u128, (arg1[1])) * cast(u128, ((arg2[2]) * 0xa))); const x4 = (cast(u128, (arg1[2])) * cast(u128, (arg2[0]))); const x5 = (cast(u128, (arg1[1])) * cast(u128, ((arg2[1]) * 0x2))); const x6 = (cast(u128, (arg1[1])) * cast(u128, (arg2[0]))); const x7 = (cast(u128, (arg1[0])) * cast(u128, (arg2[2]))); const x8 = (cast(u128, (arg1[0])) * cast(u128, (arg2[1]))); const x9 = (cast(u128, (arg1[0])) * cast(u128, (arg2[0]))); const x10 = (x9 + (x3 + x2)); const x11 = cast(u64, (x10 >> 44)); const x12 = cast(u64, (x10 & cast(u128, 0xfffffffffff))); const x13 = (x7 + (x5 + x4)); const x14 = (x8 + (x6 + x1)); const x15 = (cast(u128, x11) + x14); const x16 = cast(u64, (x15 >> 43)); const x17 = cast(u64, (x15 & cast(u128, 0x7ffffffffff))); const x18 = (cast(u128, x16) + x13); const x19 = cast(u64, (x18 >> 43)); const x20 = cast(u64, (x18 & cast(u128, 0x7ffffffffff))); const x21 = (x19 * 0x5); const x22 = (x12 + x21); const x23 = (x22 >> 44); const x24 = (x22 & 0xfffffffffff); const x25 = (x23 + x17); const x26 = cast(u1, (x25 >> 43)); const x27 = (x25 & 0x7ffffffffff); const x28 = (cast(u64, x26) + x20); out1[0] = x24; out1[1] = x27; out1[2] = x28; } /// The function carrySquare squares a field element and reduces the result. /// Postconditions: /// eval out1 mod m = (eval arg1 * eval arg1) mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0x300000000000], [0x0 ~> 0x180000000000], [0x0 ~> 0x180000000000]] /// Output Bounds: /// out1: [[0x0 ~> 0x100000000000], [0x0 ~> 0x80000000000], [0x0 ~> 0x80000000000]] pub fn carrySquare(out1: *[3]u64, arg1: [3]u64) void { @setRuntimeSafety(mode == .Debug); const x1 = ((arg1[2]) * 0x5); const x2 = (x1 * 0x2); const x3 = ((arg1[2]) * 0x2); const x4 = ((arg1[1]) * 0x2); const x5 = (cast(u128, (arg1[2])) * cast(u128, x1)); const x6 = (cast(u128, (arg1[1])) * cast(u128, (x2 * 0x2))); const x7 = (cast(u128, (arg1[1])) * cast(u128, ((arg1[1]) * 0x2))); const x8 = (cast(u128, (arg1[0])) * cast(u128, x3)); const x9 = (cast(u128, (arg1[0])) * cast(u128, x4)); const x10 = (cast(u128, (arg1[0])) * cast(u128, (arg1[0]))); const x11 = (x10 + x6); const x12 = cast(u64, (x11 >> 44)); const x13 = cast(u64, (x11 & cast(u128, 0xfffffffffff))); const x14 = (x8 + x7); const x15 = (x9 + x5); const x16 = (cast(u128, x12) + x15); const x17 = cast(u64, (x16 >> 43)); const x18 = cast(u64, (x16 & cast(u128, 0x7ffffffffff))); const x19 = (cast(u128, x17) + x14); const x20 = cast(u64, (x19 >> 43)); const x21 = cast(u64, (x19 & cast(u128, 0x7ffffffffff))); const x22 = (x20 * 0x5); const x23 = (x13 + x22); const x24 = (x23 >> 44); const x25 = (x23 & 0xfffffffffff); const x26 = (x24 + x18); const x27 = cast(u1, (x26 >> 43)); const x28 = (x26 & 0x7ffffffffff); const x29 = (cast(u64, x27) + x21); out1[0] = x25; out1[1] = x28; out1[2] = x29; } /// The function carry reduces a field element. /// Postconditions: /// eval out1 mod m = eval arg1 mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0x300000000000], [0x0 ~> 0x180000000000], [0x0 ~> 0x180000000000]] /// Output Bounds: /// out1: [[0x0 ~> 0x100000000000], [0x0 ~> 0x80000000000], [0x0 ~> 0x80000000000]] pub fn carry(out1: *[3]u64, arg1: [3]u64) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[0]); const x2 = ((x1 >> 44) + (arg1[1])); const x3 = ((x2 >> 43) + (arg1[2])); const x4 = ((x1 & 0xfffffffffff) + ((x3 >> 43) * 0x5)); const x5 = (cast(u64, cast(u1, (x4 >> 44))) + (x2 & 0x7ffffffffff)); const x6 = (x4 & 0xfffffffffff); const x7 = (x5 & 0x7ffffffffff); const x8 = (cast(u64, cast(u1, (x5 >> 43))) + (x3 & 0x7ffffffffff)); out1[0] = x6; out1[1] = x7; out1[2] = x8; } /// The function add adds two field elements. /// Postconditions: /// eval out1 mod m = (eval arg1 + eval arg2) mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0x100000000000], [0x0 ~> 0x80000000000], [0x0 ~> 0x80000000000]] /// arg2: [[0x0 ~> 0x100000000000], [0x0 ~> 0x80000000000], [0x0 ~> 0x80000000000]] /// Output Bounds: /// out1: [[0x0 ~> 0x300000000000], [0x0 ~> 0x180000000000], [0x0 ~> 0x180000000000]] pub fn add(out1: *[3]u64, arg1: [3]u64, arg2: [3]u64) void { @setRuntimeSafety(mode == .Debug); const x1 = ((arg1[0]) + (arg2[0])); const x2 = ((arg1[1]) + (arg2[1])); const x3 = ((arg1[2]) + (arg2[2])); out1[0] = x1; out1[1] = x2; out1[2] = x3; } /// The function sub subtracts two field elements. /// Postconditions: /// eval out1 mod m = (eval arg1 - eval arg2) mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0x100000000000], [0x0 ~> 0x80000000000], [0x0 ~> 0x80000000000]] /// arg2: [[0x0 ~> 0x100000000000], [0x0 ~> 0x80000000000], [0x0 ~> 0x80000000000]] /// Output Bounds: /// out1: [[0x0 ~> 0x300000000000], [0x0 ~> 0x180000000000], [0x0 ~> 0x180000000000]] pub fn sub(out1: *[3]u64, arg1: [3]u64, arg2: [3]u64) void { @setRuntimeSafety(mode == .Debug); const x1 = ((0x1ffffffffff6 + (arg1[0])) - (arg2[0])); const x2 = ((0xffffffffffe + (arg1[1])) - (arg2[1])); const x3 = ((0xffffffffffe + (arg1[2])) - (arg2[2])); out1[0] = x1; out1[1] = x2; out1[2] = x3; } /// The function opp negates a field element. /// Postconditions: /// eval out1 mod m = -eval arg1 mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0x100000000000], [0x0 ~> 0x80000000000], [0x0 ~> 0x80000000000]] /// Output Bounds: /// out1: [[0x0 ~> 0x300000000000], [0x0 ~> 0x180000000000], [0x0 ~> 0x180000000000]] pub fn opp(out1: *[3]u64, arg1: [3]u64) void { @setRuntimeSafety(mode == .Debug); const x1 = (0x1ffffffffff6 - (arg1[0])); const x2 = (0xffffffffffe - (arg1[1])); const x3 = (0xffffffffffe - (arg1[2])); out1[0] = x1; out1[1] = x2; out1[2] = x3; } /// The function selectznz is a multi-limb conditional select. /// Postconditions: /// eval out1 = (if arg1 = 0 then eval arg2 else eval arg3) /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn selectznz(out1: *[3]u64, arg1: u1, arg2: [3]u64, arg3: [3]u64) void { @setRuntimeSafety(mode == .Debug); var x1: u64 = undefined; cmovznzU64(&x1, arg1, (arg2[0]), (arg3[0])); var x2: u64 = undefined; cmovznzU64(&x2, arg1, (arg2[1]), (arg3[1])); var x3: u64 = undefined; cmovznzU64(&x3, arg1, (arg2[2]), (arg3[2])); out1[0] = x1; out1[1] = x2; out1[2] = x3; } /// The function toBytes serializes a field element to bytes in little-endian order. /// Postconditions: /// out1 = map (Ξ» x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)βŒ‹) [0..16] /// /// Input Bounds: /// arg1: [[0x0 ~> 0x100000000000], [0x0 ~> 0x80000000000], [0x0 ~> 0x80000000000]] /// Output Bounds: /// out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x3]] pub fn toBytes(out1: *[17]u8, arg1: [3]u64) void { @setRuntimeSafety(mode == .Debug); var x1: u64 = undefined; var x2: u1 = undefined; subborrowxU44(&x1, &x2, 0x0, (arg1[0]), 0xffffffffffb); var x3: u64 = undefined; var x4: u1 = undefined; subborrowxU43(&x3, &x4, x2, (arg1[1]), 0x7ffffffffff); var x5: u64 = undefined; var x6: u1 = undefined; subborrowxU43(&x5, &x6, x4, (arg1[2]), 0x7ffffffffff); var x7: u64 = undefined; cmovznzU64(&x7, x6, cast(u64, 0x0), 0xffffffffffffffff); var x8: u64 = undefined; var x9: u1 = undefined; addcarryxU44(&x8, &x9, 0x0, x1, (x7 & 0xffffffffffb)); var x10: u64 = undefined; var x11: u1 = undefined; addcarryxU43(&x10, &x11, x9, x3, (x7 & 0x7ffffffffff)); var x12: u64 = undefined; var x13: u1 = undefined; addcarryxU43(&x12, &x13, x11, x5, (x7 & 0x7ffffffffff)); const x14 = (x12 << 7); const x15 = (x10 << 4); const x16 = cast(u8, (x8 & cast(u64, 0xff))); const x17 = (x8 >> 8); const x18 = cast(u8, (x17 & cast(u64, 0xff))); const x19 = (x17 >> 8); const x20 = cast(u8, (x19 & cast(u64, 0xff))); const x21 = (x19 >> 8); const x22 = cast(u8, (x21 & cast(u64, 0xff))); const x23 = (x21 >> 8); const x24 = cast(u8, (x23 & cast(u64, 0xff))); const x25 = cast(u8, (x23 >> 8)); const x26 = (x15 + cast(u64, x25)); const x27 = cast(u8, (x26 & cast(u64, 0xff))); const x28 = (x26 >> 8); const x29 = cast(u8, (x28 & cast(u64, 0xff))); const x30 = (x28 >> 8); const x31 = cast(u8, (x30 & cast(u64, 0xff))); const x32 = (x30 >> 8); const x33 = cast(u8, (x32 & cast(u64, 0xff))); const x34 = (x32 >> 8); const x35 = cast(u8, (x34 & cast(u64, 0xff))); const x36 = cast(u8, (x34 >> 8)); const x37 = (x14 + cast(u64, x36)); const x38 = cast(u8, (x37 & cast(u64, 0xff))); const x39 = (x37 >> 8); const x40 = cast(u8, (x39 & cast(u64, 0xff))); const x41 = (x39 >> 8); const x42 = cast(u8, (x41 & cast(u64, 0xff))); const x43 = (x41 >> 8); const x44 = cast(u8, (x43 & cast(u64, 0xff))); const x45 = (x43 >> 8); const x46 = cast(u8, (x45 & cast(u64, 0xff))); const x47 = (x45 >> 8); const x48 = cast(u8, (x47 & cast(u64, 0xff))); const x49 = cast(u8, (x47 >> 8)); out1[0] = x16; out1[1] = x18; out1[2] = x20; out1[3] = x22; out1[4] = x24; out1[5] = x27; out1[6] = x29; out1[7] = x31; out1[8] = x33; out1[9] = x35; out1[10] = x38; out1[11] = x40; out1[12] = x42; out1[13] = x44; out1[14] = x46; out1[15] = x48; out1[16] = x49; } /// The function fromBytes deserializes a field element from bytes in little-endian order. /// Postconditions: /// eval out1 mod m = bytes_eval arg1 mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x3]] /// Output Bounds: /// out1: [[0x0 ~> 0x100000000000], [0x0 ~> 0x80000000000], [0x0 ~> 0x80000000000]] pub fn fromBytes(out1: *[3]u64, arg1: [17]u8) void { @setRuntimeSafety(mode == .Debug); const x1 = (cast(u64, (arg1[16])) << 41); const x2 = (cast(u64, (arg1[15])) << 33); const x3 = (cast(u64, (arg1[14])) << 25); const x4 = (cast(u64, (arg1[13])) << 17); const x5 = (cast(u64, (arg1[12])) << 9); const x6 = (cast(u64, (arg1[11])) * cast(u64, 0x2)); const x7 = (cast(u64, (arg1[10])) << 36); const x8 = (cast(u64, (arg1[9])) << 28); const x9 = (cast(u64, (arg1[8])) << 20); const x10 = (cast(u64, (arg1[7])) << 12); const x11 = (cast(u64, (arg1[6])) << 4); const x12 = (cast(u64, (arg1[5])) << 40); const x13 = (cast(u64, (arg1[4])) << 32); const x14 = (cast(u64, (arg1[3])) << 24); const x15 = (cast(u64, (arg1[2])) << 16); const x16 = (cast(u64, (arg1[1])) << 8); const x17 = (arg1[0]); const x18 = (x16 + cast(u64, x17)); const x19 = (x15 + x18); const x20 = (x14 + x19); const x21 = (x13 + x20); const x22 = (x12 + x21); const x23 = (x22 & 0xfffffffffff); const x24 = cast(u8, (x22 >> 44)); const x25 = (x11 + cast(u64, x24)); const x26 = (x10 + x25); const x27 = (x9 + x26); const x28 = (x8 + x27); const x29 = (x7 + x28); const x30 = (x29 & 0x7ffffffffff); const x31 = cast(u1, (x29 >> 43)); const x32 = (x6 + cast(u64, x31)); const x33 = (x5 + x32); const x34 = (x4 + x33); const x35 = (x3 + x34); const x36 = (x2 + x35); const x37 = (x1 + x36); out1[0] = x23; out1[1] = x30; out1[2] = x37; }
fiat-zig/src/poly1305_64.zig
const std = @import("std"); const builtin = @import("builtin"); const c = @cImport({ @cInclude("epoxy/gl.h"); @cInclude("GLFW/glfw3.h"); }); const shader = @import("shader.zig"); const SCREEN_WIDTH: u32 = 800; const SCREEN_HEIGHT: u32 = 600; fn handleKey(win: ?*c.GLFWwindow, key: c_int, scancode: c_int, action: c_int, mods: c_int) callconv(.C) void { if (action != c.GLFW_PRESS) return; switch (key) { c.GLFW_KEY_ESCAPE => c.glfwSetWindowShouldClose(win, c.GL_TRUE), else => {}, } } pub fn main() !void { const ok = c.glfwInit(); if (ok == 0) { std.debug.panic("Failed to init GLFW\n", .{}); } defer c.glfwTerminate(); c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MAJOR, 3); c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MINOR, 3); c.glfwWindowHint(c.GLFW_OPENGL_PROFILE, c.GLFW_OPENGL_CORE_PROFILE); c.glfwWindowHint(c.GLFW_OPENGL_FORWARD_COMPAT, c.GL_TRUE); c.glfwWindowHint(c.GLFW_RESIZABLE, c.GL_FALSE); var window = c.glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "Learn OpenGL", null, null); if (window == null) { std.debug.panic("Failed to create window\n", .{}); } defer c.glfwDestroyWindow(window); _ = c.glfwSetKeyCallback(window, handleKey); c.glfwMakeContextCurrent(window); const vertex_shader = try shader.loadShaderFromFile("shaders/triangle_vs.glsl", shader.ShaderKind.vertex); const fragment_shader = try shader.loadShaderFromFile("shaders/triangle_fs.glsl", shader.ShaderKind.fragment); const shader_program = c.glCreateProgram(); c.glAttachShader(shader_program, vertex_shader); c.glAttachShader(shader_program, fragment_shader); c.glLinkProgram(shader_program); // TODO: check info log here c.glDeleteShader(vertex_shader); c.glDeleteShader(fragment_shader); const vertices = [_]f32{ 0.5, 0.5, 0.0, 0.5, -0.5, 0.0, -0.5, -0.5, 0.0, -0.5, 0.5, 0.0, }; const indices = [_]u32{ 0, 1, 3, 1, 2, 3, }; var vao: c_uint = undefined; c.glGenVertexArrays(1, &vao); defer c.glDeleteVertexArrays(1, &vao); var vbo: c_uint = undefined; c.glGenBuffers(1, &vbo); defer c.glDeleteBuffers(1, &vbo); var ebo: c_uint = undefined; c.glGenBuffers(1, &ebo); defer c.glDeleteBuffers(1, &ebo); c.glBindVertexArray(vao); c.glBindBuffer(c.GL_ARRAY_BUFFER, vbo); c.glBufferData(c.GL_ARRAY_BUFFER, vertices.len * @sizeOf(f32), &vertices, c.GL_STATIC_DRAW); c.glBindBuffer(c.GL_ELEMENT_ARRAY_BUFFER, ebo); c.glBufferData(c.GL_ELEMENT_ARRAY_BUFFER, indices.len * @sizeOf(u32), &indices, c.GL_STATIC_DRAW); c.glVertexAttribPointer(0, 3, c.GL_FLOAT, c.GL_FALSE, 3 * @sizeOf(f32), null); c.glEnableVertexAttribArray(0); c.glBindBuffer(c.GL_ARRAY_BUFFER, 0); c.glBindVertexArray(0); while (c.glfwWindowShouldClose(window) == c.GL_FALSE) { c.glClearColor(0.2, 0.1, 0.2, 1.0); c.glClear(c.GL_COLOR_BUFFER_BIT); c.glUseProgram(shader_program); c.glBindVertexArray(vao); c.glDrawElements(c.GL_TRIANGLES, 6, c.GL_UNSIGNED_INT, null); c.glfwSwapBuffers(window); c.glfwPollEvents(); } }
src/triangle.zig
//-------------------------------------------------------------------------------- // Section: Types (19) //-------------------------------------------------------------------------------- const CLSID_CInitiateWinSAT_Value = @import("../zig.zig").Guid.initString("489331dc-f5e0-4528-9fda-45331bf4a571"); pub const CLSID_CInitiateWinSAT = &CLSID_CInitiateWinSAT_Value; const CLSID_CQueryWinSAT_Value = @import("../zig.zig").Guid.initString("f3bdfad3-f276-49e9-9b17-c474f48f0764"); pub const CLSID_CQueryWinSAT = &CLSID_CQueryWinSAT_Value; const CLSID_CQueryAllWinSAT_Value = @import("../zig.zig").Guid.initString("05df8d13-c355-47f4-a11e-851b338cefb8"); pub const CLSID_CQueryAllWinSAT = &CLSID_CQueryAllWinSAT_Value; const CLSID_CProvideWinSATVisuals_Value = @import("../zig.zig").Guid.initString("9f377d7e-e551-44f8-9f94-9db392b03b7b"); pub const CLSID_CProvideWinSATVisuals = &CLSID_CProvideWinSATVisuals_Value; const CLSID_CAccessiblityWinSAT_Value = @import("../zig.zig").Guid.initString("6e18f9c6-a3eb-495a-89b7-956482e19f7a"); pub const CLSID_CAccessiblityWinSAT = &CLSID_CAccessiblityWinSAT_Value; const CLSID_CQueryOEMWinSATCustomization_Value = @import("../zig.zig").Guid.initString("c47a41b7-b729-424f-9af9-5cb3934f2dfa"); pub const CLSID_CQueryOEMWinSATCustomization = &CLSID_CQueryOEMWinSATCustomization_Value; pub const WINSAT_OEM_DATA_TYPE = enum(i32) { DATA_VALID = 0, DATA_NON_SYS_CONFIG_MATCH = 1, DATA_INVALID = 2, NO_DATA_SUPPLIED = 3, }; pub const WINSAT_OEM_DATA_VALID = WINSAT_OEM_DATA_TYPE.DATA_VALID; pub const WINSAT_OEM_DATA_NON_SYS_CONFIG_MATCH = WINSAT_OEM_DATA_TYPE.DATA_NON_SYS_CONFIG_MATCH; pub const WINSAT_OEM_DATA_INVALID = WINSAT_OEM_DATA_TYPE.DATA_INVALID; pub const WINSAT_OEM_NO_DATA_SUPPLIED = WINSAT_OEM_DATA_TYPE.NO_DATA_SUPPLIED; pub const WINSAT_ASSESSMENT_STATE = enum(i32) { MIN = 0, // UNKNOWN = 0, this enum value conflicts with MIN VALID = 1, INCOHERENT_WITH_HARDWARE = 2, NOT_AVAILABLE = 3, INVALID = 4, // MAX = 4, this enum value conflicts with INVALID }; pub const WINSAT_ASSESSMENT_STATE_MIN = WINSAT_ASSESSMENT_STATE.MIN; pub const WINSAT_ASSESSMENT_STATE_UNKNOWN = WINSAT_ASSESSMENT_STATE.MIN; pub const WINSAT_ASSESSMENT_STATE_VALID = WINSAT_ASSESSMENT_STATE.VALID; pub const WINSAT_ASSESSMENT_STATE_INCOHERENT_WITH_HARDWARE = WINSAT_ASSESSMENT_STATE.INCOHERENT_WITH_HARDWARE; pub const WINSAT_ASSESSMENT_STATE_NOT_AVAILABLE = WINSAT_ASSESSMENT_STATE.NOT_AVAILABLE; pub const WINSAT_ASSESSMENT_STATE_INVALID = WINSAT_ASSESSMENT_STATE.INVALID; pub const WINSAT_ASSESSMENT_STATE_MAX = WINSAT_ASSESSMENT_STATE.INVALID; pub const WINSAT_ASSESSMENT_TYPE = enum(i32) { MEMORY = 0, CPU = 1, DISK = 2, D3D = 3, GRAPHICS = 4, }; pub const WINSAT_ASSESSMENT_MEMORY = WINSAT_ASSESSMENT_TYPE.MEMORY; pub const WINSAT_ASSESSMENT_CPU = WINSAT_ASSESSMENT_TYPE.CPU; pub const WINSAT_ASSESSMENT_DISK = WINSAT_ASSESSMENT_TYPE.DISK; pub const WINSAT_ASSESSMENT_D3D = WINSAT_ASSESSMENT_TYPE.D3D; pub const WINSAT_ASSESSMENT_GRAPHICS = WINSAT_ASSESSMENT_TYPE.GRAPHICS; pub const WINSAT_BITMAP_SIZE = enum(i32) { SMALL = 0, NORMAL = 1, }; pub const WINSAT_BITMAP_SIZE_SMALL = WINSAT_BITMAP_SIZE.SMALL; pub const WINSAT_BITMAP_SIZE_NORMAL = WINSAT_BITMAP_SIZE.NORMAL; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IProvideWinSATAssessmentInfo_Value = @import("../zig.zig").Guid.initString("0cd1c380-52d3-4678-ac6f-e929e480be9e"); pub const IID_IProvideWinSATAssessmentInfo = &IID_IProvideWinSATAssessmentInfo_Value; pub const IProvideWinSATAssessmentInfo = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Score: fn( self: *const IProvideWinSATAssessmentInfo, score: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Title: fn( self: *const IProvideWinSATAssessmentInfo, title: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Description: fn( self: *const IProvideWinSATAssessmentInfo, description: ?*?BSTR, ) 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 IProvideWinSATAssessmentInfo_get_Score(self: *const T, score: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IProvideWinSATAssessmentInfo.VTable, self.vtable).get_Score(@ptrCast(*const IProvideWinSATAssessmentInfo, self), score); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProvideWinSATAssessmentInfo_get_Title(self: *const T, title: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IProvideWinSATAssessmentInfo.VTable, self.vtable).get_Title(@ptrCast(*const IProvideWinSATAssessmentInfo, self), title); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProvideWinSATAssessmentInfo_get_Description(self: *const T, description: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IProvideWinSATAssessmentInfo.VTable, self.vtable).get_Description(@ptrCast(*const IProvideWinSATAssessmentInfo, self), description); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IProvideWinSATResultsInfo_Value = @import("../zig.zig").Guid.initString("f8334d5d-568e-4075-875f-9df341506640"); pub const IID_IProvideWinSATResultsInfo = &IID_IProvideWinSATResultsInfo_Value; pub const IProvideWinSATResultsInfo = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, GetAssessmentInfo: fn( self: *const IProvideWinSATResultsInfo, assessment: WINSAT_ASSESSMENT_TYPE, ppinfo: ?*?*IProvideWinSATAssessmentInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AssessmentState: fn( self: *const IProvideWinSATResultsInfo, state: ?*WINSAT_ASSESSMENT_STATE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AssessmentDateTime: fn( self: *const IProvideWinSATResultsInfo, fileTime: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SystemRating: fn( self: *const IProvideWinSATResultsInfo, level: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RatingStateDesc: fn( self: *const IProvideWinSATResultsInfo, description: ?*?BSTR, ) 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 IProvideWinSATResultsInfo_GetAssessmentInfo(self: *const T, assessment: WINSAT_ASSESSMENT_TYPE, ppinfo: ?*?*IProvideWinSATAssessmentInfo) callconv(.Inline) HRESULT { return @ptrCast(*const IProvideWinSATResultsInfo.VTable, self.vtable).GetAssessmentInfo(@ptrCast(*const IProvideWinSATResultsInfo, self), assessment, ppinfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProvideWinSATResultsInfo_get_AssessmentState(self: *const T, state: ?*WINSAT_ASSESSMENT_STATE) callconv(.Inline) HRESULT { return @ptrCast(*const IProvideWinSATResultsInfo.VTable, self.vtable).get_AssessmentState(@ptrCast(*const IProvideWinSATResultsInfo, self), state); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProvideWinSATResultsInfo_get_AssessmentDateTime(self: *const T, fileTime: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IProvideWinSATResultsInfo.VTable, self.vtable).get_AssessmentDateTime(@ptrCast(*const IProvideWinSATResultsInfo, self), fileTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProvideWinSATResultsInfo_get_SystemRating(self: *const T, level: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IProvideWinSATResultsInfo.VTable, self.vtable).get_SystemRating(@ptrCast(*const IProvideWinSATResultsInfo, self), level); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProvideWinSATResultsInfo_get_RatingStateDesc(self: *const T, description: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IProvideWinSATResultsInfo.VTable, self.vtable).get_RatingStateDesc(@ptrCast(*const IProvideWinSATResultsInfo, self), description); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IQueryRecentWinSATAssessment_Value = @import("../zig.zig").Guid.initString("f8ad5d1f-3b47-4bdc-9375-7c6b1da4eca7"); pub const IID_IQueryRecentWinSATAssessment = &IID_IQueryRecentWinSATAssessment_Value; pub const IQueryRecentWinSATAssessment = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_XML: fn( self: *const IQueryRecentWinSATAssessment, xPath: ?BSTR, namespaces: ?BSTR, ppDomNodeList: ?*?*IXMLDOMNodeList, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Info: fn( self: *const IQueryRecentWinSATAssessment, ppWinSATAssessmentInfo: ?*?*IProvideWinSATResultsInfo, ) 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 IQueryRecentWinSATAssessment_get_XML(self: *const T, xPath: ?BSTR, namespaces: ?BSTR, ppDomNodeList: ?*?*IXMLDOMNodeList) callconv(.Inline) HRESULT { return @ptrCast(*const IQueryRecentWinSATAssessment.VTable, self.vtable).get_XML(@ptrCast(*const IQueryRecentWinSATAssessment, self), xPath, namespaces, ppDomNodeList); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IQueryRecentWinSATAssessment_get_Info(self: *const T, ppWinSATAssessmentInfo: ?*?*IProvideWinSATResultsInfo) callconv(.Inline) HRESULT { return @ptrCast(*const IQueryRecentWinSATAssessment.VTable, self.vtable).get_Info(@ptrCast(*const IQueryRecentWinSATAssessment, self), ppWinSATAssessmentInfo); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IProvideWinSATVisuals_Value = @import("../zig.zig").Guid.initString("a9f4ade0-871a-42a3-b813-3078d25162c9"); pub const IID_IProvideWinSATVisuals = &IID_IProvideWinSATVisuals_Value; pub const IProvideWinSATVisuals = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Bitmap: fn( self: *const IProvideWinSATVisuals, bitmapSize: WINSAT_BITMAP_SIZE, state: WINSAT_ASSESSMENT_STATE, rating: f32, pBitmap: ?*?HBITMAP, ) 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 IProvideWinSATVisuals_get_Bitmap(self: *const T, bitmapSize: WINSAT_BITMAP_SIZE, state: WINSAT_ASSESSMENT_STATE, rating: f32, pBitmap: ?*?HBITMAP) callconv(.Inline) HRESULT { return @ptrCast(*const IProvideWinSATVisuals.VTable, self.vtable).get_Bitmap(@ptrCast(*const IProvideWinSATVisuals, self), bitmapSize, state, rating, pBitmap); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IQueryAllWinSATAssessments_Value = @import("../zig.zig").Guid.initString("0b89ed1d-6398-4fea-87fc-567d8d19176f"); pub const IID_IQueryAllWinSATAssessments = &IID_IQueryAllWinSATAssessments_Value; pub const IQueryAllWinSATAssessments = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AllXML: fn( self: *const IQueryAllWinSATAssessments, xPath: ?BSTR, namespaces: ?BSTR, ppDomNodeList: ?*?*IXMLDOMNodeList, ) 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 IQueryAllWinSATAssessments_get_AllXML(self: *const T, xPath: ?BSTR, namespaces: ?BSTR, ppDomNodeList: ?*?*IXMLDOMNodeList) callconv(.Inline) HRESULT { return @ptrCast(*const IQueryAllWinSATAssessments.VTable, self.vtable).get_AllXML(@ptrCast(*const IQueryAllWinSATAssessments, self), xPath, namespaces, ppDomNodeList); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWinSATInitiateEvents_Value = @import("../zig.zig").Guid.initString("262a1918-ba0d-41d5-92c2-fab4633ee74f"); pub const IID_IWinSATInitiateEvents = &IID_IWinSATInitiateEvents_Value; pub const IWinSATInitiateEvents = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, WinSATComplete: fn( self: *const IWinSATInitiateEvents, hresult: HRESULT, strDescription: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WinSATUpdate: fn( self: *const IWinSATInitiateEvents, uCurrentTick: u32, uTickTotal: u32, strCurrentState: ?[*:0]const u16, ) 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 IWinSATInitiateEvents_WinSATComplete(self: *const T, hresult: HRESULT, strDescription: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWinSATInitiateEvents.VTable, self.vtable).WinSATComplete(@ptrCast(*const IWinSATInitiateEvents, self), hresult, strDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWinSATInitiateEvents_WinSATUpdate(self: *const T, uCurrentTick: u32, uTickTotal: u32, strCurrentState: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWinSATInitiateEvents.VTable, self.vtable).WinSATUpdate(@ptrCast(*const IWinSATInitiateEvents, self), uCurrentTick, uTickTotal, strCurrentState); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IInitiateWinSATAssessment_Value = @import("../zig.zig").Guid.initString("d983fc50-f5bf-49d5-b5ed-cccb18aa7fc1"); pub const IID_IInitiateWinSATAssessment = &IID_IInitiateWinSATAssessment_Value; pub const IInitiateWinSATAssessment = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, InitiateAssessment: fn( self: *const IInitiateWinSATAssessment, cmdLine: ?[*:0]const u16, pCallbacks: ?*IWinSATInitiateEvents, callerHwnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InitiateFormalAssessment: fn( self: *const IInitiateWinSATAssessment, pCallbacks: ?*IWinSATInitiateEvents, callerHwnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CancelAssessment: fn( self: *const IInitiateWinSATAssessment, ) 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 IInitiateWinSATAssessment_InitiateAssessment(self: *const T, cmdLine: ?[*:0]const u16, pCallbacks: ?*IWinSATInitiateEvents, callerHwnd: ?HWND) callconv(.Inline) HRESULT { return @ptrCast(*const IInitiateWinSATAssessment.VTable, self.vtable).InitiateAssessment(@ptrCast(*const IInitiateWinSATAssessment, self), cmdLine, pCallbacks, callerHwnd); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInitiateWinSATAssessment_InitiateFormalAssessment(self: *const T, pCallbacks: ?*IWinSATInitiateEvents, callerHwnd: ?HWND) callconv(.Inline) HRESULT { return @ptrCast(*const IInitiateWinSATAssessment.VTable, self.vtable).InitiateFormalAssessment(@ptrCast(*const IInitiateWinSATAssessment, self), pCallbacks, callerHwnd); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInitiateWinSATAssessment_CancelAssessment(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IInitiateWinSATAssessment.VTable, self.vtable).CancelAssessment(@ptrCast(*const IInitiateWinSATAssessment, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IAccessibleWinSAT_Value = @import("../zig.zig").Guid.initString("30e6018a-94a8-4ff8-a69a-71b67413f07b"); pub const IID_IAccessibleWinSAT = &IID_IAccessibleWinSAT_Value; pub const IAccessibleWinSAT = extern struct { pub const VTable = extern struct { base: IAccessible.VTable, SetAccessiblityData: fn( self: *const IAccessibleWinSAT, wsName: ?[*:0]const u16, wsValue: ?[*:0]const u16, wsDesc: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IAccessible.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAccessibleWinSAT_SetAccessiblityData(self: *const T, wsName: ?[*:0]const u16, wsValue: ?[*:0]const u16, wsDesc: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IAccessibleWinSAT.VTable, self.vtable).SetAccessiblityData(@ptrCast(*const IAccessibleWinSAT, self), wsName, wsValue, wsDesc); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IQueryOEMWinSATCustomization_Value = @import("../zig.zig").Guid.initString("bc9a6a9f-ad4e-420e-9953-b34671e9df22"); pub const IID_IQueryOEMWinSATCustomization = &IID_IQueryOEMWinSATCustomization_Value; pub const IQueryOEMWinSATCustomization = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetOEMPrePopulationInfo: fn( self: *const IQueryOEMWinSATCustomization, state: ?*WINSAT_OEM_DATA_TYPE, ) 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 IQueryOEMWinSATCustomization_GetOEMPrePopulationInfo(self: *const T, state: ?*WINSAT_OEM_DATA_TYPE) callconv(.Inline) HRESULT { return @ptrCast(*const IQueryOEMWinSATCustomization.VTable, self.vtable).GetOEMPrePopulationInfo(@ptrCast(*const IQueryOEMWinSATCustomization, self), state); } };} 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 (10) //-------------------------------------------------------------------------------- const BSTR = @import("../foundation.zig").BSTR; const HBITMAP = @import("../graphics/gdi.zig").HBITMAP; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const IAccessible = @import("../ui/accessibility.zig").IAccessible; const IDispatch = @import("../system/com.zig").IDispatch; const IUnknown = @import("../system/com.zig").IUnknown; const IXMLDOMNodeList = @import("../data/xml/ms_xml.zig").IXMLDOMNodeList; const PWSTR = @import("../foundation.zig").PWSTR; const VARIANT = @import("../system/com.zig").VARIANT; 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/system/assessment_tool.zig
const std = @import("std"); const assert = std.debug.assert; const log = std.log.scoped(.reloc); const macho = std.macho; const math = std.math; const mem = std.mem; const meta = std.meta; const reloc = @import("../reloc.zig"); const Allocator = mem.Allocator; const Relocation = reloc.Relocation; const Symbol = @import("../Symbol.zig"); pub const Branch = struct { base: Relocation, pub const base_type: Relocation.Type = .branch_x86_64; pub fn resolve(branch: Branch, args: Relocation.ResolveArgs) !void { const displacement = try math.cast(i32, @intCast(i64, args.target_addr) - @intCast(i64, args.source_addr) - 4); log.debug(" | displacement 0x{x}", .{displacement}); mem.writeIntLittle(u32, branch.base.code[0..4], @bitCast(u32, displacement)); } }; pub const Signed = struct { base: Relocation, addend: i32, correction: i4, pub const base_type: Relocation.Type = .signed; pub fn resolve(signed: Signed, args: Relocation.ResolveArgs) !void { const target_addr = target_addr: { if (signed.base.target == .section) { const source_target = @intCast(i64, args.source_source_sect_addr.?) + @intCast(i64, signed.base.offset) + signed.addend + 4; const source_disp = source_target - @intCast(i64, args.source_target_sect_addr.?); break :target_addr @intCast(i64, args.target_addr) + source_disp; } break :target_addr @intCast(i64, args.target_addr) + signed.addend; }; const displacement = try math.cast( i32, target_addr - @intCast(i64, args.source_addr) - signed.correction - 4, ); log.debug(" | addend 0x{x}", .{signed.addend}); log.debug(" | correction 0x{x}", .{signed.correction}); log.debug(" | displacement 0x{x}", .{displacement}); mem.writeIntLittle(u32, signed.base.code[0..4], @bitCast(u32, displacement)); } }; pub const GotLoad = struct { base: Relocation, pub const base_type: Relocation.Type = .got_load; pub fn resolve(got_load: GotLoad, args: Relocation.ResolveArgs) !void { const displacement = try math.cast(i32, @intCast(i64, args.target_addr) - @intCast(i64, args.source_addr) - 4); log.debug(" | displacement 0x{x}", .{displacement}); mem.writeIntLittle(u32, got_load.base.code[0..4], @bitCast(u32, displacement)); } }; pub const Got = struct { base: Relocation, addend: i32, pub const base_type: Relocation.Type = .got; pub fn resolve(got: Got, args: Relocation.ResolveArgs) !void { const displacement = try math.cast( i32, @intCast(i64, args.target_addr) - @intCast(i64, args.source_addr) - 4 + got.addend, ); log.debug(" | displacement 0x{x}", .{displacement}); mem.writeIntLittle(u32, got.base.code[0..4], @bitCast(u32, displacement)); } }; pub const Tlv = struct { base: Relocation, op: *u8, pub const base_type: Relocation.Type = .tlv; pub fn resolve(tlv: Tlv, args: Relocation.ResolveArgs) !void { // We need to rewrite the opcode from movq to leaq. tlv.op.* = 0x8d; log.debug(" | rewriting op to leaq", .{}); const displacement = try math.cast(i32, @intCast(i64, args.target_addr) - @intCast(i64, args.source_addr) - 4); log.debug(" | displacement 0x{x}", .{displacement}); mem.writeIntLittle(u32, tlv.base.code[0..4], @bitCast(u32, displacement)); } }; pub const Parser = struct { allocator: *Allocator, it: *reloc.RelocIterator, code: []u8, parsed: std.ArrayList(*Relocation), symbols: []*Symbol, subtractor: ?Relocation.Target = null, pub fn deinit(parser: *Parser) void { parser.parsed.deinit(); } pub fn parse(parser: *Parser) !void { while (parser.it.next()) |rel| { switch (@intToEnum(macho.reloc_type_x86_64, rel.r_type)) { .X86_64_RELOC_BRANCH => { try parser.parseBranch(rel); }, .X86_64_RELOC_SUBTRACTOR => { try parser.parseSubtractor(rel); }, .X86_64_RELOC_UNSIGNED => { try parser.parseUnsigned(rel); }, .X86_64_RELOC_SIGNED, .X86_64_RELOC_SIGNED_1, .X86_64_RELOC_SIGNED_2, .X86_64_RELOC_SIGNED_4, => { try parser.parseSigned(rel); }, .X86_64_RELOC_GOT_LOAD => { try parser.parseGotLoad(rel); }, .X86_64_RELOC_GOT => { try parser.parseGot(rel); }, .X86_64_RELOC_TLV => { try parser.parseTlv(rel); }, } } } fn parseBranch(parser: *Parser, rel: macho.relocation_info) !void { const rel_type = @intToEnum(macho.reloc_type_x86_64, rel.r_type); assert(rel_type == .X86_64_RELOC_BRANCH); assert(rel.r_pcrel == 1); assert(rel.r_length == 2); const offset = @intCast(u32, rel.r_address); const inst = parser.code[offset..][0..4]; var branch = try parser.allocator.create(Branch); errdefer parser.allocator.destroy(branch); const target = Relocation.Target.from_reloc(rel, parser.symbols); branch.* = .{ .base = .{ .@"type" = .branch_x86_64, .code = inst, .offset = offset, .target = target, }, }; log.debug(" | emitting {}", .{branch}); try parser.parsed.append(&branch.base); } fn parseSigned(parser: *Parser, rel: macho.relocation_info) !void { assert(rel.r_pcrel == 1); assert(rel.r_length == 2); const rel_type = @intToEnum(macho.reloc_type_x86_64, rel.r_type); const target = Relocation.Target.from_reloc(rel, parser.symbols); const is_extern = rel.r_extern == 1; const offset = @intCast(u32, rel.r_address); const inst = parser.code[offset..][0..4]; const correction: i4 = switch (rel_type) { .X86_64_RELOC_SIGNED => 0, .X86_64_RELOC_SIGNED_1 => 1, .X86_64_RELOC_SIGNED_2 => 2, .X86_64_RELOC_SIGNED_4 => 4, else => unreachable, }; const addend = mem.readIntLittle(i32, inst) + correction; var signed = try parser.allocator.create(Signed); errdefer parser.allocator.destroy(signed); signed.* = .{ .base = .{ .@"type" = .signed, .code = inst, .offset = offset, .target = target, }, .addend = addend, .correction = correction, }; log.debug(" | emitting {}", .{signed}); try parser.parsed.append(&signed.base); } fn parseGotLoad(parser: *Parser, rel: macho.relocation_info) !void { const rel_type = @intToEnum(macho.reloc_type_x86_64, rel.r_type); assert(rel_type == .X86_64_RELOC_GOT_LOAD); assert(rel.r_pcrel == 1); assert(rel.r_length == 2); const offset = @intCast(u32, rel.r_address); const inst = parser.code[offset..][0..4]; const target = Relocation.Target.from_reloc(rel, parser.symbols); var got_load = try parser.allocator.create(GotLoad); errdefer parser.allocator.destroy(got_load); got_load.* = .{ .base = .{ .@"type" = .got_load, .code = inst, .offset = offset, .target = target, }, }; log.debug(" | emitting {}", .{got_load}); try parser.parsed.append(&got_load.base); } fn parseGot(parser: *Parser, rel: macho.relocation_info) !void { const rel_type = @intToEnum(macho.reloc_type_x86_64, rel.r_type); assert(rel_type == .X86_64_RELOC_GOT); assert(rel.r_pcrel == 1); assert(rel.r_length == 2); const offset = @intCast(u32, rel.r_address); const inst = parser.code[offset..][0..4]; const target = Relocation.Target.from_reloc(rel, parser.symbols); const addend = mem.readIntLittle(i32, inst); var got = try parser.allocator.create(Got); errdefer parser.allocator.destroy(got); got.* = .{ .base = .{ .@"type" = .got, .code = inst, .offset = offset, .target = target, }, .addend = addend, }; log.debug(" | emitting {}", .{got}); try parser.parsed.append(&got.base); } fn parseTlv(parser: *Parser, rel: macho.relocation_info) !void { const rel_type = @intToEnum(macho.reloc_type_x86_64, rel.r_type); assert(rel_type == .X86_64_RELOC_TLV); assert(rel.r_pcrel == 1); assert(rel.r_length == 2); const offset = @intCast(u32, rel.r_address); const inst = parser.code[offset..][0..4]; const target = Relocation.Target.from_reloc(rel, parser.symbols); var tlv = try parser.allocator.create(Tlv); errdefer parser.allocator.destroy(tlv); tlv.* = .{ .base = .{ .@"type" = .tlv, .code = inst, .offset = offset, .target = target, }, .op = &parser.code[offset - 2], }; log.debug(" | emitting {}", .{tlv}); try parser.parsed.append(&tlv.base); } fn parseSubtractor(parser: *Parser, rel: macho.relocation_info) !void { const rel_type = @intToEnum(macho.reloc_type_x86_64, rel.r_type); assert(rel_type == .X86_64_RELOC_SUBTRACTOR); assert(rel.r_pcrel == 0); assert(parser.subtractor == null); parser.subtractor = Relocation.Target.from_reloc(rel, parser.symbols); // Verify SUBTRACTOR is followed by UNSIGNED. const next = @intToEnum(macho.reloc_type_x86_64, parser.it.peek().r_type); if (next != .X86_64_RELOC_UNSIGNED) { log.err("unexpected relocation type: expected UNSIGNED, found {s}", .{next}); return error.UnexpectedRelocationType; } } fn parseUnsigned(parser: *Parser, rel: macho.relocation_info) !void { defer { // Reset parser's subtractor state parser.subtractor = null; } const rel_type = @intToEnum(macho.reloc_type_x86_64, rel.r_type); assert(rel_type == .X86_64_RELOC_UNSIGNED); assert(rel.r_pcrel == 0); var unsigned = try parser.allocator.create(reloc.Unsigned); errdefer parser.allocator.destroy(unsigned); const target = Relocation.Target.from_reloc(rel, parser.symbols); const is_64bit: bool = switch (rel.r_length) { 3 => true, 2 => false, else => unreachable, }; const offset = @intCast(u32, rel.r_address); const addend: i64 = if (is_64bit) mem.readIntLittle(i64, parser.code[offset..][0..8]) else mem.readIntLittle(i32, parser.code[offset..][0..4]); unsigned.* = .{ .base = .{ .@"type" = .unsigned, .code = if (is_64bit) parser.code[offset..][0..8] else parser.code[offset..][0..4], .offset = offset, .target = target, }, .subtractor = parser.subtractor, .is_64bit = is_64bit, .addend = addend, }; log.debug(" | emitting {}", .{unsigned}); try parser.parsed.append(&unsigned.base); } };
src/link/MachO/reloc/x86_64.zig
const midi = @import("../midi.zig"); const std = @import("std"); const debug = std.debug; const io = std.io; const math = std.math; const mem = std.mem; const decode = @This(); fn statusByte(b: u8) ?u7 { if (@truncate(u1, b >> 7) != 0) return @truncate(u7, b); return null; } fn readDataByte(reader: anytype) !u7 { return math.cast(u7, try reader.readByte()) catch return error.InvalidDataByte; } pub fn message(reader: anytype, last_message: ?midi.Message) !midi.Message { var first_byte: ?u8 = try reader.readByte(); const status_byte = if (statusByte(first_byte.?)) |status_byte| blk: { first_byte = null; break :blk status_byte; } else if (last_message) |m| blk: { if (m.channel() == null) return error.InvalidMessage; break :blk m.status; } else return error.InvalidMessage; const kind = @truncate(u3, status_byte >> 4); const channel = @truncate(u4, status_byte); switch (kind) { 0x0, 0x1, 0x2, 0x3, 0x6 => return midi.Message{ .status = status_byte, .values = [2]u7{ math.cast(u7, first_byte orelse try reader.readByte()) catch return error.InvalidDataByte, try readDataByte(reader), }, }, 0x4, 0x5 => return midi.Message{ .status = status_byte, .values = [2]u7{ math.cast(u7, first_byte orelse try reader.readByte()) catch return error.InvalidDataByte, 0, }, }, 0x7 => { debug.assert(first_byte == null); switch (channel) { 0x0, 0x6, 0x07, 0x8, 0xA, 0xB, 0xC, 0xE, 0xF => return midi.Message{ .status = status_byte, .values = [2]u7{ 0, 0 }, }, 0x1, 0x3 => return midi.Message{ .status = status_byte, .values = [2]u7{ try readDataByte(reader), 0, }, }, 0x2 => return midi.Message{ .status = status_byte, .values = [2]u7{ try readDataByte(reader), try readDataByte(reader), }, }, // Undefined 0x4, 0x5, 0x9, 0xD => return midi.Message{ .status = status_byte, .values = [2]u7{ 0, 0 }, }, } }, } } pub fn chunk(reader: anytype) !midi.file.Chunk { var buf: [8]u8 = undefined; try reader.readNoEof(&buf); return decode.chunkFromBytes(buf); } pub fn chunkFromBytes(bytes: [8]u8) midi.file.Chunk { return midi.file.Chunk{ .kind = bytes[0..4].*, .len = mem.readIntBig(u32, bytes[4..8]), }; } pub fn fileHeader(reader: anytype) !midi.file.Header { var buf: [14]u8 = undefined; try reader.readNoEof(&buf); return decode.fileHeaderFromBytes(buf); } pub fn fileHeaderFromBytes(bytes: [14]u8) !midi.file.Header { const _chunk = decode.chunkFromBytes(bytes[0..8].*); if (!mem.eql(u8, &_chunk.kind, midi.file.Chunk.file_header)) return error.InvalidFileHeader; if (_chunk.len < midi.file.Header.size) return error.InvalidFileHeader; return midi.file.Header{ .chunk = _chunk, .format = mem.readIntBig(u16, bytes[8..10]), .tracks = mem.readIntBig(u16, bytes[10..12]), .division = mem.readIntBig(u16, bytes[12..14]), }; } pub fn int(reader: anytype) !u28 { var res: u28 = 0; while (true) { const b = try reader.readByte(); const is_last = @truncate(u1, b >> 7) == 0; const value = @truncate(u7, b); res = try math.mul(u28, res, math.maxInt(u7) + 1); res = try math.add(u28, res, value); if (is_last) return res; } } pub fn metaEvent(reader: anytype) !midi.file.MetaEvent { return midi.file.MetaEvent{ .kind_byte = try reader.readByte(), .len = try decode.int(reader), }; } pub fn trackEvent(reader: anytype, last_event: ?midi.file.TrackEvent) !midi.file.TrackEvent { var peek_reader = io.peekStream(1, reader); var in_reader = peek_reader.reader(); const delta_time = try decode.int(&in_reader); const first_byte = try in_reader.readByte(); if (first_byte == 0xFF) { return midi.file.TrackEvent{ .delta_time = delta_time, .kind = midi.file.TrackEvent.Kind{ .MetaEvent = try decode.metaEvent(&in_reader) }, }; } const last_midi_event = if (last_event) |e| switch (e.kind) { .MidiEvent => |m| m, .MetaEvent => null, } else null; peek_reader.putBackByte(first_byte) catch unreachable; return midi.file.TrackEvent{ .delta_time = delta_time, .kind = midi.file.TrackEvent.Kind{ .MidiEvent = try decode.message(&in_reader, last_midi_event) }, }; } /// Decodes a midi file from a reader. Caller owns the returned value /// (see: `midi.File.deinit`). pub fn file(reader: anytype, allocator: *mem.Allocator) !midi.File { var chunks = std.ArrayList(midi.File.FileChunk).init(allocator); errdefer { (midi.File{ .format = 0, .division = 0, .chunks = chunks.toOwnedSlice(), }).deinit(allocator); } const header = try decode.fileHeader(reader); const header_data = try allocator.alloc(u8, header.chunk.len - midi.file.Header.size); errdefer allocator.free(header_data); try reader.readNoEof(header_data); while (true) { const c = decode.chunk(reader) catch |err| switch (err) { error.EndOfStream => break, else => |e| return e, }; const chunk_bytes = try allocator.alloc(u8, c.len); errdefer allocator.free(chunk_bytes); try reader.readNoEof(chunk_bytes); try chunks.append(.{ .kind = c.kind, .bytes = chunk_bytes, }); } return midi.File{ .format = header.format, .division = header.division, .header_data = header_data, .chunks = chunks.toOwnedSlice(), }; }
midi/decode.zig
const std = @import("std"); const builtin = @import("builtin"); const assert = std.debug.assert; pub fn Dense(comptime T: type) type { return DenseCustomSlot(T, u16, u16); } pub fn DenseCustomSlot(comptime T: type, comptime slot_index_type: type, comptime slot_salt_type: type) type { // Both slot index and salt must be unsigned const index_info = @typeInfo(slot_index_type); assert(index_info.Int.signedness == .unsigned); const salt_info = @typeInfo(slot_salt_type); assert(salt_info.Int.signedness == .unsigned); return struct { const Self = @This(); const SlotList = std.ArrayList(Slot); const TList = std.ArrayList(T); const IndexList = std.ArrayList(usize); slots: SlotList, data: TList, erase: IndexList, next_free: slot_index_type, len: usize, pub const Slot = SlotType(slot_index_type, slot_salt_type); pub fn init(allocator: *std.mem.Allocator) Self { return Self{ .slots = SlotList.init(allocator), .data = TList.init(allocator), .erase = IndexList.init(allocator), .next_free = 0, .len = 0, }; } pub fn deinit(self: *Self) void { self.slots.deinit(); self.data.deinit(); self.erase.deinit(); } pub fn capacity(self: *Self) usize { return self.slots.items.len; } pub fn ensureCapacity(self: *Self, new_capacity: usize) !void { std.debug.assert(new_capacity < std.math.maxInt(slot_index_type)); if (self.slots.items.len < new_capacity) { var previous_last = self.slots.items.len; try self.slots.resize(new_capacity); try self.data.resize(new_capacity); try self.erase.resize(new_capacity); // add new items to the freelist for (self.slots.items[previous_last..self.slots.items.len]) |*slot, index| { slot.index = @intCast(slot_index_type, index + previous_last) + 1; slot.salt = 1; } } } pub fn clear(self: *Self) void { self.next_free = 0; self.len = 0; for (self.slots.items[self.next_free..self.slots.items.len]) |*slot, index| { slot.index = @intCast(slot_index_type, index + 1); slot.salt = slot.salt +% 1; if (slot.salt == 0) { slot.salt = 1; } } } pub fn insert(self: *Self, v: T) !Slot { try self.ensureCapacity(self.len + 1); var index_of_redirect = self.next_free; var redirect = &self.slots.items[index_of_redirect]; self.next_free = redirect.index; // redirect.index points to the next free slot redirect.index = @intCast(slot_index_type, self.len); self.data.items[redirect.index] = v; self.erase.items[redirect.index] = index_of_redirect; self.len += 1; return Slot{ .index = index_of_redirect, .salt = redirect.salt, }; } pub fn remove(self: *Self, slot: Slot) !void { if (!slot.is_valid()) { return error.INVALID_PARAMETER; } var redirect = &self.slots.items[slot.index]; if (slot.salt != redirect.salt) { std.debug.warn("{} {} {}\n", .{ slot, redirect, self }); return error.NOT_FOUND; } var free_index = redirect.index; self.len -= 1; if (self.len > 0) { var free_data = &self.data.items[free_index]; var free_erase = &self.erase.items[free_index]; var last_data = &self.data.items[self.len]; var last_erase = &self.erase.items[self.len]; free_data.* = last_data.*; free_erase.* = last_erase.*; self.slots.items[free_erase.*].index = free_index; } // Update the redirect after "self.slots.ptrAt(free_erase.*).index" was updated because // if it happened to point to this redirect we want to avoid breaking the freelist redirect.salt +%= 1; if (redirect.salt == 0) { redirect.salt = 1; } redirect.index = self.next_free; self.next_free = slot.index; } pub fn getPtr(self: *Self, slot: Slot) !*T { if (!slot.is_valid()) { return error.INVALID_PARAMETER; } const redirect = &self.slots.items[slot.index]; if (slot.salt == redirect.salt) { return &self.data.items[redirect.index]; } else { return error.NOT_FOUND; } } pub fn get(self: *Self, slot: Slot) !T { return (try self.getPtr(slot)).*; } pub fn toSlice(self: *Self) []T { return self.data.items[0..self.len]; } pub fn toSliceConst(self: *Self) []const T { return self.data.items[0..self.len]; } }; } fn SlotType(comptime slot_index_type: type, comptime slot_salt_type: type) type { return struct { const Self = @This(); index: slot_index_type = 0, salt: slot_salt_type = 0, fn is_valid(slot: Self) bool { return slot.salt != 0; } fn is_equal(a: Self, b: Self) bool { return a.index == b.index and a.salt == b.salt; } }; } test "slots" { const Slotmap = Dense(i32); const invalid = Slotmap.Slot{}; const valid1 = Slotmap.Slot{ .index = 0, .salt = 1 }; const valid2 = Slotmap.Slot{ .index = 0, .salt = 1 }; assert(!invalid.is_valid()); assert(valid1.is_valid()); assert(valid2.is_valid()); assert(!valid1.is_equal(invalid)); assert(valid1.is_equal(valid2)); } test "basic inserts and growing" { var map = Dense(i32).init(std.testing.allocator); assert(map.len == 0); try map.ensureCapacity(4); assert(map.len == 0); var slot0 = try map.insert(10); var slot1 = try map.insert(11); var slot2 = try map.insert(12); var slot3 = try map.insert(13); assert(slot0.is_valid()); assert(slot1.is_valid()); assert(slot2.is_valid()); assert(slot3.is_valid()); assert(!slot0.is_equal(slot1)); assert(!slot0.is_equal(slot2)); assert(!slot0.is_equal(slot3)); assert(!slot2.is_equal(slot3)); assert(map.len == 4); assert((try map.get(slot0)) == 10); assert((try map.get(slot1)) == 11); assert((try map.get(slot2)) == 12); assert((try map.get(slot3)) == 13); var slot4 = try map.insert(14); assert(map.len == 5); assert(map.capacity() == 5); assert((try map.get(slot0)) == 10); assert((try map.get(slot1)) == 11); assert((try map.get(slot2)) == 12); assert((try map.get(slot3)) == 13); assert((try map.get(slot4)) == 14); try map.ensureCapacity(1); try map.ensureCapacity(6); try map.ensureCapacity(8); try map.ensureCapacity(16); assert(map.len == 5); assert(map.capacity() == 16); var slot5 = try map.insert(15); assert((try map.get(slot0)) == 10); assert((try map.get(slot1)) == 11); assert((try map.get(slot2)) == 12); assert((try map.get(slot3)) == 13); assert((try map.get(slot4)) == 14); assert((try map.get(slot5)) == 15); map.deinit(); } test "removal" { var map = Dense(i32).init(std.testing.allocator); try map.ensureCapacity(6); var slot0 = try map.insert(10); var slot1 = try map.insert(11); var slot2 = try map.insert(12); var slot3 = try map.insert(13); assert(map.len == 4); assert(map.capacity() == 6); try map.remove(slot3); assert(map.len == 3); try map.remove(slot0); assert(map.len == 2); try map.remove(slot1); try map.remove(slot2); assert(map.len == 0); assert(map.capacity() == 6); map.deinit(); } test "mixed insert and removal" { var map = Dense(i32).init(std.testing.allocator); try map.ensureCapacity(4); var iterations: usize = 10; while (iterations > 0) { iterations -= 1; var slot0 = try map.insert(10); var slot1 = try map.insert(11); var slot2 = try map.insert(12); var slot3 = try map.insert(13); assert(map.len == 4); var slot4 = try map.insert(14); assert(map.len == 5); try map.remove(slot1); try map.remove(slot4); var slot5 = try map.insert(15); var slot6 = try map.insert(16); var slot7 = try map.insert(17); var slot8 = try map.insert(18); try map.remove(slot5); try map.remove(slot2); var slot9 = try map.insert(19); var slot10 = try map.insert(20); assert(map.len == 7); map.clear(); } map.deinit(); } test "slices" { const MapType = Dense(i32); var map = MapType.init(std.testing.allocator); try map.ensureCapacity(10); var slots = [_]MapType.Slot{ try map.insert(0xDEAD1), try map.insert(0xDEAD2), try map.insert(0xDEAD3), try map.insert(0xDEAD4), try map.insert(0xDEAD5), try map.insert(0xDEAD6), try map.insert(0xDEAD7), try map.insert(0xDEAD8), try map.insert(0xDEAD9), try map.insert(0xDEAD10), try map.insert(0xDEAD11), }; assert(map.len == 11); for (slots) |slot, i| { if (@mod(i, 2) == 0) { try map.remove(slot); } else { var value = try map.getPtr(slot); value.* = 0xBEEF; } } assert(map.len == 5); for (map.toSliceConst()) |value, i| { assert(value == 0xBEEF); } for (slots) |slot, i| { if (@mod(i, 2) == 1) { try map.remove(slot); } } for (slots) |*slot, i| { slot.* = try map.insert(0x1337); } assert(map.len == 11); for (map.toSliceConst()) |value, i| { assert(value == 0x1337); } map.deinit(); } test "stresstest" { var buffer: [1024 * 1024 * 4]u8 = undefined; const allocator = &std.heap.FixedBufferAllocator.init(&buffer).allocator; const MapType = Dense(i32); var map = MapType.init(allocator); var slots = std.ArrayList(MapType.Slot).init(allocator); var rng = std.rand.DefaultPrng.init(0); var iterations: i32 = 100; while (iterations > 0) { iterations -= 1; var i: usize = 20000; while (i > 0) { var value = @intCast(i32, i) - 500; var slot = try map.insert(value); try slots.append(slot); i -= 1; } i = 15000; while (i > 0) { var index = @mod(rng.random.int(usize), slots.items.len); var slot = slots.swapRemove(index); try map.remove(slot); i -= 1; } i = 7500; while (i > 0) { var value = @intCast(i32, i) - 500; try slots.append((try map.insert(value))); i -= 1; } i = slots.items.len; while (i > 0) { var index = @mod(rng.random.int(usize), slots.items.len); var slot = slots.swapRemove(index); try map.remove(slot); i -= 1; } } map.deinit(); }
slotmap.zig
const std = @import("std"); pub const Highscores = struct { const Self = @This(); pub const Entry = struct { id: usize, score: isize, }; allocator: std.mem.Allocator, entries: []Entry, pub fn init(allocator: std.mem.Allocator, num_entries: usize) !Self { std.debug.assert(num_entries > 0); const entries = try allocator.alloc(Entry, num_entries); std.mem.set(Entry, entries, Entry{ .id = 0, .score = -1 }); return Self{ .allocator = allocator, .entries = entries, }; } pub fn add(self: *Self, id: usize, score: usize) void { var lowest_entry = &self.entries[self.entries.len - 1]; if (score < lowest_entry.*.score) return; var slot: usize = for (self.entries) |entry, index| { if (entry.id == id) { // ensure score is not decreasing for existing entry // otherwise sorting mechanism below fails std.debug.assert(entry.score <= @intCast(isize, score)); break index; } } else self.entries.len - 1; var entry = &self.entries[slot]; entry.id = id; entry.score = @intCast(isize, score); // check if neighbouring entry is lower, if so swap while (slot >= 1) : (slot -= 1) { var right_entry = &self.entries[slot]; var left_entry = &self.entries[slot - 1]; if (left_entry.score > right_entry.score) break; swap(right_entry, left_entry); } } pub fn top_to_bottom(self: *Self) []const Entry { // skip empty entries var max_slot: usize = for (self.entries) |entry, index| { if (entry.score < 0) break index; } else self.entries.len; return self.entries[0..max_slot]; } pub fn deinit(self: *Self) void { self.allocator.free(self.entries); } fn swap(a: anytype, b: anytype) void { const tmp = a.*; a.* = b.*; b.* = tmp; } }; test "test" { const allocator = std.testing.allocator; var hs = try Highscores.init(allocator, 3); defer hs.deinit(); try std.testing.expectEqual(@as(usize, 0), hs.top_to_bottom().len); const IdA = 3; const IdB = 51; const IdC = 77; const IdD = 101; hs.add(IdA, 100); try std.testing.expectEqual(@as(usize, 1), hs.top_to_bottom().len); hs.add(IdB, 20); try std.testing.expectEqual(@as(usize, 2), hs.top_to_bottom().len); var cmp1 = [_]Highscores.Entry{ .{ .id = IdA, .score = 100 }, .{ .id = IdB, .score = 20 } }; try std.testing.expectEqualSlices(Highscores.Entry, &cmp1, hs.top_to_bottom()); hs.add(IdB, 150); try std.testing.expectEqual(@as(usize, 2), hs.top_to_bottom().len); hs.add(IdC, 50); try std.testing.expectEqual(@as(usize, 3), hs.top_to_bottom().len); hs.add(IdD, 30); try std.testing.expectEqual(@as(usize, 3), hs.top_to_bottom().len); var cmp2 = [_]Highscores.Entry{ .{ .id = IdB, .score = 150 }, .{ .id = IdA, .score = 100 }, .{ .id = IdC, .score = 50 } }; try std.testing.expectEqualSlices(Highscores.Entry, &cmp2, hs.top_to_bottom()); hs.add(IdC, 200); var cmp3 = [_]Highscores.Entry{ .{ .id = IdC, .score = 200 }, .{ .id = IdB, .score = 150 }, .{ .id = IdA, .score = 100 } }; try std.testing.expectEqualSlices(Highscores.Entry, &cmp3, hs.top_to_bottom()); }
src/highscores.zig
const std = @import("std"); const log = std.log.scoped(.curl); const c = @cImport({ @cInclude("curl.h"); }); pub usingnamespace c; pub var inited = false; pub fn initDefault() c.CURLcode { return init(c.CURL_GLOBAL_DEFAULT); } pub fn init(flags: c_long) c.CURLcode { defer inited = true; return c.curl_global_init(flags); } pub fn deinit() void { c.curl_global_cleanup(); } pub const CurlM = struct { const Self = @This(); handle: *c.CURLM, pub fn init() Self { return .{ .handle = c.curl_multi_init().?, }; } pub fn deinit(self: Self) void { _ = c.curl_multi_cleanup(self.handle); } pub fn setOption(self: Self, option: c.CURLMoption, arg: anytype) c.CURLMcode { return c.curl_multi_setopt(self.handle, option, arg); } pub fn addHandle(self: Self, curl_h: Curl) c.CURLMcode { return c.curl_multi_add_handle(self.handle, curl_h.handle); } pub fn removeHandle(self: Self, curl_h: Curl) c.CURLMcode { return c.curl_multi_remove_handle(self.handle, curl_h.handle); } pub fn perform(self: Self, running_handles: *c_int) c.CURLMcode { return c.curl_multi_perform(self.handle, running_handles); } pub fn poll(self: Self, extra_fds: ?*c.struct_curl_waitfd, extra_nfds: c_uint, timeout_ms: c_int, ret: ?*c_int) c.CURLMcode { return c.curl_multi_poll(self.handle, extra_fds, extra_nfds, timeout_ms, ret); } pub fn socketAction(self: Self, sock_fd: c.curl_socket_t, ev_bitmask: c_int, running_handles: *c_int) c.CURLMcode { return c.curl_multi_socket_action(self.handle, sock_fd, ev_bitmask, running_handles); } pub fn assign(self: Self, sock_fd: c.curl_socket_t, sock_ptr: ?*anyopaque) c.CURLMcode { return c.curl_multi_assign(self.handle, sock_fd, sock_ptr); } pub fn infoRead(self: Self, num_remaining_msgs: *c_int) ?*c.CURLMsg { return c.curl_multi_info_read(self.handle, num_remaining_msgs); } pub fn assertNoError(code: c.CURLMcode) void { if (code != c.CURLM_OK) { log.debug("curl_multi error: [{}] {s}", .{code, getStrError(code)}); unreachable; } } pub fn getStrError(code: c.CURLMcode) []const u8 { const str = c.curl_multi_strerror(code); const len = std.mem.len(str); return str[0..len]; } }; pub const Curl = struct { const Self = @This(); handle: *c.CURL, pub fn init() Self { return .{ .handle = c.curl_easy_init().?, }; } pub fn deinit(self: Self) void { c.curl_easy_cleanup(self.handle); } pub fn setOption(self: Self, option: c.CURLoption, arg: anytype) c.CURLcode { return c.curl_easy_setopt(self.handle, option, arg); } pub fn mustSetOption(self: Self, option: c.CURLoption, arg: anytype) void { const res = self.setOption(option, arg); assertNoError(res); } pub fn perform(self: Self) c.CURLcode { return c.curl_easy_perform(self.handle); } pub fn getInfo(self: Self, option: c.CURLINFO, ptr: anytype) c.CURLcode { return c.curl_easy_getinfo(self.handle, option, ptr); } pub fn assertNoError(code: c.CURLcode) void { if (code != c.CURLE_OK) { log.debug("curl_easy error: [{}] {s}", .{code, getStrError(code)}); unreachable; } } pub fn getStrError(code: c.CURLcode) [*:0]const u8 { return c.curl_easy_strerror(code); } }; pub const CurlSH = struct { const Self = @This(); handle: *c.CURLSH, pub fn init() Self { return .{ .handle = c.curl_share_init().?, }; } pub fn deinit(self: Self) void { _ = c.curl_share_cleanup(self.handle); } pub fn setOption(self: Self, option: c.CURLSHoption, arg: anytype) c.CURLSHcode { return c.curl_share_setopt(self.handle, option, arg); } };
lib/curl/curl.zig
usingnamespace @import("exports.zig"); const CParser = c.yaml_parser_t; const CEvent = c.yaml_event_t; const CEventType = c.yaml_event_e; const CError = c.yaml_error_type_t; /// A simple abstraction around libyaml's parser. This is for private use only. /// Most of the resource ownership rules from libyaml still apply, /// so be careful with this. pub fn Parser(comptime Reader: type) type { return struct { raw: *CParser, allocator: *Allocator, _reader: Reader, const Self = @This(); pub fn init(allocator: *Allocator, reader: Reader) common.ParserError!Self { var raw = try allocator.create(CParser); errdefer allocator.destroy(raw); // Checking if initialization failed. if (c.yaml_parser_initialize(raw) == 0) { return error.OutOfMemory; } errdefer c.yaml_parser_delete(raw); c.yaml_parser_set_input(raw, Self.handler, @ptrCast(?*c_void, reader)); return Self{ .raw = raw, .allocator = allocator, ._reader = reader, }; } // This function is called by libyaml to get more data from a buffer. // `data` is a pointer we give to libyaml when `yaml_parser_set_input` is called. // `buff` is a pointer to a byte buffer of size `buflen`. // This is were we should paste the data read from `context`. // `bytes_read` is a pointer in which we write the actual number of bytes that were read. fn handler(maybe_data: ?*c_void, maybe_buff: ?[*]u8, buflen: usize, bytes_read: ?*usize) callconv(.C) c_int { if (maybe_data) |data| { if (maybe_buff) |buff| { var reader = @ptrCast(Reader, @alignCast(@alignOf(Reader), data)); if (reader.read(buff[0..buflen])) |br| { bytes_read.?.* = br; return 1; } else |_| { return 0; } } } return 0; } pub fn nextEvent(self: *Self) common.ParserError!common.Event { var raw_event: CEvent = undefined; if (c.yaml_parser_parse(self.raw, &raw_event) == 0) { return common.ParserError.ReadingFailed; } defer c.yaml_event_delete(&raw_event); const etype = switch (raw_event.type) { c.YAML_NO_EVENT => .NoEvent, c.YAML_STREAM_START_EVENT => common.EventType{ .StreamStartEvent = switch (raw_event.data.stream_start.encoding) { c.YAML_UTF8_ENCODING => .Utf8, c.YAML_UTF16LE_ENCODING => .Utf16LittleEndian, c.YAML_UTF16BE_ENCODING => .Utf16BigEndian, else => .Any, } }, c.YAML_STREAM_END_EVENT => .StreamEndEvent, c.YAML_DOCUMENT_START_EVENT => blk: { const version = if (raw_event.data.document_start.version_directive) |_ver| common.Version { .major = @intCast(u32, _ver.*.major), .minor = @intCast(u32, _ver.*.minor), } else null; break :blk common.EventType{ .DocumentStartEvent = .{ .version = version } }; }, c.YAML_DOCUMENT_END_EVENT => .DocumentEndEvent, c.YAML_ALIAS_EVENT => unreachable, c.YAML_SCALAR_EVENT => common.EventType{ .ScalarEvent = .{ .value = try self.allocator.dupe(u8, raw_event.data.scalar.value[0..raw_event.data.scalar.length]), } }, c.YAML_SEQUENCE_START_EVENT => .SequenceStartEvent, c.YAML_SEQUENCE_END_EVENT => .SequenceEndEvent, c.YAML_MAPPING_START_EVENT => .MappingStartEvent, c.YAML_MAPPING_END_EVENT => .MappingEndEvent, else => unreachable, }; return common.Event{ .etype = etype, .allocator = self.allocator, }; } pub fn deinit(self: Self) void { c.yaml_parser_delete(self.raw); self.allocator.destroy(self.raw); } }; }
src/backends/c/parser.zig
const std = @import("std"); const c = @import("../../c_global.zig").c_imp; // dross-zig const Vector2 = @import("../../core/vector2.zig").Vector2; const tx = @import("../texture.zig"); const Texture = tx.Texture; // ----------------------------------------------------------------------------- // ----------------------------------------- // - Glyph - // ----------------------------------------- /// pub const Glyph = struct { internal_texture: ?*Texture = 0, texture_coordinates: Vector2 = undefined, internal_width: u32 = undefined, internal_rows: u32 = undefined, internal_offset_x: i32 = undefined, internal_offset_y: i32 = undefined, internal_advance: u32 = undefined, const Self = @This(); /// Allocates and builds a Glyph instance /// Comments: The Font instance should be the /// only player this is called, so the owner /// SHOULD be a Font instance. pub fn new( allocator: *std.mem.Allocator, data: [*c]u8, desired_width: u32, desired_rows: u32, desired_offset_x: i32, desired_offset_y: i32, desired_advance: u32, ) !*Self { var glyph = try allocator.create(Glyph); glyph.internal_texture = try Texture.newFont(allocator, data, desired_width, desired_rows); glyph.internal_width = desired_width; glyph.internal_rows = desired_rows; glyph.internal_offset_x = desired_offset_x; glyph.internal_offset_y = desired_offset_y; glyph.internal_advance = desired_advance; return glyph; } /// Cleans up and de-allocates the Glyph and /// any memory it allocated. pub fn free(allocator: *std.mem.Allocator, self: *Self) void { Texture.free(allocator, self.internal_texture.?); allocator.destroy(self); } /// Sets the stored size of the glyph pub fn setWidth(self: *Self, width: u32) void { self.internal_width = width; } /// Sets the stored size of the glyph pub fn setRows(self: *Self, rows: u32) void { self.internal_rows = rows; } /// Sets the stored offset of the glyph pub fn setOffset(self: *Self, offset_x: i32, offset_y: i32) void { self.internal_offset_x = offset_x; self.internal_offset_y = offset_y; } /// Sets the stored x_advance of the glyph pub fn setAdvance(self: *Self, x_advance: u32) void { self.internal_advance = x_advance; } /// Returns the stored width of the glyph pub fn width(self: *Self) u32 { return self.internal_width; } /// Returns the stored number of rows of the glyph pub fn rows(self: *Self) u32 { return self.internal_rows; } /// Returns the stored offset of the glyph pub fn offset(self: *Self) Vector2 { return Vector2.new( @intToFloat(f32, self.internal_offset_x), @intToFloat(f32, self.internal_offset_y), ); } /// Returns the stored x_advance of the glyph pub fn advance(self: *Self) u32 { return self.internal_advance; } /// Returns a pointer to the glyph's texture pub fn texture(self: *Self) ?*Texture { return self.internal_texture; } };
src/renderer/font/glyph.zig
const std = @import("std"); const print = std.debug.print; pub fn main() void { const reader0 = std.io.fixedBufferStream("1234").reader(); var buf0: [4]u8 = undefined; var foo = reader0.readUntilDelimiter(&buf0, '\n') catch "error"; print("0->{s}<-\n", .{ foo }); foo = reader0.readUntilDelimiter(&buf0, '\n') catch |err| @errorName(err); print("0->{s}<-\n", .{ foo }); foo = reader0.readUntilDelimiter(&buf0, '\n') catch |err| @errorName(err); print("0->{s}<-\n", .{ foo }); print("========================\n", .{}); const reader1 = std.io.fixedBufferStream("000\n1234567\n").reader(); var buf1: [4]u8 = undefined; foo = reader1.readUntilDelimiter(&buf1, '\n') catch "error"; print("1->{s}<-\n", .{ foo }); foo = reader1.readUntilDelimiter(&buf1, '\n') catch |err| @errorName(err); print("1->{s}<-\n", .{ foo }); foo = reader1.readUntilDelimiter(&buf1, '\n') catch |err| @errorName(err); print("1->{s}<-\n", .{ foo }); print("========================\n", .{}); const reader2 = std.io.fixedBufferStream("\n").reader(); var buf2: [4]u8 = undefined; foo = reader2.readUntilDelimiter(&buf2, '\n') catch |err| @errorName(err); print("2->{s}<-\n", .{ foo }); foo = reader2.readUntilDelimiter(&buf2, '\n') catch |err| @errorName(err); print("2->{s}<-\n", .{ foo }); print("========================\n", .{}); const reader3 = std.io.fixedBufferStream("").reader(); var buf3: [4]u8 = undefined; foo = reader3.readUntilDelimiter(&buf3, '\n') catch |err| @errorName(err); print("3->{s}<-\n", .{ foo }); foo = reader3.readUntilDelimiter(&buf3, '\n') catch |err| @errorName(err); print("3->{s}<-\n", .{ foo }); } test "9594-1" { const reader = std.io.fixedBufferStream("1234567\n").reader(); var buf: [4]u8 = undefined; try std.testing.expectError(error.StreamTooLong, reader.readUntilDelimiter(&buf, '\n')); try std.testing.expectEqualStrings("567", try reader.readUntilDelimiter(&buf, '\n')); } test "9594-4" { const reader = std.io.fixedBufferStream("0000\n1234567\n").reader(); var buf: [4]u8 = undefined; try std.testing.expectEqualStrings("0000", try reader.readUntilDelimiter(&buf, '\n')); try std.testing.expectError(error.StreamTooLong, reader.readUntilDelimiter(&buf, '\n')); try std.testing.expectEqualStrings("567", try reader.readUntilDelimiter(&buf, '\n')); } test "9594-5" { const reader = std.io.fixedBufferStream("\n").reader(); var buf: [4]u8 = undefined; try std.testing.expectEqualStrings("", try reader.readUntilDelimiter(&buf, '\n')); try std.testing.expectError(error.EndOfStream, reader.readUntilDelimiter(&buf, '\n')); } test "9594-3" { const reader = std.io.fixedBufferStream("1234").reader(); var buf: [4]u8 = undefined; try std.testing.expectError(error.EndOfStream, reader.readUntilDelimiter(&buf, '\n')); } test "9594-2" { const reader = std.io.fixedBufferStream("123").reader(); var buf: [4]u8 = undefined; try std.testing.expectError(error.EndOfStream, reader.readUntilDelimiter(&buf, '\n')); } test "9594-6" { const reader = std.io.fixedBufferStream("").reader(); var buf: [4]u8 = undefined; try std.testing.expectError(error.EndOfStream, reader.readUntilDelimiter(&buf, '\n')); }
zig/issue_9594.zig
const std = @import("std"); const math = std.math; const max = math.max; const min = math.min; const abs = math.fabs; const hypot = math.hypot; const ln = math.ln; const exp = math.exp; const floor = math.floor; const ceil = math.ceil; const pi: f64 = math.pi; const tau: f64 = 6.28318530717958647; const sdf2 = @import("sdf2.zig"); const V2 = @import("affine.zig").V2; const v2 = V2.init; const V3 = @import("affine.zig").V3; const v3 = V3.init; const gmath = @import("gmath.zig").gmath(f64); const saturate = gmath.saturate; const clamp = gmath.clamp; const mix = gmath.mix; pub const Sdfn = fn (V3) f64; pub const Model = union(enum) { const Self = @This(); Origin: void, Round: Round, Sdfn: Sdfn, Displace: Model2, pub fn compile(comptime self: Self) Sdfn { return switch (self) { .Origin => Sdf.origin, .Round => |c| Sdf.roundFn(c.sub.compile(), c.r), .Sdfn => |f| f, .Displace => |c| Sdf.displaceFn(c.a.compile(), c.b.compile()), }; } }; pub const Round = struct { r: f64, sub: *const Model, }; pub const Model2 = struct { a: *const Model, b: *const Model, }; pub const Sdf = struct { pub inline fn origin(p: V3) f64 { return p.length(); } pub fn roundFn(comptime sub: Sdfn, comptime r: f64) Sdfn { const compiler = struct { inline fn round(p: V3) f64 { return Dist.round(sub(p), r); } }; return compiler.round; } pub fn displaceFn(comptime f: Sdfn, comptime g: Sdfn) Sdfn { const compiler = struct { inline fn displace(p: V3) f64 { return Dist.displace(f(p), g(p)); } }; return compiler.displace; } pub fn sphere01(p: V3) f64 { return Dist.round(v3(p.x - 0.5, p.y - 0.5, p.z).length(), 0.5); } pub fn horizontalExtrudedEllispe(p: V3) f64 { const o = v3(0.5, 0.5, 0); const round = 0.005; const width = 0.8; const height = 0.8; const curve = 0.2; const sp2: V2 = sdf2.NearestPoint.ellipse(v2(p.y - o.y, p.z - o.z), v2(width * 0.5 - round, curve)); const sp3 = v3(clamp(o.x - height * 0.5 + round, o.x + height * 0.5 - round, p.x), sp2.x + o.y, sp2.y + o.z); return p.distTo(sp3) - round; } pub fn verticalExtrudedEllipse(p: V3) f64 { const o = v3(0.5, 0.5, 0); const round = 0.005; const width = 0.8; const height = 0.8; const curve = 0.2; const sp2: V2 = sdf2.NearestPoint.ellipse(v2(p.x - o.x, p.z - o.z), v2(width * 0.5 - round, curve)); const sp3 = v3(sp2.x + o.x, clamp(o.y - height * 0.5 + round, o.y + height * 0.5 - round, p.y), sp2.y + o.z); return p.distTo(sp3) - round; } }; pub const Dist = struct { pub inline fn invert(d: f64) f64 { return -d; } pub inline fn edge(d: f64) f64 { return abs(d); } pub inline fn round(d: f64, r: f64) f64 { return d - r; } pub inline fn displace(a: f64, b: f64) f64 { return a + b; } }; pub fn rayMarch(ro: V3, rd: V3, comptime model: Sdfn) ?Marched { const stepLimit: usize = 256; const closeEnough: f64 = 0.001; const maxT: f64 = 1000; var t: f64 = 0; var step: usize = 0; while (step < stepLimit and t < maxT) : (step += 1) { const pos = rd.scale(t).add(ro); const d = model(pos); if (d < closeEnough) { return Marched{ .d = d, .pos = pos, }; } t += d * 0.95; } return null; } pub const Marched = struct { d: f64, pos: V3, }; pub fn softShadowMarch(ro: V3, rd: V3, comptime model: Sdfn, k: f64) f64 { const stepLimit: usize = 128; const closeEnough: f64 = 0.002; const maxT: f64 = 1000; var t: f64 = 0; var step: usize = 0; var result: f64 = 1.0; while (step < stepLimit and t < maxT) : (step += 1) { const pos = rd.scale(t).add(ro); const d = model(pos); result = math.min(result, k * d / t); if (d < closeEnough) { return 0; } t += clamp(0.005, 0.1, d); } //return math.max(result, 0); return 1; } //pub fn normal(p: V3, comptime model: Sdfn) V3 { // const e = 0.00001; // return v3( // model(v3(p.x + e, p.y, p.z)) - model(v3(p.x - e, p.y, p.z)), // model(v3(p.x, p.y + e, p.z)) - model(v3(p.x, p.y - e, p.z)), // model(v3(p.x, p.y, p.z + e)) - model(v3(p.x, p.y, p.z - e)), // ).normalize(); //} //pub fn normal(p: V3, comptime model: Sdfn) V3 { // const eps = 0.00001; // const x = 0.5773; // const y = -0.5773; // // var p1 = v3(x, y, y).scale(model(p.add(v3(x, y, y).scale(eps)))); // var p2 = v3(y, y, x).scale(model(p.add(v3(y, y, x).scale(eps)))); // var p3 = v3(y, x, y).scale(model(p.add(v3(y, x, y).scale(eps)))); // var p4 = v3(x, x, x).scale(model(p.add(v3(x, x, x).scale(eps)))); // // return p1.add(p2).add(p3.add(p4)).normalize(); //} pub fn normal(p: V3, comptime model: Sdfn) V3 { const eps = 0.00001; const a = 0.5773; const b = -0.5773; const ae = a * eps; const be = b * eps; const d1 = model(v3(p.x + ae, p.y + be, p.z + be)); const d2 = model(v3(p.x + be, p.y + be, p.z + ae)); const d3 = model(v3(p.x + be, p.y + ae, p.z + be)); const d4 = model(v3(p.x + ae, p.y + ae, p.z + ae)); return v3( d1 * a + d2 * b + d3 * b + d4 * a, d1 * b + d2 * b + d3 * a + d4 * a, d1 * b + d2 * a + d3 * b + d4 * a, ).normalize(); }
lib/sdf3.zig
const std = @import("std"); const builtin = @import("builtin"); const Allocator = std.mem.Allocator; const x11 = @import("x11.zig"); const wayland = @import("wayland.zig"); const windows = @import("windows.zig"); const xlib = @import("xlib.zig"); pub const PlatformType = enum { Xlib, X11, Wayland, Windows, }; pub const PlatformsEnabled = struct { x11: bool = if (builtin.os.tag == .linux) true else false, wayland: bool = if (builtin.os.tag == .linux) true else false, windows: bool = if (builtin.os.tag == .windows) true else false, /// The Xlib backend provides OpenGL features for all platforms. Fuck NVIDIA for us requiring to do this! xlib: bool = false, }; pub const OpenGlVersion = struct { major: u8, minor: u8, core: bool = true, // enable core profile }; /// This enum lists all possible render backends ZWL can initialize on a window. pub const Backend = union(enum) { /// Initialize no render backend, the window is just a raw window handle. none, /// Initialize basic software rendering. This enables the `mapPixels` and `submitPixels` functions. software, /// Initializes a OpenGL context for the window. The given version is the minimum version required. opengl: OpenGlVersion, /// Creates a vulkan swapchain for the window. vulkan, }; pub const BackendEnabled = struct { /// When this is enabled, you can create windows that allow mapping their pixel content /// into system memory and allow framebuffer modification by the CPU. /// Create the window with Backend.software to use this feature. software: bool = false, /// When this is enabled, you can create windows that export an OpenGL context. /// Create the window with Backend.opengl to use this feature. opengl: bool = false, /// When this is enabled, you can create windows that export a Vulkan swap chain. /// In addition to that, the Platform itself will try initializing vulkan and provide /// access to a vkInstance. /// Create the window with Backend.vulkan to use this feature. vulkan: bool = false, }; /// Global compile-time platform settings pub const PlatformSettings = struct { /// The list of platforms you'd like to compile in support for. platforms_enabled: PlatformsEnabled = .{}, /// Specify which rendering backends you want to compile in support for. /// You probably don't want to enable hardware rendering on Linux without linking XCB/Xlib or libwayland. backends_enabled: BackendEnabled = .{}, /// If you need to track data about specific monitors, set this to true. Usually not needed for /// always-windowed applications or programs that don't need explicit control on what monitor to /// fullscreen themselves on. monitors: bool = false, // Set this to "true" if you're never creating more than a single window. Doing so // simplifies the internal library bookkeeping, but means any call to // createWindow() is undefined behaviour if a window already exists. single_window: bool = false, /// Specify if you want to be able to render to a remote server over TCP. This only works on X11 with software rendering /// and has quite poor performance. Does not affect X11 on Windows as the TCP connection is the only way it works. remote: bool = false, /// Specify if you'd like to use XCB instead of the native Zig X11 connection. This is chiefly /// useful for hardware rendering when you need to hand over the connection to other rendering APIs, e.g. Vulkan. x11_use_xcb: bool = false, /// There is one Vulkan extension (VK_EXT_acquire_xlib_display) that only exists for Xlib, not XCB, If /// this is enabled, Xlib is linked instead and an XCB connection is acquired through that so this /// extension can be used. x11_use_xcb_through_xlib: bool = false, /// Specify if you'd like to use libwayland instead of the native Zig Wayland connection. This is chiefly /// useful for hardware rendering when you need to hand over the connection to other rendering APIs, e.g. Vulkan. wayland_use_libwayland: bool = false, /// If you set 'hdr' to true, the pixel buffer(s) you get is in the native window/monitor colour depth, /// which can have more (or fewer, technically) than 8 bits per colour. /// If false, the library will always give you an 8-bit buffer and automatically convert it to /// the native depth for you if needed. hdr: bool = false, }; /// Backend-specific runtime options. pub const PlatformOptions = struct { x11: struct { /// The X11 host we will connect to. 'null' here means using the DISPLAY environment variable, /// parsed in the same manner as XCB. Specifying "localhost" or a zero-length string will use /// a Unix domain socket if supported by the OS. /// Note that ZWL does not support the really ancient protocol specification syntax (i.e. proto/host), /// used e.g. for DECnet and will instead treat it as a malformed host. host: ?[]const u8 = null, /// What X11 display to connect to. Practically always 0 for modern X11. /// 'null' here means using the DISPLAY environment variable, parsed in the same manner as XCB. display: ?u6 = null, /// What X11 screen to use. Practically always 0 for modern X11. /// 'null' here means using the DISPLAY environment variable, parsed in the same manner as XCB. screen: ?u8 = null, /// The X11 MIT-MAGIC-COOKIE-1 to be used during authentication. /// 'null' here means reading it from the .Xauthority file mit_magic_cookie: ?[16]u8 = null, /// The location of the X11 .Xauthority file, used if mit_magic_cookie is null. /// 'null' here means reading it from the XAUTHORITY environment variable. xauthority_location: ?[]const u8 = null, } = .{}, wayland: struct { // todo: stuff } = .{}, windows: struct { // todo: stuff } = .{}, }; /// The window mode. All options degrade to "Fullscreen" if not supported by the platform. pub const WindowMode = enum { /// A normal desktop window. Windowed, /// A normal desktop window, resized so that it covers the entire screen. Compared to proper fullscreen /// this does not bypass the compositor, which usually adds one frame of latency and degrades performance slightly. /// The upside is that switching desktops or alt-tabbing from this application to another is much faster. WindowedFullscreen, /// A normal fullscreen window. Fullscreen, }; /// Options for windows pub const WindowOptions = struct { /// The title of the window. Ignored if the platform does not support it. If specifying a title is not optional /// for the current platform, a null title will be interpreted as an empty string. title: ?[]const u8 = null, width: ?u16 = null, height: ?u16 = null, visible: ?bool = null, mode: ?WindowMode = null, /// Whether the user is allowed to resize the window or not. Note that this is more of a suggestion, /// and the window manager could resize us anyway if it so chooses. resizeable: ?bool = null, /// Set this to "true" you want the default system border and title bar with the name, buttons, etc. when windowed. /// Set this to "false" if you're a time traveller from 1999 developing your latest winamp skin or something. decorations: ?bool = null, /// Set 'transparent' to true if you'd like to get pixels with an alpha component, so that parts of your window /// can be made transparent. Note that this will only work if the platform has a compositor running. transparent: ?bool = null, /// This means that the event callback will notify you if any of your window is "damaged", i.e. /// needs to be re-rendered due to (for example) another window having covered part of it. /// Not needed if you're constantly re-rendering the entire window anyway. track_damage: ?bool = null, /// This means that mouse motion and click events will be tracked. track_mouse: ?bool = null, /// This means that keyboard events will be tracked. track_keyboard: ?bool = null, /// This defines the render backend ZWL will initialize. backend: Backend = Backend.none, }; pub const EventType = enum { WindowResized, WindowDestroyed, WindowDamaged, WindowVBlank, ApplicationTerminated, KeyDown, KeyUp, MouseButtonDown, MouseButtonUp, MouseMotion, }; pub const KeyEvent = struct { scancode: u32, }; pub const MouseMotionEvent = struct { x: i16, y: i16, }; pub const MouseButtonEvent = struct { x: i16, y: i16, button: MouseButton, }; pub const MouseButton = enum(u8) { left = 1, middle = 2, right = 3, wheel_up = 4, wheel_down = 5, nav_backward = 6, nav_forward = 7, _, }; pub fn Platform(comptime _settings: PlatformSettings) type { return struct { const Self = @This(); pub const settings = _settings; pub const PlatformX11 = x11.Platform(Self); pub const PlatformWayland = wayland.Platform(Self); pub const PlatformWindows = windows.Platform(Self); pub const PlatformXlib = xlib.Platform(Self); type: PlatformType, allocator: *Allocator, window: if (settings.single_window) ?*Window else void, windows: if (settings.single_window) void else []*Window, pub fn init(allocator: *Allocator, options: PlatformOptions) !*Self { if (settings.platforms_enabled.xlib) blk: { return PlatformXlib.init(allocator, options) catch break :blk; } if (settings.platforms_enabled.wayland) blk: { return PlatformWayland.init(allocator, options) catch break :blk; } if (settings.platforms_enabled.x11) blk: { return PlatformX11.init(allocator, options) catch break :blk; } if (settings.platforms_enabled.windows) blk: { return PlatformWindows.init(allocator, options) catch break :blk; } return error.NoPlatformAvailable; } pub fn deinit(self: *Self) void { switch (self.type) { .X11 => if (!settings.platforms_enabled.x11) unreachable else PlatformX11.deinit(@ptrCast(*PlatformX11, self)), .Wayland => if (!settings.platforms_enabled.wayland) unreachable else PlatformWayland.deinit(@ptrCast(*PlatformWayland, self)), .Windows => if (!settings.platforms_enabled.windows) unreachable else PlatformWindows.deinit(@ptrCast(*PlatformWindows, self)), .Xlib => if (!settings.platforms_enabled.xlib) unreachable else PlatformXlib.deinit(@ptrCast(*PlatformXlib, self)), } } pub fn waitForEvent(self: *Self) anyerror!Event { return switch (self.type) { .X11 => if (!settings.platforms_enabled.x11) unreachable else PlatformX11.waitForEvent(@ptrCast(*PlatformX11, self)), .Wayland => if (!settings.platforms_enabled.wayland) unreachable else PlatformWayland.waitForEvent(@ptrCast(*PlatformWayland, self)), .Windows => if (!settings.platforms_enabled.windows) unreachable else PlatformWindows.waitForEvent(@ptrCast(*PlatformWindows, self)), .Xlib => if (!settings.platforms_enabled.xlib) unreachable else PlatformXlib.waitForEvent(@ptrCast(*PlatformXlib, self)), }; } pub fn createWindow(self: *Self, options: WindowOptions) anyerror!*Window { const window = try switch (self.type) { .X11 => if (!settings.platforms_enabled.x11) unreachable else PlatformX11.createWindow(@ptrCast(*PlatformX11, self), options), .Wayland => if (!settings.platforms_enabled.wayland) unreachable else PlatformWayland.createWindow(@ptrCast(*PlatformWayland, self), options), .Windows => if (!settings.platforms_enabled.windows) unreachable else PlatformWindows.createWindow(@ptrCast(*PlatformWindows, self), options), .Xlib => if (!settings.platforms_enabled.xlib) unreachable else PlatformXlib.createWindow(@ptrCast(*PlatformXlib, self), options), }; errdefer window.deinit(); if (settings.single_window) { self.window = window; } else { self.windows = try self.allocator.realloc(self.windows, self.windows.len + 1); self.windows[self.windows.len - 1] = window; } return window; } pub fn getOpenGlProcAddress(self: *Self, entry_point: [:0]const u8) ?*c_void { return switch (self.type) { .X11 => if (!settings.platforms_enabled.x11) unreachable else PlatformX11.getOpenGlProcAddress(@ptrCast(*PlatformX11, self), entry_point), .Wayland => if (!settings.platforms_enabled.wayland) unreachable else PlatformWayland.getOpenGlProcAddress(@ptrCast(*PlatformWayland, self), entry_point), .Windows => if (!settings.platforms_enabled.windows) unreachable else PlatformWindows.getOpenGlProcAddress(@ptrCast(*PlatformWindows, self), entry_point), .Xlib => if (!settings.platforms_enabled.xlib) unreachable else PlatformXlib.getOpenGlProcAddress(@ptrCast(*PlatformXlib, self), entry_point), }; } pub const Event = union(EventType) { WindowResized: *Window, WindowDestroyed: *Window, WindowDamaged: struct { window: *Window, x: u16, y: u16, w: u16, h: u16 }, WindowVBlank: *Window, ApplicationTerminated: void, KeyDown: KeyEvent, KeyUp: KeyEvent, MouseButtonDown: MouseButtonEvent, MouseButtonUp: MouseButtonEvent, MouseMotion: MouseMotionEvent, }; pub const Window = struct { platform: *Self, pub fn deinit(self: *Window) void { if (settings.single_window) { self.platform.window = null; } else { for (self.platform.windows) |*w, i| { if (w.* == self) { w.* = self.platform.windows[self.platform.windows.len - 1]; break; } } self.platform.windows = self.platform.allocator.realloc(self.platform.windows, self.platform.windows.len - 1) catch unreachable; } return switch (self.platform.type) { .X11 => if (!settings.platforms_enabled.x11) unreachable else PlatformX11.Window.deinit(@ptrCast(*PlatformX11.Window, self)), .Wayland => if (!settings.platforms_enabled.wayland) unreachable else PlatformWayland.Window.deinit(@ptrCast(*PlatformWayland.Window, self)), .Windows => if (!settings.platforms_enabled.windows) unreachable else PlatformWindows.Window.deinit(@ptrCast(*PlatformWindows.Window, self)), .Xlib => if (!settings.platforms_enabled.xlib) unreachable else PlatformXlib.Window.deinit(@ptrCast(*PlatformXlib.Window, self)), }; } pub fn configure(self: *Window, options: WindowOptions) !void { return switch (self.platform.type) { .X11 => if (!settings.platforms_enabled.x11) unreachable else PlatformX11.Window.configure(@ptrCast(*PlatformX11.Window, self), options), .Wayland => if (!settings.platforms_enabled.wayland) unreachable else PlatformWayland.Window.configure(@ptrCast(*PlatformWayland.Window, self), options), .Windows => if (!settings.platforms_enabled.windows) unreachable else PlatformWindows.Window.configure(@ptrCast(*PlatformWindows.Window, self), options), .Xlib => if (!settings.platforms_enabled.xlib) unreachable else PlatformXlib.Window.configure(@ptrCast(*PlatformXlib.Window, self), options), }; } pub fn getSize(self: *Window) [2]u16 { return switch (self.platform.type) { .X11 => if (!settings.platforms_enabled.x11) unreachable else PlatformX11.Window.getSize(@ptrCast(*PlatformX11.Window, self)), .Wayland => if (!settings.platforms_enabled.wayland) unreachable else PlatformWayland.Window.getSize(@ptrCast(*PlatformWayland.Window, self)), .Windows => if (!settings.platforms_enabled.windows) unreachable else PlatformWindows.Window.getSize(@ptrCast(*PlatformWindows.Window, self)), .Xlib => if (!settings.platforms_enabled.xlib) unreachable else PlatformXlib.Window.getSize(@ptrCast(*PlatformXlib.Window, self)), }; } pub fn present(self: *Window) !void { return switch (self.platform.type) { .X11 => @panic("not implemented yet!"), .Wayland => @panic("not implemented yet!"), .Windows => if (!settings.platforms_enabled.windows) unreachable else PlatformWindows.Window.present(@ptrCast(*PlatformWindows.Window, self)), .Xlib => if (!settings.platforms_enabled.xlib) unreachable else PlatformXlib.Window.present(@ptrCast(*PlatformXlib.Window, self)), }; } pub fn mapPixels(self: *Window) anyerror!PixelBuffer { return switch (self.platform.type) { .X11 => if (!settings.platforms_enabled.x11) unreachable else PlatformX11.Window.mapPixels(@ptrCast(*PlatformX11.Window, self)), .Wayland => if (!settings.platforms_enabled.wayland) unreachable else PlatformWayland.Window.mapPixels(@ptrCast(*PlatformWayland.Window, self)), .Windows => if (!settings.platforms_enabled.windows) unreachable else PlatformWindows.Window.mapPixels(@ptrCast(*PlatformWindows.Window, self)), .Xlib => if (!settings.platforms_enabled.xlib) unreachable else PlatformXlib.Window.mapPixels(@ptrCast(*PlatformXlib.Window, self)), }; } pub fn submitPixels(self: *Window, updates: []const UpdateArea) !void { return switch (self.platform.type) { .X11 => if (!settings.platforms_enabled.x11) unreachable else PlatformX11.Window.submitPixels(@ptrCast(*PlatformX11.Window, self), updates), .Wayland => if (!settings.platforms_enabled.wayland) unreachable else PlatformWayland.Window.submitPixels(@ptrCast(*PlatformWayland.Window, self), updates), .Windows => if (!settings.platforms_enabled.windows) unreachable else PlatformWindows.Window.submitPixels(@ptrCast(*PlatformWindows.Window, self), updates), .Xlib => if (!settings.platforms_enabled.xlib) unreachable else PlatformXlib.Window.submitPixels(@ptrCast(*PlatformXlib.Window, self), updates), }; } }; }; } pub const Pixel = extern struct { // TODO: Maybe make this *order* platform dependent! b: u8, g: u8, r: u8, a: u8 = 0xFF, }; pub const UpdateArea = struct { x: u16, y: u16, w: u16, h: u16, }; pub const PixelBuffer = struct { const Self = @This(); data: [*]u32, // todo: format as well width: u16, height: u16, pub inline fn setPixel(self: Self, x: usize, y: usize, color: Pixel) void { self.data[self.width * y + x] = @bitCast(u32, color); } pub inline fn getPixel(self: Self, x: usize, y: usize) Pixel { return @bitCast(Pixel, self.data[self.width * y + x]); } pub fn span(self: Self) []u32 { return self.data[0 .. @as(usize, self.width) * @as(usize, self.height)]; } }; comptime { std.debug.assert(@sizeOf(Pixel) == 4); std.debug.assert(@bitSizeOf(Pixel) == 32); }
didot-zwl/zwl/src/zwl.zig
const std = @import("std"); const getty = @import("../../../lib.zig"); pub fn Visitor(comptime Array: type) type { return struct { allocator: ?std.mem.Allocator = null, const Self = @This(); const impl = @"impl Visitor"(Array); pub usingnamespace getty.de.Visitor( Self, impl.visitor.Value, undefined, undefined, undefined, undefined, undefined, undefined, impl.visitor.visitSequence, impl.visitor.visitString, undefined, undefined, ); }; } fn @"impl Visitor"(comptime Array: type) type { const Self = Visitor(Array); return struct { pub const visitor = struct { pub const Value = Array; pub fn visitSequence(self: Self, sequenceAccess: anytype) @TypeOf(sequenceAccess).Error!Value { var seq: Value = undefined; var seen: usize = 0; errdefer { if (self.allocator) |allocator| { if (seq.len > 0) { var i: usize = 0; while (i < seen) : (i += 1) { getty.de.free(allocator, seq[i]); } } } } switch (seq.len) { 0 => seq = .{}, else => for (seq) |*elem| { if (try sequenceAccess.nextElement(Child)) |value| { elem.* = value; seen += 1; } else { // End of sequence was reached early. return error.InvalidLength; } }, } // Expected end of sequence, but found an element. if ((try sequenceAccess.nextElement(Child)) != null) { return error.InvalidLength; } return seq; } pub fn visitString(self: Self, comptime Error: type, input: anytype) Error!Value { defer getty.de.free(self.allocator.?, input); if (Child == u8) { var string: Value = undefined; if (input.len == string.len) { std.mem.copy(u8, &string, input); return string; } } return error.InvalidType; } const Child = std.meta.Child(Value); }; }; }
src/de/impl/visitor/array.zig
const std = @import("std"); const meta = std.meta; const testing = std.testing; const assert = std.debug.assert; const jsonrpc = @import("jsonrpc.zig"); const kisa = @import("kisa"); const Keys = @import("main.zig").Keys; const RpcKind = enum { jsonrpc }; const rpcImplementation = RpcKind.jsonrpc; pub fn Request(comptime ParamsShape: type) type { return RequestType(rpcImplementation, ParamsShape); } pub fn Response(comptime ResultShape: type) type { return ResponseType(rpcImplementation, ResultShape); } pub const EmptyResponse = Response(bool); pub const EmptyRequest = Request([]bool); pub const KeypressRequest = jsonrpc.Request(Keys.Key); pub fn ackResponse(id: ?u32) EmptyResponse { return EmptyResponse.initSuccess(id, true); } pub const ResponseError = error{ AccessDenied, BadPathName, DeviceBusy, EmptyPacket, FileNotFound, FileTooBig, InputOutput, InvalidParams, InvalidRequest, InvalidUtf8, IsDir, MethodNotFound, NameTooLong, NoDevice, NoSpaceLeft, NotOpenForReading, NullIdInRequest, OperationAborted, ParseError, ProcessFdQuotaExceeded, SharingViolation, SymLinkLoop, SystemFdQuotaExceeded, SystemResources, Unexpected, UninitializedClient, }; pub fn errorResponse(id: ?u32, err: ResponseError) EmptyResponse { switch (err) { // JSON-RPC 2.0 errors error.EmptyPacket => return EmptyResponse.initError(id, -32700, "Parse error: empty packet"), error.InvalidRequest => return EmptyResponse.initError(id, -32600, "Invalid request"), error.NullIdInRequest => return EmptyResponse.initError(id, -32600, "Invalid request: Id can't be null"), error.ParseError => return EmptyResponse.initError(id, -32700, "Parse error"), error.MethodNotFound => return EmptyResponse.initError(id, -32601, "Method not found"), error.InvalidParams => return EmptyResponse.initError(id, -32602, "Invalid params"), // Unix-style issues error.AccessDenied => return EmptyResponse.initError(id, 13, "Permission denied"), error.SharingViolation => return EmptyResponse.initError(id, 37, "Sharing violation"), error.SymLinkLoop => return EmptyResponse.initError(id, 40, "Too many levels of symbolic links"), error.ProcessFdQuotaExceeded => return EmptyResponse.initError(id, 24, "Too many open files"), error.SystemFdQuotaExceeded => return EmptyResponse.initError(id, 23, "Too many open files in system"), error.FileNotFound => return EmptyResponse.initError(id, 2, "No such file or directory"), error.SystemResources => return EmptyResponse.initError(id, 104, "Connection reset by peer"), error.NameTooLong => return EmptyResponse.initError(id, 36, "File name too long"), error.NoDevice => return EmptyResponse.initError(id, 19, "No such device"), error.DeviceBusy => return EmptyResponse.initError(id, 16, "Device or resource busy"), error.FileTooBig => return EmptyResponse.initError(id, 27, "File too large"), error.NoSpaceLeft => return EmptyResponse.initError(id, 28, "No space left on device"), error.IsDir => return EmptyResponse.initError(id, 21, "Is a directory"), error.NotOpenForReading => return EmptyResponse.initError(id, 77, "File descriptor in bad state, not open for reading"), error.InputOutput => return EmptyResponse.initError(id, 5, "Input/output error"), // Other OS-specific issues error.BadPathName => return EmptyResponse.initError(id, 1001, "On Windows, file paths cannot contain these characters: '/', '*', '?', '\"', '<', '>', '|'"), error.InvalidUtf8 => return EmptyResponse.initError(id, 1002, "On Windows, file paths must be valid Unicode."), error.OperationAborted => return EmptyResponse.initError(id, 1003, "Operation aborted"), error.Unexpected => return EmptyResponse.initError(id, 999, "Unexpected error, language-level bug"), // Application errors error.UninitializedClient => return EmptyResponse.initError(id, 2001, "Client is not initialized"), } unreachable; } pub fn request( comptime ParamsShape: type, id: ?u32, method: []const u8, params: ?ParamsShape, ) Request(ParamsShape) { return Request(ParamsShape).init(id, method, params); } pub fn commandRequest( comptime command_kind: kisa.CommandKind, id: ?u32, params: meta.TagPayload(kisa.Command, command_kind), ) Request(meta.TagPayload(kisa.Command, command_kind)) { return request( meta.TagPayload(kisa.Command, command_kind), id, comptime meta.tagName(command_kind), params, ); } pub fn emptyCommandRequest(comptime command_kind: kisa.CommandKind, id: ?u32) EmptyRequest { return EmptyRequest.init(id, comptime meta.tagName(command_kind), null); } pub fn emptyNotification( method: []const u8, ) Request([]bool) { return Request([]bool).init(null, method, null); } pub fn response( comptime ResultShape: type, id: ?u32, result: ResultShape, ) Response(ResultShape) { return Response(ResultShape).initSuccess(id, result); } pub fn parseRequest( comptime ParamsShape: type, buf: []u8, string: []const u8, ) !Request(ParamsShape) { return try Request(ParamsShape).parse(buf, string); } pub fn parseResponse( comptime ResultShape: type, buf: []u8, string: []const u8, ) !Response(ResultShape) { return try Response(ResultShape).parse(buf, string); } pub fn parseCommandFromRequest( comptime command_kind: kisa.CommandKind, buf: []u8, string: []const u8, ) !kisa.Command { const Payload = meta.TagPayload(kisa.Command, command_kind); switch (@typeInfo(Payload)) { .Void => { _ = EmptyRequest.parse(buf, string) catch return error.InvalidRequest; return @unionInit(kisa.Command, comptime meta.tagName(command_kind), {}); }, else => { const req = Request(Payload).parse(buf, string) catch |err| switch (err) { error.MissingField => return error.InvalidParams, else => return error.InvalidRequest, }; return @unionInit(kisa.Command, comptime meta.tagName(command_kind), req.params.?); }, } } pub fn parseId(string: []const u8) !?u32 { switch (rpcImplementation) { .jsonrpc => { const id_value = jsonrpc.parseId(null, string) catch |err| switch (err) { error.MissingField => return error.MissingField, else => return error.ParseError, }; if (id_value) |id| { return @intCast(u32, id.Integer); } else { return null; } }, } unreachable; } pub fn parseMethod(buf: []u8, string: []const u8) ![]u8 { switch (rpcImplementation) { .jsonrpc => { return jsonrpc.parseMethod(buf, string) catch |err| switch (err) { error.MissingField => return error.MethodNotFound, else => return error.ParseError, }; }, } } fn RequestType(comptime kind: RpcKind, comptime ParamsShape: type) type { return struct { /// Identification of a message, when ID is `null`, it means there's no response expected. id: ?u32, /// Name of a remote procedure. method: []const u8, /// Parameters to the `method`. params: ?ParamsShape, const Self = @This(); const RequestImpl = switch (kind) { .jsonrpc => jsonrpc.Request(ParamsShape), }; pub fn init(id: ?u32, method: []const u8, params: ?ParamsShape) Self { return Self{ .id = id, .method = method, .params = params }; } /// Turns message into string representation. pub fn generate(self: Self, buf: []u8) ![]u8 { switch (kind) { .jsonrpc => { const message = blk: { if (self.id) |id| { break :blk RequestImpl.init( jsonrpc.IdValue{ .Integer = id }, self.method, self.params, ); } else { break :blk RequestImpl.initNotification(self.method, self.params); } }; return try message.generate(buf); }, } unreachable; } pub fn parse(buf: []u8, string: []const u8) !Self { switch (kind) { .jsonrpc => { const jsonrpc_message = try RequestImpl.parse(buf, string); switch (jsonrpc_message) { .Request => |s| { return Self{ .id = @intCast(u32, s.id.?.Integer), .method = s.method, .params = s.params, }; }, .RequestNoParams => |s| { return Self{ .id = @intCast(u32, s.id.?.Integer), .method = s.method, .params = null, }; }, .Notification => |s| { return Self{ .id = null, .method = s.method, .params = s.params, }; }, .NotificationNoParams => |s| { return Self{ .id = null, .method = s.method, .params = null, }; }, } }, } unreachable; } }; } fn ResponseType(comptime kind: RpcKind, comptime ResultShape: type) type { return union(enum) { Success: struct { /// Identification of a message, must be same as the ID of the request. /// When ID is `null`, it means there's specific request to respond to. id: ?u32, /// Result of a request, by convention when nothing is needed it is `true`. result: ResultShape, }, Error: struct { /// Identification of a message, must be same as the ID of the request. /// When ID is `null`, it means there's specific request to respond to. id: ?u32, /// Error code, a mix of Linux-specific codes and HTTP error codes. code: i64, /// Error message describing the error code. message: []const u8, }, const Self = @This(); const ResponseImpl = switch (kind) { .jsonrpc => jsonrpc.Response(ResultShape, bool), }; pub fn initSuccess(id: ?u32, result: ResultShape) Self { return Self{ .Success = .{ .id = id, .result = result } }; } pub fn initError(id: ?u32, code: i32, message: []const u8) Self { return Self{ .Error = .{ .id = id, .code = code, .message = message } }; } /// Turns message into string representation. pub fn generate(self: Self, buf: []u8) ![]u8 { switch (kind) { .jsonrpc => { const message = blk: { switch (self) { .Success => |s| { if (s.id) |id| { break :blk ResponseImpl.initResult( jsonrpc.IdValue{ .Integer = id }, s.result, ); } else { break :blk ResponseImpl.initResult( null, s.result, ); } }, .Error => |e| { if (e.id) |id| { break :blk ResponseImpl.initError( jsonrpc.IdValue{ .Integer = id }, e.code, e.message, null, ); } else { break :blk ResponseImpl.initError( null, e.code, e.message, null, ); } }, } }; return try message.generate(buf); }, } unreachable; } pub fn parse(buf: []u8, string: []const u8) !Self { switch (kind) { .jsonrpc => { const jsonrpc_message = try ResponseImpl.parse(buf, string); switch (jsonrpc_message) { .Result => |r| { if (r.id) |id| { return Self{ .Success = .{ .id = @intCast(u32, id.Integer), .result = r.result, } }; } else { return Self{ .Success = .{ .id = null, .result = r.result, } }; } }, .Error => |e| { if (e.id) |id| { return Self{ .Error = .{ .id = @intCast(u32, id.Integer), .code = jsonrpc_message.errorCode(), .message = jsonrpc_message.errorMessage(), } }; } else { return Self{ .Error = .{ .id = null, .code = jsonrpc_message.errorCode(), .message = jsonrpc_message.errorMessage(), } }; } }, } }, } unreachable; } }; } const MyRequest = RequestType(.jsonrpc, []const u32); const Person = struct { name: []const u8, age: u32 }; const PersonRequest = RequestType(.jsonrpc, Person); const MyResponse = ResponseType(.jsonrpc, []const u32); const PersonResponse = ResponseType(.jsonrpc, Person); fn testMyRequest(want: MyRequest, message: MyRequest) !void { try testing.expectEqual(want.id, message.id); try testing.expectEqualStrings(want.method, message.method); if (want.params) |params| { try testing.expectEqual(params.len, message.params.?.len); try testing.expectEqual(params[0], message.params.?[0]); } else { try testing.expectEqual(@as(?[]const u32, null), message.params); } } fn testPersonRequest(want: PersonRequest, message: PersonRequest) !void { try testing.expectEqual(want.id, message.id); try testing.expectEqualStrings(want.method, message.method); try testing.expectEqualStrings(want.params.?.name, message.params.?.name); try testing.expectEqual(want.params.?.age, message.params.?.age); } fn testMyResponse(want: MyResponse, message: MyResponse) !void { switch (want) { .Success => |s| { try testing.expectEqual(s.id, message.Success.id); try testing.expectEqual(s.result.len, message.Success.result.len); try testing.expectEqual(s.result[0], message.Success.result[0]); }, .Error => |e| { try testing.expectEqual(e.id, message.Error.id); try testing.expectEqual(e.code, message.Error.code); try testing.expectEqualStrings(e.message, message.Error.message); }, } } fn testPersonResponse(want: PersonResponse, message: PersonResponse) !void { switch (want) { .Success => |s| { try testing.expectEqual(s.id, message.Success.id); try testing.expectEqualStrings(s.result.name, message.Success.result.name); try testing.expectEqual(s.result.age, message.Success.result.age); }, .Error => |e| { try testing.expectEqual(e.id, message.Error.id); try testing.expectEqual(e.code, message.Error.code); try testing.expectEqualStrings(e.message, message.Error.message); }, } } test "myrpc: jsonrpc generates and parses a request string" { var generate_buf: [256]u8 = undefined; var parse_buf: [256]u8 = undefined; { const message = MyRequest.init(1, "startParty", &[_]u32{18}); const want = \\{"jsonrpc":"2.0","method":"startParty","id":1,"params":[18]} ; try testing.expectEqualStrings(want, try message.generate(&generate_buf)); const parsed = try MyRequest.parse(&parse_buf, want); try testMyRequest(message, parsed); } { const message = MyRequest.init(null, "startParty", &[_]u32{18}); const want = \\{"jsonrpc":"2.0","method":"startParty","params":[18]} ; try testing.expectEqualStrings(want, try message.generate(&generate_buf)); const parsed = try MyRequest.parse(&parse_buf, want); try testMyRequest(message, parsed); } { const message = MyRequest.init(null, "startParty", null); const want = \\{"jsonrpc":"2.0","method":"startParty"} ; try testing.expectEqualStrings(want, try message.generate(&generate_buf)); const parsed = try MyRequest.parse(&parse_buf, want); try testMyRequest(message, parsed); } { const message = MyRequest.init(1, "startParty", null); const want = \\{"jsonrpc":"2.0","method":"startParty","id":1} ; try testing.expectEqualStrings(want, try message.generate(&generate_buf)); const parsed = try MyRequest.parse(&parse_buf, want); try testMyRequest(message, parsed); } { const message = PersonRequest.init(null, "startParty", Person{ .name = "Bob", .age = 37 }); const want = \\{"jsonrpc":"2.0","method":"startParty","params":{"name":"Bob","age":37}} ; try testing.expectEqualStrings(want, try message.generate(&generate_buf)); const parsed = try PersonRequest.parse(&parse_buf, want); try testPersonRequest(message, parsed); } { const message = request([]const u32, 1, "startParty", &[_]u32{18}); const want = \\{"jsonrpc":"2.0","method":"startParty","id":1,"params":[18]} ; try testing.expectEqualStrings(want, try message.generate(&generate_buf)); const parsed = try parseRequest([]const u32, &parse_buf, want); try testMyRequest(message, parsed); } } test "myrpc: jsonrpc generates and parses a response string" { var generate_buf: [256]u8 = undefined; var parse_buf: [256]u8 = undefined; { const message = MyResponse.initSuccess(1, &[_]u32{18}); const want = \\{"jsonrpc":"2.0","id":1,"result":[18]} ; try testing.expectEqualStrings(want, try message.generate(&generate_buf)); const parsed = try MyResponse.parse(&parse_buf, want); try testMyResponse(message, parsed); } { const message = MyResponse.initSuccess(null, &[_]u32{18}); const want = \\{"jsonrpc":"2.0","id":null,"result":[18]} ; try testing.expectEqualStrings(want, try message.generate(&generate_buf)); const parsed = try MyResponse.parse(&parse_buf, want); try testMyResponse(message, parsed); } { const message = PersonResponse.initSuccess(1, Person{ .name = "Bob", .age = 37 }); const want = \\{"jsonrpc":"2.0","id":1,"result":{"name":"Bob","age":37}} ; try testing.expectEqualStrings(want, try message.generate(&generate_buf)); const parsed = try PersonResponse.parse(&parse_buf, want); try testPersonResponse(message, parsed); } { const message = MyResponse.initError(1, 2, "ENOENT"); const want = \\{"jsonrpc":"2.0","id":1,"error":{"code":2,"message":"ENOENT"}} ; try testing.expectEqualStrings(want, try message.generate(&generate_buf)); const parsed = try MyResponse.parse(&parse_buf, want); try testMyResponse(message, parsed); } { const message = MyResponse.initError(null, 2, "ENOENT"); const want = \\{"jsonrpc":"2.0","id":null,"error":{"code":2,"message":"ENOENT"}} ; try testing.expectEqualStrings(want, try message.generate(&generate_buf)); const parsed = try MyResponse.parse(&parse_buf, want); try testMyResponse(message, parsed); } { const message = response([]const u32, 1, &[_]u32{18}); const want = \\{"jsonrpc":"2.0","id":1,"result":[18]} ; try testing.expectEqualStrings(want, try message.generate(&generate_buf)); const parsed = try parseResponse([]const u32, &parse_buf, want); try testMyResponse(message, parsed); } }
src/rpc.zig
const std = @import("std"); const expect = std.testing.expect; pub const TokenList = std.SegmentedList(CToken, 32); pub const CToken = struct { id: Id, bytes: []const u8, num_lit_suffix: NumLitSuffix = .None, pub const Id = enum { CharLit, StrLit, NumLitInt, NumLitFloat, Identifier, Minus, Slash, LParen, RParen, Eof, Dot, Asterisk, Bang, Tilde, Shl, Lt, Comma, Fn, Arrow, LBrace, RBrace, Pipe, }; pub const NumLitSuffix = enum { None, F, L, U, LU, LL, LLU, }; }; pub fn tokenizeCMacro(tl: *TokenList, chars: [*:0]const u8) !void { var index: usize = 0; var first = true; while (true) { const tok = try next(chars, &index); if (tok.id == .StrLit or tok.id == .CharLit) try tl.push(try zigifyEscapeSequences(tl.allocator, tok)) else try tl.push(tok); if (tok.id == .Eof) return; if (first) { // distinguish NAME (EXPR) from NAME(ARGS) first = false; if (chars[index] == '(') { try tl.push(.{ .id = .Fn, .bytes = "", }); } } } } fn zigifyEscapeSequences(allocator: *std.mem.Allocator, tok: CToken) !CToken { for (tok.bytes) |c| { if (c == '\\') { break; } } else return tok; var bytes = try allocator.alloc(u8, tok.bytes.len * 2); var state: enum { Start, Escape, Hex, Octal, } = .Start; var i: usize = 0; var count: u8 = 0; var num: u8 = 0; for (tok.bytes) |c| { switch (state) { .Escape => { switch (c) { 'n', 'r', 't', '\\', '\'', '\"' => { bytes[i] = c; }, '0'...'7' => { count += 1; num += c - '0'; state = .Octal; bytes[i] = 'x'; }, 'x' => { state = .Hex; bytes[i] = 'x'; }, 'a' => { bytes[i] = 'x'; i += 1; bytes[i] = '0'; i += 1; bytes[i] = '7'; }, 'b' => { bytes[i] = 'x'; i += 1; bytes[i] = '0'; i += 1; bytes[i] = '8'; }, 'f' => { bytes[i] = 'x'; i += 1; bytes[i] = '0'; i += 1; bytes[i] = 'C'; }, 'v' => { bytes[i] = 'x'; i += 1; bytes[i] = '0'; i += 1; bytes[i] = 'B'; }, '?' => { i -= 1; bytes[i] = '?'; }, 'u', 'U' => { // TODO unicode escape sequences return error.TokenizingFailed; }, else => { // unknown escape sequence return error.TokenizingFailed; }, } i += 1; if (state == .Escape) state = .Start; }, .Start => { if (c == '\\') { state = .Escape; } bytes[i] = c; i += 1; }, .Hex => { switch (c) { '0'...'9' => { num = std.math.mul(u8, num, 16) catch return error.TokenizingFailed; num += c - '0'; }, 'a'...'f' => { num = std.math.mul(u8, num, 16) catch return error.TokenizingFailed; num += c - 'a' + 10; }, 'A'...'F' => { num = std.math.mul(u8, num, 16) catch return error.TokenizingFailed; num += c - 'A' + 10; }, else => { i += std.fmt.formatIntBuf(bytes[i..], num, 16, false, std.fmt.FormatOptions{.fill = '0', .width = 2}); num = 0; if (c == '\\') state = .Escape else state = .Start; bytes[i] = c; i += 1; }, } }, .Octal => { switch (c) { '0'...'7' => { count += 1; num = std.math.mul(u8, num, 8) catch return error.TokenizingFailed; num += c - '0'; if (count < 3) continue; }, else => {}, } i += std.fmt.formatIntBuf(bytes[i..], num, 16, false, std.fmt.FormatOptions{.fill = '0', .width = 2}); state = .Start; count = 0; num = 0; }, } } if (state == .Hex or state == .Octal) i += std.fmt.formatIntBuf(bytes[i..], num, 16, false, std.fmt.FormatOptions{.fill = '0', .width = 2}); return CToken{ .id = tok.id, .bytes = bytes[0..i], }; } fn next(chars: [*:0]const u8, i: *usize) !CToken { var state: enum { Start, GotLt, CharLit, OpenComment, Comment, CommentStar, Backslash, String, Identifier, Decimal, Octal, GotZero, Hex, Bin, Float, ExpSign, FloatExp, FloatExpFirst, NumLitIntSuffixU, NumLitIntSuffixL, NumLitIntSuffixLL, NumLitIntSuffixUL, Minus, Done, } = .Start; var result = CToken{ .bytes = "", .id = .Eof, }; var begin_index: usize = 0; var digits: u8 = 0; var pre_escape = state; while (true) { const c = chars[i.*]; if (c == 0) { switch (state) { .Identifier, .Decimal, .Hex, .Bin, .Octal, .GotZero, .Float, .FloatExp, => { result.bytes = chars[begin_index..i.*]; return result; }, .Start, .Minus, .Done, .NumLitIntSuffixU, .NumLitIntSuffixL, .NumLitIntSuffixUL, .NumLitIntSuffixLL, .GotLt, => { return result; }, .CharLit, .OpenComment, .Comment, .CommentStar, .Backslash, .String, .ExpSign, .FloatExpFirst, => return error.TokenizingFailed, } } switch (state) { .Start => { switch (c) { ' ', '\t', '\x0B', '\x0C' => {}, '\'' => { state = .CharLit; result.id = .CharLit; begin_index = i.*; }, '\"' => { state = .String; result.id = .StrLit; begin_index = i.*; }, '/' => { state = .OpenComment; }, '\\' => { state = .Backslash; }, '\n', '\r' => { return result; }, 'a'...'z', 'A'...'Z', '_' => { state = .Identifier; result.id = .Identifier; begin_index = i.*; }, '1'...'9' => { state = .Decimal; result.id = .NumLitInt; begin_index = i.*; }, '0' => { state = .GotZero; result.id = .NumLitInt; begin_index = i.*; }, '.' => { result.id = .Dot; state = .Done; }, '<' => { result.id = .Lt; state = .GotLt; }, '(' => { result.id = .LParen; state = .Done; }, ')' => { result.id = .RParen; state = .Done; }, '*' => { result.id = .Asterisk; state = .Done; }, '-' => { state = .Minus; result.id = .Minus; }, '!' => { result.id = .Bang; state = .Done; }, '~' => { result.id = .Tilde; state = .Done; }, ',' => { result.id = .Comma; state = .Done; }, '[' => { result.id = .LBrace; state = .Done; }, ']' => { result.id = .RBrace; state = .Done; }, '|' => { result.id = .Pipe; state = .Done; }, else => return error.TokenizingFailed, } }, .Done => return result, .Minus => { switch (c) { '>' => { result.id = .Arrow; state = .Done; }, else => { return result; }, } }, .GotLt => { switch (c) { '<' => { result.id = .Shl; state = .Done; }, else => { return result; }, } }, .Float => { switch (c) { '.', '0'...'9' => {}, 'e', 'E' => { state = .ExpSign; }, 'f', 'F', => { result.num_lit_suffix = .F; result.bytes = chars[begin_index..i.*]; state = .Done; }, 'l', 'L' => { result.num_lit_suffix = .L; result.bytes = chars[begin_index..i.*]; state = .Done; }, else => { result.bytes = chars[begin_index..i.*]; return result; }, } }, .ExpSign => { switch (c) { '+', '-' => { state = .FloatExpFirst; }, '0'...'9' => { state = .FloatExp; }, else => return error.TokenizingFailed, } }, .FloatExpFirst => { switch (c) { '0'...'9' => { state = .FloatExp; }, else => return error.TokenizingFailed, } }, .FloatExp => { switch (c) { '0'...'9' => {}, 'f', 'F' => { result.num_lit_suffix = .F; result.bytes = chars[begin_index..i.*]; state = .Done; }, 'l', 'L' => { result.num_lit_suffix = .L; result.bytes = chars[begin_index..i.*]; state = .Done; }, else => { result.bytes = chars[begin_index..i.*]; return result; }, } }, .Decimal => { switch (c) { '0'...'9' => {}, '\'' => {}, 'u', 'U' => { state = .NumLitIntSuffixU; result.num_lit_suffix = .U; result.bytes = chars[begin_index..i.*]; }, 'l', 'L' => { state = .NumLitIntSuffixL; result.num_lit_suffix = .L; result.bytes = chars[begin_index..i.*]; }, '.' => { result.id = .NumLitFloat; state = .Float; }, else => { result.bytes = chars[begin_index..i.*]; return result; }, } }, .GotZero => { switch (c) { 'x', 'X' => { state = .Hex; }, 'b', 'B' => { state = .Bin; }, '.' => { state = .Float; result.id = .NumLitFloat; }, 'u', 'U' => { state = .NumLitIntSuffixU; result.num_lit_suffix = .U; result.bytes = chars[begin_index..i.*]; }, 'l', 'L' => { state = .NumLitIntSuffixL; result.num_lit_suffix = .L; result.bytes = chars[begin_index..i.*]; }, else => { i.* -= 1; state = .Octal; }, } }, .Octal => { switch (c) { '0'...'7' => {}, '8', '9' => return error.TokenizingFailed, else => { result.bytes = chars[begin_index..i.*]; return result; }, } }, .Hex => { switch (c) { '0'...'9', 'a'...'f', 'A'...'F' => {}, 'u', 'U' => { // marks the number literal as unsigned state = .NumLitIntSuffixU; result.num_lit_suffix = .U; result.bytes = chars[begin_index..i.*]; }, 'l', 'L' => { // marks the number literal as long state = .NumLitIntSuffixL; result.num_lit_suffix = .L; result.bytes = chars[begin_index..i.*]; }, else => { result.bytes = chars[begin_index..i.*]; return result; }, } }, .Bin => { switch (c) { '0'...'1' => {}, '2'...'9' => return error.TokenizingFailed, 'u', 'U' => { // marks the number literal as unsigned state = .NumLitIntSuffixU; result.num_lit_suffix = .U; result.bytes = chars[begin_index..i.*]; }, 'l', 'L' => { // marks the number literal as long state = .NumLitIntSuffixL; result.num_lit_suffix = .L; result.bytes = chars[begin_index..i.*]; }, else => { result.bytes = chars[begin_index..i.*]; return result; }, } }, .NumLitIntSuffixU => { switch (c) { 'l', 'L' => { result.num_lit_suffix = .LU; state = .NumLitIntSuffixUL; }, else => { return result; }, } }, .NumLitIntSuffixL => { switch (c) { 'l', 'L' => { result.num_lit_suffix = .LL; state = .NumLitIntSuffixLL; }, 'u', 'U' => { result.num_lit_suffix = .LU; state = .Done; }, else => { return result; }, } }, .NumLitIntSuffixLL => { switch (c) { 'u', 'U' => { result.num_lit_suffix = .LLU; state = .Done; }, else => { return result; }, } }, .NumLitIntSuffixUL => { switch (c) { 'l', 'L' => { result.num_lit_suffix = .LLU; state = .Done; }, else => { return result; }, } }, .Identifier => { switch (c) { '_', 'a'...'z', 'A'...'Z', '0'...'9' => {}, else => { result.bytes = chars[begin_index..i.*]; return result; }, } }, .String => { switch (c) { '\"' => { result.bytes = chars[begin_index .. i.* + 1]; state = .Done; }, else => {}, } }, .CharLit => { switch (c) { '\'' => { result.bytes = chars[begin_index .. i.* + 1]; state = .Done; }, else => {}, } }, .OpenComment => { switch (c) { '/' => { return result; }, '*' => { state = .Comment; }, else => { result.id = .Slash; state = .Done; }, } }, .Comment => { switch (c) { '*' => { state = .CommentStar; }, else => {}, } }, .CommentStar => { switch (c) { '/' => { state = .Start; }, else => { state = .Comment; }, } }, .Backslash => { switch (c) { ' ', '\t', '\x0B', '\x0C' => {}, '\n', '\r' => { state = .Start; }, else => return error.TokenizingFailed, } }, } i.* += 1; } unreachable; } test "tokenize macro" { var tl = TokenList.init(std.heap.page_allocator); defer tl.deinit(); const src = "TEST(0\n"; try tokenizeCMacro(&tl, src); var it = tl.iterator(0); expect(it.next().?.id == .Identifier); expect(it.next().?.id == .Fn); expect(it.next().?.id == .LParen); expect(std.mem.eql(u8, it.next().?.bytes, "0")); expect(it.next().?.id == .Eof); expect(it.next() == null); tl.shrink(0); const src2 = "__FLT_MIN_10_EXP__ -37\n"; try tokenizeCMacro(&tl, src2); it = tl.iterator(0); expect(std.mem.eql(u8, it.next().?.bytes, "__FLT_MIN_10_EXP__")); expect(it.next().?.id == .Minus); expect(std.mem.eql(u8, it.next().?.bytes, "37")); expect(it.next().?.id == .Eof); expect(it.next() == null); tl.shrink(0); const src3 = "__llvm__ 1\n#define"; try tokenizeCMacro(&tl, src3); it = tl.iterator(0); expect(std.mem.eql(u8, it.next().?.bytes, "__llvm__")); expect(std.mem.eql(u8, it.next().?.bytes, "1")); expect(it.next().?.id == .Eof); expect(it.next() == null); tl.shrink(0); const src4 = "TEST 2"; try tokenizeCMacro(&tl, src4); it = tl.iterator(0); expect(it.next().?.id == .Identifier); expect(std.mem.eql(u8, it.next().?.bytes, "2")); expect(it.next().?.id == .Eof); expect(it.next() == null); tl.shrink(0); const src5 = "FOO 0ull"; try tokenizeCMacro(&tl, src5); it = tl.iterator(0); expect(it.next().?.id == .Identifier); expect(std.mem.eql(u8, it.next().?.bytes, "0")); expect(it.next().?.id == .Eof); expect(it.next() == null); tl.shrink(0); } test "escape sequences" { var buf: [1024]u8 = undefined; var alloc = std.heap.FixedBufferAllocator.init(buf[0..]); const a = &alloc.allocator; expect(std.mem.eql(u8, (try zigifyEscapeSequences(a, .{ .id = .StrLit, .bytes = "\\x0077", })).bytes, "\\x77")); expect(std.mem.eql(u8, (try zigifyEscapeSequences(a, .{ .id = .StrLit, .bytes = "\\24500", })).bytes, "\\xa500")); expect(std.mem.eql(u8, (try zigifyEscapeSequences(a, .{ .id = .StrLit, .bytes = "\\x0077 abc", })).bytes, "\\x77 abc")); expect(std.mem.eql(u8, (try zigifyEscapeSequences(a, .{ .id = .StrLit, .bytes = "\\045abc", })).bytes, "\\x25abc")); }
src-self-hosted/c_tokenizer.zig
const std = @import("std"); const testing = std.testing; const TypeId = @import("builtin").TypeId; const TypeInfo = @import("builtin").TypeInfo; pub fn DivPair(comptime T: type) type { return struct { quotient: T, modulus: T, }; } pub fn signFlag(comptime T: type, val: T) u1 { if (@typeId(T) != TypeId.Int) { @compileError("signFlag requires an integer type"); } if (@typeInfo(T).Int.is_signed) { if (val < 0) { return 1; } else { return 0; } } else { return 0; } } pub fn abs(comptime T: type, val: T) T { if (@typeId(T) != TypeId.Int) { @compileError("abs requires an integer type"); } if (@typeInfo(T).Int.is_signed) { if (val < 0) { return -val; } else { return val; } } else { return val; } } /// flooredDivision is defined as q = floor(a/n) /// The quotient is always rounded downward, even if it is negative. pub fn flooredDivision(comptime T: type, dividend: T, divisor: T) DivPair(T) { if (@typeId(T) != TypeId.Int) { @compileError("flooredDivision requires an integer type"); } const s_divisor = signFlag(T, divisor); const abs_divisor = abs(T, divisor); var m: T = @rem(abs(T, dividend), abs_divisor); var d = dividend; if (m != 0 and signFlag(T, dividend) ^ s_divisor != 0) { d -= divisor; m = abs_divisor - m; } return DivPair(T){ .quotient = @divTrunc(d, divisor), .modulus = if (s_divisor != 0) -m else m, }; } /// truncatedDivision is defined as q = truncate(a/n). /// q will remain zero for -n < a < n. /// m always has the sign of the divisor. pub fn truncatedDivision(comptime T: type, dividend: T, divisor: T) DivPair(T) { const abs_divisor = abs(T, divisor); const q: T = @divTrunc(dividend, abs_divisor); const m: T = @rem(dividend, abs_divisor); return DivPair(T){ .quotient = if (signFlag(T, divisor) != 0) -q else q, .modulus = m, }; } /// euclideanDivision is defined as: q = floor(a/n), for n > 0; and q = ceil(a/n) for n < 0. /// The modulus is always 0 <= m < n. pub fn euclideanDivision(comptime T: type, dividend: T, divisor: T) DivPair(T) { const abs_divisor = abs(T, divisor); var m: T = @rem(abs(T, dividend), abs_divisor); var q: T = @divTrunc(dividend, divisor); if (m != 0) { if (signFlag(T, dividend) == 1) { m = abs_divisor - m; if (signFlag(T, divisor) == 1) { q += 1; } else { q -= 1; } } } return DivPair(T){ .quotient = q, .modulus = m, }; } test "flooredDivision quick" { var di = flooredDivision(i32, 10, 12); testing.expectEqual(i32(10), di.modulus); testing.expectEqual(i32(0), di.quotient); di = flooredDivision(i32, -14, 12); testing.expectEqual(i32(10), di.modulus); testing.expectEqual(i32(-2), di.quotient); di = flooredDivision(i32, -2, 12); testing.expectEqual(i32(10), di.modulus); testing.expectEqual(i32(-1), di.quotient); } test "flooredDivision full" { const TestDivIntegerElem = struct { N: i32, D: i32, Q: i32, M: i32, }; const testData = []TestDivIntegerElem{ TestDivIntegerElem{ .N = 180, .D = 131, .Q = 1, .M = 49 }, TestDivIntegerElem{ .N = -180, .D = 131, .Q = -2, .M = 82 }, TestDivIntegerElem{ .N = 180, .D = -131, .Q = -2, .M = -82 }, TestDivIntegerElem{ .N = -180, .D = -131, .Q = 1, .M = -49 }, TestDivIntegerElem{ .N = 180, .D = 31, .Q = 5, .M = 25 }, TestDivIntegerElem{ .N = -180, .D = 31, .Q = -6, .M = 6 }, TestDivIntegerElem{ .N = 180, .D = -31, .Q = -6, .M = -6 }, TestDivIntegerElem{ .N = -180, .D = -31, .Q = 5, .M = -25 }, TestDivIntegerElem{ .N = 18, .D = 3, .Q = 6, .M = 0 }, TestDivIntegerElem{ .N = -18, .D = 3, .Q = -6, .M = 0 }, TestDivIntegerElem{ .N = 18, .D = -3, .Q = -6, .M = 0 }, TestDivIntegerElem{ .N = -18, .D = -3, .Q = 6, .M = 0 }, TestDivIntegerElem{ .N = 0, .D = -3, .Q = 0, .M = 0 }, TestDivIntegerElem{ .N = 0, .D = -3, .Q = 0, .M = 0 }, }; for (testData) |elem| { const di = flooredDivision(i32, elem.N, elem.D); testing.expectEqual(elem.Q, di.quotient); testing.expectEqual(elem.M, di.modulus); } } const IdtIdx = enum(usize) { A, N, Q, R, }; const truncatedTable = []const [@memberCount(IdtIdx)]i32 { []i32{ -10, 3, -3, -1, }, []i32{ -9, 3, -3, 0, }, []i32{ -8, 3, -2, -2, }, []i32{ -7, 3, -2, -1, }, []i32{ -6, 3, -2, 0, }, []i32{ -5, 3, -1, -2, }, []i32{ -4, 3, -1, -1, }, []i32{ -3, 3, -1, 0, }, []i32{ -2, 3, 0, -2, }, []i32{ -1, 3, 0, -1, }, []i32{ 0, 3, 0, 0, }, []i32{ 1, 3, 0, 1, }, []i32{ 2, 3, 0, 2, }, []i32{ 3, 3, 1, 0, }, []i32{ 4, 3, 1, 1, }, []i32{ 5, 3, 1, 2, }, []i32{ 6, 3, 2, 0, }, []i32{ 7, 3, 2, 1, }, []i32{ 8, 3, 2, 2, }, []i32{ 9, 3, 3, 0, }, []i32{ 10, 3, 3, 1, }, []i32{ -10, -3, 3, -1, }, []i32{ -9, -3, 3, 0, }, []i32{ -8, -3, 2, -2, }, []i32{ -7, -3, 2, -1, }, []i32{ -6, -3, 2, 0, }, []i32{ -5, -3, 1, -2, }, []i32{ -4, -3, 1, -1, }, []i32{ -3, -3, 1, 0, }, []i32{ -2, -3, 0, -2, }, []i32{ -1, -3, 0, -1, }, []i32{ 0, -3, 0, 0, }, []i32{ 1, -3, 0, 1, }, []i32{ 2, -3, 0, 2, }, []i32{ 3, -3, -1, 0, }, []i32{ 4, -3, -1, 1, }, []i32{ 5, -3, -1, 2, }, []i32{ 6, -3, -2, 0, }, []i32{ 7, -3, -2, 1, }, []i32{ 8, -3, -2, 2, }, []i32{ 9, -3, -3, 0, }, []i32{ 10, -3, -3, 1, }, }; const flooredTable = []const [@memberCount(IdtIdx)]i32 { []i32{ -10, 3, -4, 2, }, []i32{ -9, 3, -3, 0, }, []i32{ -8, 3, -3, 1, }, []i32{ -7, 3, -3, 2, }, []i32{ -6, 3, -2, 0, }, []i32{ -5, 3, -2, 1, }, []i32{ -4, 3, -2, 2, }, []i32{ -3, 3, -1, 0, }, []i32{ -2, 3, -1, 1, }, []i32{ -1, 3, -1, 2, }, []i32{ 0, 3, 0, 0, }, []i32{ 1, 3, 0, 1, }, []i32{ 2, 3, 0, 2, }, []i32{ 3, 3, 1, 0, }, []i32{ 4, 3, 1, 1, }, []i32{ 5, 3, 1, 2, }, []i32{ 6, 3, 2, 0, }, []i32{ 7, 3, 2, 1, }, []i32{ 8, 3, 2, 2, }, []i32{ 9, 3, 3, 0, }, []i32{ 10, 3, 3, 1, }, []i32{ -10, -3, 3, -1, }, []i32{ -9, -3, 3, 0, }, []i32{ -8, -3, 2, -2, }, []i32{ -7, -3, 2, -1, }, []i32{ -6, -3, 2, 0, }, []i32{ -5, -3, 1, -2, }, []i32{ -4, -3, 1, -1, }, []i32{ -3, -3, 1, 0, }, []i32{ -2, -3, 0, -2, }, []i32{ -1, -3, 0, -1, }, []i32{ 0, -3, 0, 0, }, []i32{ 1, -3, -1, -2, }, []i32{ 2, -3, -1, -1, }, []i32{ 3, -3, -1, 0, }, []i32{ 4, -3, -2, -2, }, []i32{ 5, -3, -2, -1, }, []i32{ 6, -3, -2, 0, }, []i32{ 7, -3, -3, -2, }, []i32{ 8, -3, -3, -1, }, []i32{ 9, -3, -3, 0, }, []i32{ 10, -3, -4, -2, }, }; const euclideanTable = []const [@memberCount(IdtIdx)]i32 { []i32{ -10, 3, -4, 2, }, []i32{ -9, 3, -3, 0, }, []i32{ -8, 3, -3, 1, }, []i32{ -7, 3, -3, 2, }, []i32{ -6, 3, -2, 0, }, []i32{ -5, 3, -2, 1, }, []i32{ -4, 3, -2, 2, }, []i32{ -3, 3, -1, 0, }, []i32{ -2, 3, -1, 1, }, []i32{ -1, 3, -1, 2, }, []i32{ 0, 3, 0, 0, }, []i32{ 1, 3, 0, 1, }, []i32{ 2, 3, 0, 2, }, []i32{ 3, 3, 1, 0, }, []i32{ 4, 3, 1, 1, }, []i32{ 5, 3, 1, 2, }, []i32{ 6, 3, 2, 0, }, []i32{ 7, 3, 2, 1, }, []i32{ 8, 3, 2, 2, }, []i32{ 9, 3, 3, 0, }, []i32{ 10, 3, 3, 1, }, []i32{ -10, -3, 4, 2, }, []i32{ -9, -3, 3, 0, }, []i32{ -8, -3, 3, 1, }, []i32{ -7, -3, 3, 2, }, []i32{ -6, -3, 2, 0, }, []i32{ -5, -3, 2, 1, }, []i32{ -4, -3, 2, 2, }, []i32{ -3, -3, 1, 0, }, []i32{ -2, -3, 1, 1, }, []i32{ -1, -3, 1, 2, }, []i32{ 0, -3, 0, 0, }, []i32{ 1, -3, 0, 1, }, []i32{ 2, -3, 0, 2, }, []i32{ 3, -3, -1, 0, }, []i32{ 4, -3, -1, 1, }, []i32{ 5, -3, -1, 2, }, []i32{ 6, -3, -2, 0, }, []i32{ 7, -3, -2, 1, }, []i32{ 8, -3, -2, 2, }, []i32{ 9, -3, -3, 0, }, []i32{ 10, -3, -3, 1, }, }; const divisionOp = fn (type, i32, i32) DivPair(i32); fn run(comptime op: divisionOp, comptime table: []const [@memberCount(IdtIdx)]i32) void { for (table) |testcase| { const pair = op(i32, testcase[@enumToInt(IdtIdx.A)], testcase[@enumToInt(IdtIdx.N)]); const a2 = testcase[@enumToInt(IdtIdx.N)] * pair.quotient + pair.modulus; testing.expectEqual(testcase[@enumToInt(IdtIdx.A)], a2); testing.expectEqual(testcase[@enumToInt(IdtIdx.Q)], pair.quotient); testing.expectEqual(testcase[@enumToInt(IdtIdx.R)], pair.modulus); } } test "integer division" { const Pair = struct { op: divisionOp, table: []const [@memberCount(IdtIdx)]i32, }; const runs = []Pair{ Pair{ .op=flooredDivision, .table=flooredTable, }, Pair{ .op=truncatedDivision, .table=truncatedTable, }, Pair{ .op=euclideanDivision, .table=euclideanTable, }, }; inline for (runs) |pass| { run(pass.op, pass.table); } }
src/divInteger.zig
const nyancore_options = @import("nyancore_options"); const c = @import("../c.zig"); const std = @import("std"); const vk = @import("../vk.zig"); const builtin = @import("builtin"); const Allocator = std.mem.Allocator; const Application = @import("../application/application.zig").Application; const printError = @import("../application/print_error.zig").printError; const printErrorNoPanic = @import("../application/print_error.zig").printErrorNoPanic; pub extern fn glfwGetInstanceProcAddress(instance: vk.Instance, procname: [*:0]const u8) vk.PfnVoidFunction; pub extern fn glfwCreateWindowSurface(instance: vk.Instance, window: *c.GLFWwindow, alocation_callback: ?*const vk.AllocationCallbacks, surface: *vk.SurfaceKHR) vk.Result; const required_device_extensions: [1][:0]const u8 = [_][:0]const u8{ "VK_KHR_swapchain", }; const validation_layers: [1][:0]const u8 = [_][:0]const u8{ "VK_LAYER_KHRONOS_validation", }; pub const Buffer = struct { size: vk.DeviceSize, buffer: vk.Buffer, memory: vk.DeviceMemory, mapped_memory: *anyopaque, pub fn init(self: *Buffer, size: vk.DeviceSize, usage: vk.BufferUsageFlags, properties: vk.MemoryPropertyFlags) void { const buffer_info: vk.BufferCreateInfo = .{ .size = size, .usage = usage, .sharing_mode = .exclusive, .flags = .{}, .queue_family_index_count = 0, .p_queue_family_indices = undefined, }; self.buffer = vkd.createBuffer(vkc.device, buffer_info, null) catch |err| { printVulkanError("Can't create buffer for ui", err, vkc.allocator); return; }; var mem_req: vk.MemoryRequirements = vkd.getBufferMemoryRequirements(vkc.device, self.buffer); const alloc_info: vk.MemoryAllocateInfo = .{ .allocation_size = mem_req.size, .memory_type_index = vkc.getMemoryType(mem_req.memory_type_bits, properties), }; self.memory = vkd.allocateMemory(vkc.device, alloc_info, null) catch |err| { printVulkanError("Can't allocate buffer for ui", err, vkc.allocator); return; }; vkd.bindBufferMemory(vkc.device, self.buffer, self.memory, 0) catch |err| { printVulkanError("Can't bind buffer memory for ui", err, vkc.allocator); return; }; self.mapped_memory = vkd.mapMemory(vkc.device, self.memory, 0, size, .{}) catch |err| { printVulkanError("Can't map memory for ui", err, vkc.allocator); return; } orelse return; } pub fn flush(self: *Buffer) void { const mapped_range: vk.MappedMemoryRange = .{ .memory = self.memory, .offset = 0, .size = vk.WHOLE_SIZE, }; vkd.flushMappedMemoryRanges(vkc.device, 1, @ptrCast([*]const vk.MappedMemoryRange, &mapped_range)) catch |err| { printVulkanError("Can't flush buffer for ui", err, vkc.allocator); }; } pub fn destroy(self: *Buffer) void { vkd.unmapMemory(vkc.device, self.memory); vkd.destroyBuffer(vkc.device, self.buffer, null); vkd.freeMemory(vkc.device, self.memory, null); } }; const BaseDispatch = struct { vkCreateInstance: vk.PfnCreateInstance, vkEnumerateInstanceLayerProperties: vk.PfnEnumerateInstanceLayerProperties, usingnamespace vk.BaseWrapper(@This()); }; pub var vkb: BaseDispatch = undefined; const InstanceDispatch = if (nyancore_options.use_vulkan_sdk) struct { vkCreateDebugUtilsMessengerEXT: vk.PfnCreateDebugUtilsMessengerEXT, vkDestroyDebugUtilsMessengerEXT: vk.PfnDestroyDebugUtilsMessengerEXT, vkCreateDevice: vk.PfnCreateDevice, vkDestroyInstance: vk.PfnDestroyInstance, vkDestroySurfaceKHR: vk.PfnDestroySurfaceKHR, vkEnumerateDeviceExtensionProperties: vk.PfnEnumerateDeviceExtensionProperties, vkEnumeratePhysicalDevices: vk.PfnEnumeratePhysicalDevices, vkGetDeviceProcAddr: vk.PfnGetDeviceProcAddr, vkGetPhysicalDeviceMemoryProperties: vk.PfnGetPhysicalDeviceMemoryProperties, vkGetPhysicalDeviceQueueFamilyProperties: vk.PfnGetPhysicalDeviceQueueFamilyProperties, vkGetPhysicalDeviceSurfaceCapabilitiesKHR: vk.PfnGetPhysicalDeviceSurfaceCapabilitiesKHR, vkGetPhysicalDeviceSurfaceFormatsKHR: vk.PfnGetPhysicalDeviceSurfaceFormatsKHR, vkGetPhysicalDeviceSurfacePresentModesKHR: vk.PfnGetPhysicalDeviceSurfacePresentModesKHR, vkGetPhysicalDeviceSurfaceSupportKHR: vk.PfnGetPhysicalDeviceSurfaceSupportKHR, usingnamespace vk.InstanceWrapper(@This()); } else struct { vkCreateDevice: vk.PfnCreateDevice, vkDestroyInstance: vk.PfnDestroyInstance, vkDestroySurfaceKHR: vk.PfnDestroySurfaceKHR, vkEnumerateDeviceExtensionProperties: vk.PfnEnumerateDeviceExtensionProperties, vkEnumeratePhysicalDevices: vk.PfnEnumeratePhysicalDevices, vkGetDeviceProcAddr: vk.PfnGetDeviceProcAddr, vkGetPhysicalDeviceMemoryProperties: vk.PfnGetPhysicalDeviceMemoryProperties, vkGetPhysicalDeviceQueueFamilyProperties: vk.PfnGetPhysicalDeviceQueueFamilyProperties, vkGetPhysicalDeviceSurfaceCapabilitiesKHR: vk.PfnGetPhysicalDeviceSurfaceCapabilitiesKHR, vkGetPhysicalDeviceSurfaceFormatsKHR: vk.PfnGetPhysicalDeviceSurfaceFormatsKHR, vkGetPhysicalDeviceSurfacePresentModesKHR: vk.PfnGetPhysicalDeviceSurfacePresentModesKHR, vkGetPhysicalDeviceSurfaceSupportKHR: vk.PfnGetPhysicalDeviceSurfaceSupportKHR, usingnamespace vk.InstanceWrapper(@This()); }; pub var vki: InstanceDispatch = undefined; const DeviceDispatch = struct { vkAcquireNextImageKHR: vk.PfnAcquireNextImageKHR, vkAllocateCommandBuffers: vk.PfnAllocateCommandBuffers, vkAllocateDescriptorSets: vk.PfnAllocateDescriptorSets, vkAllocateMemory: vk.PfnAllocateMemory, vkBeginCommandBuffer: vk.PfnBeginCommandBuffer, vkBindBufferMemory: vk.PfnBindBufferMemory, vkBindImageMemory: vk.PfnBindImageMemory, vkCmdBeginRenderPass: vk.PfnCmdBeginRenderPass, vkCmdBindDescriptorSets: vk.PfnCmdBindDescriptorSets, vkCmdBindIndexBuffer: vk.PfnCmdBindIndexBuffer, vkCmdBindPipeline: vk.PfnCmdBindPipeline, vkCmdBindVertexBuffers: vk.PfnCmdBindVertexBuffers, vkCmdClearAttachments: vk.PfnCmdClearAttachments, vkCmdCopyBufferToImage: vk.PfnCmdCopyBufferToImage, vkCmdCopyImageToBuffer: vk.PfnCmdCopyImageToBuffer, vkCmdDispatch: vk.PfnCmdDispatch, vkCmdDraw: vk.PfnCmdDraw, vkCmdDrawIndexed: vk.PfnCmdDrawIndexed, vkCmdEndRenderPass: vk.PfnCmdEndRenderPass, vkCmdPipelineBarrier: vk.PfnCmdPipelineBarrier, vkCmdPushConstants: vk.PfnCmdPushConstants, vkCmdSetScissor: vk.PfnCmdSetScissor, vkCmdSetViewport: vk.PfnCmdSetViewport, vkCreateBuffer: vk.PfnCreateBuffer, vkCreateCommandPool: vk.PfnCreateCommandPool, vkCreateComputePipelines: vk.PfnCreateComputePipelines, vkCreateDescriptorPool: vk.PfnCreateDescriptorPool, vkCreateDescriptorSetLayout: vk.PfnCreateDescriptorSetLayout, vkCreateFence: vk.PfnCreateFence, vkCreateFramebuffer: vk.PfnCreateFramebuffer, vkCreateGraphicsPipelines: vk.PfnCreateGraphicsPipelines, vkCreateImage: vk.PfnCreateImage, vkCreateImageView: vk.PfnCreateImageView, vkCreatePipelineCache: vk.PfnCreatePipelineCache, vkCreatePipelineLayout: vk.PfnCreatePipelineLayout, vkCreateRenderPass: vk.PfnCreateRenderPass, vkCreateSampler: vk.PfnCreateSampler, vkCreateSemaphore: vk.PfnCreateSemaphore, vkCreateShaderModule: vk.PfnCreateShaderModule, vkCreateSwapchainKHR: vk.PfnCreateSwapchainKHR, vkDestroyBuffer: vk.PfnDestroyBuffer, vkDestroyCommandPool: vk.PfnDestroyCommandPool, vkDestroyDescriptorPool: vk.PfnDestroyDescriptorPool, vkDestroyDescriptorSetLayout: vk.PfnDestroyDescriptorSetLayout, vkDestroyDevice: vk.PfnDestroyDevice, vkDestroyFence: vk.PfnDestroyFence, vkDestroyFramebuffer: vk.PfnDestroyFramebuffer, vkDestroyImage: vk.PfnDestroyImage, vkDestroyImageView: vk.PfnDestroyImageView, vkDestroyPipeline: vk.PfnDestroyPipeline, vkDestroyPipelineCache: vk.PfnDestroyPipelineCache, vkDestroyPipelineLayout: vk.PfnDestroyPipelineLayout, vkDestroyRenderPass: vk.PfnDestroyRenderPass, vkDestroySampler: vk.PfnDestroySampler, vkDestroySemaphore: vk.PfnDestroySemaphore, vkDestroyShaderModule: vk.PfnDestroyShaderModule, vkDestroySwapchainKHR: vk.PfnDestroySwapchainKHR, vkDeviceWaitIdle: vk.PfnDeviceWaitIdle, vkEndCommandBuffer: vk.PfnEndCommandBuffer, vkFlushMappedMemoryRanges: vk.PfnFlushMappedMemoryRanges, vkFreeCommandBuffers: vk.PfnFreeCommandBuffers, vkFreeMemory: vk.PfnFreeMemory, vkGetBufferMemoryRequirements: vk.PfnGetBufferMemoryRequirements, vkGetDeviceQueue: vk.PfnGetDeviceQueue, vkGetFenceStatus: vk.PfnGetFenceStatus, vkGetImageMemoryRequirements: vk.PfnGetImageMemoryRequirements, vkGetSwapchainImagesKHR: vk.PfnGetSwapchainImagesKHR, vkMapMemory: vk.PfnMapMemory, vkQueuePresentKHR: vk.PfnQueuePresentKHR, vkQueueSubmit: vk.PfnQueueSubmit, vkQueueWaitIdle: vk.PfnQueueWaitIdle, vkResetCommandBuffer: vk.PfnResetCommandBuffer, vkResetFences: vk.PfnResetFences, vkUnmapMemory: vk.PfnUnmapMemory, vkUpdateDescriptorSets: vk.PfnUpdateDescriptorSets, vkWaitForFences: vk.PfnWaitForFences, usingnamespace vk.DeviceWrapper(@This()); }; pub var vkd: DeviceDispatch = undefined; pub const SwapchainSupportDetails = struct { capabilities: vk.SurfaceCapabilitiesKHR, formats: []vk.SurfaceFormatKHR, format_count: u32, present_modes: []vk.PresentModeKHR, present_mode_count: u32, }; const QueueFamilyIndices = struct { graphics_family: u32, present_family: u32, compute_family: u32, graphics_family_set: bool, present_family_set: bool, compute_family_set: bool, pub fn isComplete(self: *const QueueFamilyIndices) bool { return self.graphics_family_set and self.present_family_set and self.compute_family_set; } }; const VulkanError = error{ DeviceLost, ExtensionNotPresent, FeatureNotPresent, FragmentationEXT, FragmentedPool, HostAllocationError, IncompatibleDriver, InitializationFailed, InvalidExternalHandle, InvalidOpaqueCaptureAddressKHR, InvalidShaderNV, LayerNotPresent, MemoryMapFailed, NativeWindowInUseKHR, OutOfDeviceMemory, OutOfHostMemory, OutOfPoolMemory, SurfaceLostKHR, TooManyObjects, Unknown, ValidationLayerNotSupported, }; pub fn printVulkanError(comptime err_context: []const u8, err: VulkanError, allocator: Allocator) void { @setCold(true); const vulkan_error_message: []const u8 = switch (err) { error.DeviceLost => "Device lost", error.ExtensionNotPresent => "Extension not present", error.FeatureNotPresent => "Feature not present", error.FragmentationEXT => "Fragmentation", error.FragmentedPool => "Fragmented pool", error.HostAllocationError => "Error during allocation on host", error.IncompatibleDriver => "Incompatible driver", error.InitializationFailed => "Initialization failed", error.InvalidExternalHandle => "Invalid external handle", error.InvalidOpaqueCaptureAddressKHR => "Invalid opaque capture address KHR", error.InvalidShaderNV => "Invalid Shader", error.MemoryMapFailed => "Memory map failed", error.NativeWindowInUseKHR => "Native window in use", error.LayerNotPresent => "Layer not present", error.OutOfDeviceMemory => "Out of device memory", error.OutOfHostMemory => "Out of host memory", error.OutOfPoolMemory => "Out of pool memory", error.SurfaceLostKHR => "Surface lost", error.TooManyObjects => "Too many objects", error.Unknown => "Unknown error", error.ValidationLayerNotSupported => "Validation layer not supported", }; const message: []const u8 = std.mem.join(allocator, ": ", &[_][]const u8{ err_context, vulkan_error_message }) catch "=c Error while creating error message: " ++ err_context; defer allocator.free(message); printError("Vulkan", message); } pub var vkc: VulkanContext = undefined; pub const VulkanContext = struct { allocator: Allocator, instance: vk.Instance, surface: vk.SurfaceKHR, debug_messenger: vk.DebugUtilsMessengerEXT, physical_device: vk.PhysicalDevice, memory_properties: vk.PhysicalDeviceMemoryProperties, family_indices: QueueFamilyIndices, device: vk.Device, graphics_queue: vk.Queue, present_queue: vk.Queue, compute_queue: vk.Queue, pub fn init(self: *VulkanContext, allocator: Allocator, app: *Application) !void { // Workaround bug in amd driver, that reports zero vulkan capable gpu devices //https://github.com/KhronosGroup/Vulkan-Loader/issues/552 if (builtin.target.os.tag == .windows) { _ = c._putenv("DISABLE_LAYER_AMD_SWITCHABLE_GRAPHICS_1=1"); _ = c._putenv("DISABLE_LAYER_NV_OPTIMUS_1=1"); } self.allocator = allocator; vkb = try BaseDispatch.load(glfwGetInstanceProcAddress); self.createInstance(app.name) catch |err| { printVulkanError("Error during instance creation", err, self.allocator); return err; }; errdefer vki.destroyInstance(self.instance, null); vki = try InstanceDispatch.load(self.instance, glfwGetInstanceProcAddress); self.createSurface(app.window) catch |err| { printVulkanError("Error during surface creation", err, self.allocator); return err; }; errdefer vki.destroySurfaceKHR(self.instance, self.surface, null); if (nyancore_options.use_vulkan_sdk) { self.setupDebugMessenger() catch |err| { printVulkanError("Error setting up debug messenger", err, self.allocator); return err; }; errdefer vki.destroyDebugUtilsMessengerEXT(self.instance, self.debug_messenger, null); } self.pickPhysicalDevice() catch |err| { printVulkanError("Error picking physical device", err, self.allocator); return err; }; self.createLogicalDevice() catch |err| { printVulkanError("Error creating logical device", err, self.allocator); return err; }; vkd = try DeviceDispatch.load(self.device, vki.vkGetDeviceProcAddr); errdefer vkd.destroyDevice(self.device, null); self.graphics_queue = vkd.getDeviceQueue(self.device, self.family_indices.graphics_family, 0); self.present_queue = vkd.getDeviceQueue(self.device, self.family_indices.present_family, 0); self.compute_queue = vkd.getDeviceQueue(self.device, self.family_indices.compute_family, 0); } pub fn deinit(self: *VulkanContext) void { vkd.destroyDevice(self.device, null); if (nyancore_options.use_vulkan_sdk) { vki.destroyDebugUtilsMessengerEXT(self.instance, self.debug_messenger, null); } vki.destroySurfaceKHR(self.instance, self.surface, null); vki.destroyInstance(self.instance, null); } pub fn getMemoryType(self: *VulkanContext, type_bits: u32, properties: vk.MemoryPropertyFlags) u32 { var temp: u32 = type_bits; for (self.memory_properties.memory_types) |mem_type, ind| { if ((temp & 1) == 1) if ((mem_type.property_flags.toInt() & properties.toInt()) == properties.toInt()) return @intCast(u32, ind); temp >>= 1; } @panic("Can't get memory type"); } fn createInstance(self: *VulkanContext, app_name: [:0]const u8) !void { if (nyancore_options.use_vulkan_sdk) { const validation_layers_supported: bool = self.checkValidationLayerSupport() catch |err| { printVulkanError("Error getting information about layers", err, self.allocator); return err; }; if (!validation_layers_supported) { printError("Vulkan", "Validation layer not supported"); return error.ValidationLayerNotSupported; } } const app_info: vk.ApplicationInfo = .{ .p_application_name = app_name, .application_version = vk.makeApiVersion(0, 1, 0, 0), .p_engine_name = "nyancore engine", .engine_version = vk.makeApiVersion(0, 1, 0, 0), .api_version = vk.API_VERSION_1_2, }; var glfw_extension_count: u32 = undefined; const glfw_extensions: [*c][*c]const u8 = c.glfwGetRequiredInstanceExtensions(&glfw_extension_count); const extensions_count: u32 = glfw_extension_count + 1 * @boolToInt(nyancore_options.use_vulkan_sdk); var extensions: [][*c]const u8 = self.allocator.alloc([*c]const u8, extensions_count) catch { printError("Vulkan", "Can't allocate memory for extensions"); return error.HostAllocationError; }; defer self.allocator.free(extensions); var i: usize = 0; while (i < glfw_extension_count) : (i += 1) { extensions[i] = glfw_extensions[i]; } if (nyancore_options.use_vulkan_sdk) { extensions[i] = "VK_EXT_debug_utils"; } const create_info: vk.InstanceCreateInfo = .{ .p_application_info = &app_info, .enabled_extension_count = extensions_count, .pp_enabled_extension_names = @ptrCast([*]const [*:0]const u8, extensions), .enabled_layer_count = if (nyancore_options.use_vulkan_sdk) @intCast(u32, std.mem.len(validation_layers)) else 0, .pp_enabled_layer_names = if (nyancore_options.use_vulkan_sdk) @ptrCast([*]const [*:0]const u8, &validation_layers) else undefined, .flags = .{}, }; self.instance = vkb.createInstance(create_info, null) catch |err| { printVulkanError("Couldn't create vulkan instance", err, self.allocator); return err; }; } fn createSurface(self: *VulkanContext, window: *c.GLFWwindow) !void { const res: vk.Result = glfwCreateWindowSurface(self.instance, window, null, &self.surface); if (res != .success) { printError("Vulkan", "Glfw couldn't create window surface for vulkan context"); return error.Unknown; } } fn vulkanDebugCallback( message_severity: vk.DebugUtilsMessageSeverityFlagsEXT.IntType, message_types: vk.DebugUtilsMessageTypeFlagsEXT.IntType, p_callback_data: *const vk.DebugUtilsMessengerCallbackDataEXT, p_user_data: *anyopaque, ) callconv(vk.vulkan_call_conv) vk.Bool32 { _ = message_severity; _ = message_types; _ = p_user_data; printErrorNoPanic("Vulkan Validation Layer", std.mem.span(p_callback_data.p_message)); return 1; } fn setupDebugMessenger(self: *VulkanContext) !void { const create_info: vk.DebugUtilsMessengerCreateInfoEXT = .{ .flags = .{}, .message_severity = .{ .warning_bit_ext = true, .error_bit_ext = true, }, .message_type = .{ .general_bit_ext = true, .validation_bit_ext = true, .performance_bit_ext = true, }, .pfn_user_callback = vulkanDebugCallback, .p_user_data = null, }; self.debug_messenger = vki.createDebugUtilsMessengerEXT(self.instance, create_info, null) catch |err| { printVulkanError("Can't create debug messenger", err, self.allocator); return err; }; } fn checkDeviceExtensionsSupport(self: *VulkanContext, device: *const vk.PhysicalDevice) !bool { var extension_count: u32 = undefined; _ = vki.enumerateDeviceExtensionProperties(device.*, null, &extension_count, null) catch |err| { printVulkanError("Can't get count of device extensions", err, self.allocator); return err; }; var available_extensions: []vk.ExtensionProperties = self.allocator.alloc(vk.ExtensionProperties, extension_count) catch { printError("Vulkan", "Can't allocate information for available extensions"); return error.HostAllocationError; }; defer self.allocator.free(available_extensions); _ = vki.enumerateDeviceExtensionProperties(device.*, null, &extension_count, @ptrCast([*]vk.ExtensionProperties, available_extensions)) catch |err| { printVulkanError("Can't get information about available extensions", err, self.allocator); return err; }; for (required_device_extensions) |req_ext| { var extension_found: bool = false; for (available_extensions) |ext| { if (std.mem.startsWith(u8, ext.extension_name[0..], req_ext)) { extension_found = true; break; } } if (!extension_found) { return false; } } return true; } pub fn getSwapchainSupport(self: *const VulkanContext, device: *const vk.PhysicalDevice) !SwapchainSupportDetails { var details: SwapchainSupportDetails = undefined; details.capabilities = vki.getPhysicalDeviceSurfaceCapabilitiesKHR(device.*, self.surface) catch |err| { printVulkanError("Can't get physical device surface capabilities", err, self.allocator); return err; }; _ = vki.getPhysicalDeviceSurfaceFormatsKHR(device.*, self.surface, &details.format_count, null) catch |err| { printVulkanError("Can't get physical device's formats count", err, self.allocator); return err; }; if (details.format_count > 0) { details.formats = self.allocator.alloc(vk.SurfaceFormatKHR, details.format_count) catch { printError("Vulkan", "Can't allocate memory for device formats"); return error.HostAllocationError; }; _ = vki.getPhysicalDeviceSurfaceFormatsKHR(device.*, self.surface, &details.format_count, @ptrCast([*]vk.SurfaceFormatKHR, details.formats)) catch |err| { printVulkanError("Can't get information about physical device's supported formats", err, self.allocator); return err; }; } _ = vki.getPhysicalDeviceSurfacePresentModesKHR(device.*, self.surface, &details.present_mode_count, null) catch |err| { printVulkanError("Can't get physical device's present modes count", err, self.allocator); return err; }; if (details.present_mode_count > 0) { details.present_modes = self.allocator.alloc(vk.PresentModeKHR, details.present_mode_count) catch { printError("Vulkan", "Can't allocate memory for device present modes"); return error.HostAllocationError; }; _ = vki.getPhysicalDeviceSurfacePresentModesKHR(device.*, self.surface, &details.present_mode_count, @ptrCast([*]vk.PresentModeKHR, details.present_modes)) catch |err| { printVulkanError("Can't get information about physical device present modes", err, self.allocator); return err; }; } return details; } fn findQueueFamilyIndices(self: *VulkanContext, device: *const vk.PhysicalDevice) !QueueFamilyIndices { var indices: QueueFamilyIndices = undefined; var queue_family_count: u32 = undefined; vki.getPhysicalDeviceQueueFamilyProperties(device.*, &queue_family_count, null); var queue_families: []vk.QueueFamilyProperties = self.allocator.alloc(vk.QueueFamilyProperties, queue_family_count) catch { printError("Vulkan", "Can't allocate information for queue families"); return error.HostAllocationError; }; defer self.allocator.free(queue_families); vki.getPhysicalDeviceQueueFamilyProperties(device.*, &queue_family_count, @ptrCast([*]vk.QueueFamilyProperties, queue_families)); for (queue_families) |family, i| { if (family.queue_flags.graphics_bit) { indices.graphics_family = @intCast(u32, i); indices.graphics_family_set = true; } if (family.queue_flags.compute_bit) { indices.compute_family = @intCast(u32, i); indices.compute_family_set = true; } var present_support: vk.Bool32 = vki.getPhysicalDeviceSurfaceSupportKHR(device.*, @intCast(u32, i), self.surface) catch |err| { printVulkanError("Can't get physical device surface support information", err, self.allocator); return err; }; if (present_support != 0) { indices.present_family = @intCast(u32, i); indices.present_family_set = true; } if (indices.isComplete()) { break; } } return indices; } fn isDeviceSuitable(self: *VulkanContext, device: *const vk.PhysicalDevice) !bool { const extensions_supported: bool = self.checkDeviceExtensionsSupport(device) catch |err| { printVulkanError("Error while checking device extensions", err, self.allocator); return err; }; if (!extensions_supported) { return false; } var swapchain_support: SwapchainSupportDetails = self.getSwapchainSupport(device) catch |err| { printVulkanError("Can't get swapchain support details", err, self.allocator); return err; }; defer self.allocator.free(swapchain_support.formats); defer self.allocator.free(swapchain_support.present_modes); if (swapchain_support.format_count < 1 or swapchain_support.present_mode_count < 1) { return false; } const indices: QueueFamilyIndices = self.findQueueFamilyIndices(device) catch |err| { printVulkanError("Can't get family indices", err, self.allocator); return err; }; if (!indices.isComplete()) { return false; } return true; } fn pickPhysicalDevice(self: *VulkanContext) !void { var gpu_count: u32 = undefined; _ = vki.enumeratePhysicalDevices(self.instance, &gpu_count, null) catch |err| { printVulkanError("Can't get physical device count", err, self.allocator); return err; }; var physical_devices: []vk.PhysicalDevice = self.allocator.alloc(vk.PhysicalDevice, gpu_count) catch { printError("Vulkan", "Can't allocate information for physical devices"); return error.HostAllocationError; }; defer self.allocator.free(physical_devices); _ = vki.enumeratePhysicalDevices(self.instance, &gpu_count, @ptrCast([*]vk.PhysicalDevice, physical_devices)) catch |err| { printVulkanError("Can't get physical devices information", err, self.allocator); return err; }; for (physical_devices) |device| { if (self.isDeviceSuitable(&device)) { self.physical_device = device; self.memory_properties = vki.getPhysicalDeviceMemoryProperties(self.physical_device); self.family_indices = self.findQueueFamilyIndices(&self.physical_device) catch unreachable; return; } else |err| { printVulkanError("Error checking physical device suitabilty", err, self.allocator); return err; } } printError("Vulkan", "Can't find suitable device"); return error.Unknown; } fn createLogicalDevice(self: *VulkanContext) !void { var queue_indices: [3]u32 = [_]u32{ self.family_indices.present_family, self.family_indices.graphics_family, self.family_indices.compute_family, }; std.sort.sort(u32, queue_indices[0..], {}, comptime std.sort.asc(u32)); var queue_create_info: [3]vk.DeviceQueueCreateInfo = [_]vk.DeviceQueueCreateInfo{ undefined, undefined, undefined }; var queue_create_info_count: usize = 0; var i: usize = 0; var last_family: u32 = undefined; const queue_priority: f32 = 1.0; while (i < std.mem.len(queue_indices)) : (i += 1) { if (queue_indices[i] != last_family) { queue_create_info[queue_create_info_count] = .{ .flags = .{}, .queue_family_index = queue_indices[i], .queue_count = 1, .p_queue_priorities = @ptrCast([*]const f32, &queue_priority), }; last_family = queue_indices[i]; queue_create_info_count += 1; } } const create_info: vk.DeviceCreateInfo = .{ .flags = .{}, .p_queue_create_infos = @ptrCast([*]const vk.DeviceQueueCreateInfo, &queue_create_info), .queue_create_info_count = @intCast(u32, queue_create_info_count), .p_enabled_features = null, .enabled_layer_count = if (nyancore_options.use_vulkan_sdk) @intCast(u32, std.mem.len(validation_layers)) else 0, .pp_enabled_layer_names = if (nyancore_options.use_vulkan_sdk) @ptrCast([*]const [*:0]const u8, &validation_layers) else undefined, .enabled_extension_count = @intCast(u32, std.mem.len(required_device_extensions)), .pp_enabled_extension_names = @ptrCast([*]const [*:0]const u8, &required_device_extensions), }; self.device = vki.createDevice(self.physical_device, create_info, null) catch |err| { printVulkanError("Can't create device", err, self.allocator); return err; }; } fn checkValidationLayerSupport(self: *VulkanContext) !bool { var layerCount: u32 = undefined; _ = vkb.enumerateInstanceLayerProperties(&layerCount, null) catch |err| { printVulkanError("Can't enumerate instance layer properties for layer support", err, self.allocator); return err; }; var available_layers: []vk.LayerProperties = self.allocator.alloc(vk.LayerProperties, layerCount) catch { printError("Vulkan", "Can't allocate memory for available layers"); return error.HostAllocationError; }; defer self.allocator.free(available_layers); _ = vkb.enumerateInstanceLayerProperties(&layerCount, @ptrCast([*]vk.LayerProperties, available_layers)) catch |err| { printVulkanError("Can't enumerate instance layer properties for layer support", err, self.allocator); return err; }; for (validation_layers) |validation_layer| { var exist: bool = for (available_layers) |layer| { if (std.mem.startsWith(u8, layer.layer_name[0..], validation_layer[0..])) { break true; } } else false; if (!exist) { return false; } } return true; } };
src/vulkan_wrapper/vulkan_context.zig
const std = @import("std"); const Random = std.rand.Random; const expect = std.testing.expect; const parseInt = std.fmt.parseInt; const Day = enum { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, }; const Month = enum { January = 1, February, March, April, May, June, July, August, September, October, November, December, fn numDays(self: Month, leap: bool) u8 { return switch (self) { .January, .March, .May, .July, .August, .October, .December => 31, .April, .June, .September, .November => 30, .February => if (leap) @as(u8, 29) else 28, }; } }; fn randDate(r: *Random) Date { const y = r.intRangeLessThan(u16, 1600, 2500); const m = @intToEnum(Month, r.intRangeAtMost(@TagType(Month), 1, 12)); const d = r.intRangeAtMost(u8, 1, m.numDays(isLeap(y))); return Date{ .year = y, .month = m, .day = d }; } const Date = struct { year: u16, month: Month, day: u8, pub fn format(self: Date, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { try writer.print("{} {} {}", .{ self.day, @tagName(self.month), self.year }); } fn dayOfWeek(self: Date) Day { const dd = doomsday(self.year); const d = switch (self.month) { .January => if (isLeap(self.year)) @as(u8, 4) // appease the type-checker else 3, .February => if (isLeap(self.year)) @as(u8, 29) else 28, .March => 0, .April => 4, .May => 9, .June => 6, .July => 11, .August => 8, .September => 5, .October => 10, .November => 7, .December => 12, }; // add 35 (0 mod 7) to avoid underflow, since d is at most 29 return @intToEnum(Day, @intCast(@TagType(Day), (self.day + 35 - d + dd) % 7)); } }; test "day of week" { const d1 = Date{ .year = 2020, .month = .October, .day = 12 }; expect(d1.dayOfWeek() == .Monday); const d2 = Date{ .year = 1815, .month = .February, .day = 14 }; expect(d2.dayOfWeek() == .Tuesday); } fn isLeap(y: u16) bool { return y % 400 == 0 or y % 100 != 0 and y % 4 == 0; } test "leap years" { expect(isLeap(2000)); expect(isLeap(1996)); expect(!isLeap(1900)); } fn centuryAnchor(y: u16) u8 { const c = y / 100 % 4; return @intCast(u8, (5 * c + 2) % 7); } test "century anchors" { expect(centuryAnchor(1776) == 0); expect(centuryAnchor(1837) == 5); expect(centuryAnchor(1952) == 3); expect(centuryAnchor(2001) == 2); } fn doomsday(y: u16) u8 { const anchor = centuryAnchor(y); const year = y % 100; return @intCast(u8, (year + year / 4 + anchor) % 7); } test "doomsday calculation" { expect(doomsday(2020) == 6); expect(doomsday(1966) == 1); expect(doomsday(1939) == 2); } fn readDay(b: []const u8) ?Day { const i = parseInt(@TagType(Day), std.mem.trim(u8, b, " \n"), 10) catch return null; if (i >= 7) { return null; } return @intToEnum(Day, i); } const maxLineLength = 4096; // as in termios(3) fn askDay(d: Date) !void { const stdout = std.io.getStdOut().writer(); const stdin = std.io.getStdIn(); var b: [maxLineLength]u8 = undefined; const day = d.dayOfWeek(); try stdout.print("{}? ", .{d}); const t = try std.time.Timer.start(); while (true) { const n = try stdin.read(&b); if (readDay(b[0..n])) |read| { if (read == day) { const seconds = t.read() / 1_000_000_000; try stdout.print("Correct! You took {} second{}.\n", .{ seconds, plural(seconds), }); return; } else { try stdout.print("Wrong, try again: ", .{}); } } else { try stdout.print("not a day, try again: ", .{}); } } } fn plural(n: anytype) []const u8 { if (n == 1) { return ""; } else { return "s"; } } pub fn main() !void { const num_questions = blk: { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = &arena.allocator; var args_it = std.process.args(); const exe = try args_it.next(allocator).?; const res = if (args_it.next(allocator)) |arg_or_err| parseInt(usize, try arg_or_err, 10) catch return usage(exe) else 1; if (args_it.next(allocator) != null) return usage(exe); break :blk res; }; var seed: u64 = undefined; try std.crypto.randomBytes(std.mem.asBytes(&seed)); const rand = &std.rand.DefaultPrng.init(seed).random; var asked: usize = 0; while (asked < num_questions) : (asked += 1) { const date = randDate(rand); try askDay(date); } } fn usage(exe: []const u8) !void { std.log.err("Usage: {} [number]\n", .{exe}); return error.Invalid; }
src/main.zig
const clap = @import("clap"); const std = @import("std"); const ston = @import("ston"); const util = @import("util"); const common = @import("common.zig"); const format = @import("format.zig"); const gen3 = @import("gen3.zig"); const gen4 = @import("gen4.zig"); const gen5 = @import("gen5.zig"); const rom = @import("rom.zig"); const debug = std.debug; const fs = std.fs; const heap = std.heap; const io = std.io; const log = std.log; const math = std.math; const mem = std.mem; const unicode = std.unicode; const gba = rom.gba; const nds = rom.nds; const lu16 = rom.int.lu16; const lu32 = rom.int.lu32; const bit = util.bit; const escape = util.escape; const Game = format.Game; const Program = @This(); allocator: mem.Allocator, file: []const u8, pub const main = util.generateMain(Program); pub const version = "0.0.0"; pub const description = \\Load data from PokΓ©mon games. \\ ; pub const params = &[_]clap.Param(clap.Help){ clap.parseParam("-h, --help Display this help text and exit. ") catch unreachable, clap.parseParam("-v, --version Output version information and exit.") catch unreachable, clap.parseParam("<ROM> The rom to apply the changes to. ") catch unreachable, }; pub fn init(allocator: mem.Allocator, args: anytype) !Program { const pos = args.positionals(); const file_name = if (pos.len > 0) pos[0] else return error.MissingFile; return Program{ .allocator = allocator, .file = file_name, }; } pub fn run( program: *Program, comptime Reader: type, comptime Writer: type, stdio: util.CustomStdIoStreams(Reader, Writer), ) anyerror!void { const allocator = program.allocator; const file = try fs.cwd().openFile(program.file, .{}); defer file.close(); const gen3_error = if (gen3.Game.fromFile(file, allocator)) |*game| { defer game.deinit(); try outputGen3Data(game.*, stdio.out); return; } else |err| err; try file.seekTo(0); if (nds.Rom.fromFile(file, allocator)) |*nds_rom| { const gen4_error = if (gen4.Game.fromRom(allocator, nds_rom)) |*game| { defer game.deinit(); try outputGen4Data(game.*, stdio.out); return; } else |err| err; const gen5_error = if (gen5.Game.fromRom(allocator, nds_rom)) |*game| { defer game.deinit(); try outputGen5Data(game.*, stdio.out); return; } else |err| err; log.info("Successfully loaded '{s}' as a nds rom.", .{program.file}); log.err("Failed to load '{s}' as a gen4 game: {}", .{ program.file, gen4_error }); log.err("Failed to load '{s}' as a gen5 game: {}", .{ program.file, gen5_error }); return gen5_error; } else |nds_error| { log.err("Failed to load '{s}' as a gen3 game: {}", .{ program.file, gen3_error }); log.err("Failed to load '{s}' as a gen4/gen5 game: {}", .{ program.file, nds_error }); return nds_error; } } fn outputGen3Data(game: gen3.Game, writer: anytype) !void { var buf: [mem.page_size]u8 = undefined; for (game.starters) |starter, index| { if (starter.value() != game.starters_repeat[index].value()) log.warn("repeated starters don't match.", .{}); } try ston.serialize(writer, .{ .version = game.version, .game_title = ston.string(escape.default.escapeFmt(game.header.game_title.span())), .gamecode = ston.string(escape.default.escapeFmt(&game.header.gamecode)), .starters = game.starters, .text_delays = game.text_delays, .tms = game.tms, .hms = game.hms, .static_pokemons = game.static_pokemons, .given_pokemons = game.given_pokemons, .pokeball_items = game.pokeball_items, }); for (game.trainers) |trainer, i| { var fbs = io.fixedBufferStream(&buf); try gen3.encodings.decode(.en_us, &trainer.name, fbs.writer()); const decoded_name = fbs.getWritten(); const party = game.trainer_parties[i]; try ston.serialize(writer, .{ .trainers = ston.index(i, .{ .class = trainer.class, .encounter_music = trainer.encounter_music.music, .trainer_picture = trainer.trainer_picture, .name = ston.string(escape.default.escapeFmt(decoded_name)), .items = trainer.items, .party_type = trainer.party_type, .party_size = trainer.partyLen(), }) }); for (party.members[0..party.size]) |member, j| { try ston.serialize(writer, .{ .trainers = ston.index(i, .{ .party = ston.index(j, .{ .level = member.base.level, .species = member.base.species, }), }) }); if (trainer.party_type == .item or trainer.party_type == .both) { try ston.serialize(writer, .{ .trainers = ston.index(i, .{ .party = ston.index(j, .{ .item = member.item }), }) }); } if (trainer.party_type == .moves or trainer.party_type == .both) { for (member.moves) |move, k| { try ston.serialize(writer, .{ .trainers = ston.index(i, .{ .party = ston.index(j, .{ .moves = ston.index(k, move), }) }) }); } } } } for (game.moves) |move, i| { try ston.serialize(writer, .{ .moves = ston.index(i, .{ .effect = move.effect, .power = move.power, .type = move.@"type", .accuracy = move.accuracy, .pp = move.pp, .target = move.target, .priority = move.priority, .category = move.category, }) }); } for (game.pokemons) |pokemon, i| { // Wonna crash the compiler? Follow this one simple trick!!! // Remove these variables and do the initialization directly in `ston.serialize` const stats = pokemon.stats; const ev_yield = .{ .hp = pokemon.ev_yield.hp, .attack = pokemon.ev_yield.attack, .defense = pokemon.ev_yield.defense, .speed = pokemon.ev_yield.speed, .sp_attack = pokemon.ev_yield.sp_attack, .sp_defense = pokemon.ev_yield.sp_defense, }; try ston.serialize(writer, .{ .pokemons = ston.index(i, .{ .stats = stats, .catch_rate = pokemon.catch_rate, .base_exp_yield = pokemon.base_exp_yield, .ev_yield = ev_yield, .gender_ratio = pokemon.gender_ratio, .egg_cycles = pokemon.egg_cycles, .base_friendship = pokemon.base_friendship, .growth_rate = pokemon.growth_rate, .color = pokemon.color.color, .types = pokemon.types, .items = pokemon.items, .egg_groups = pokemon.egg_groups, .abilities = pokemon.abilities, }) }); } for (game.species_to_national_dex) |dex_entry, i| { try ston.serialize(writer, .{ .pokemons = ston.index(i + 1, .{ .pokedex_entry = dex_entry, }) }); } for (game.evolutions) |evos, i| { for (evos) |evo, j| { if (evo.method == .unused) continue; try ston.serialize(writer, .{ .pokemons = ston.index(i, .{ .evos = ston.index(j, .{ .method = evo.method, .param = evo.param, .target = evo.target, }), }) }); } } for (game.level_up_learnset_pointers) |lvl_up_learnset, i| { const learnset = try lvl_up_learnset.toSliceEnd(game.data); for (learnset) |l, j| { if (std.meta.eql(l, gen3.LevelUpMove.term)) break; try ston.serialize(writer, .{ .pokemons = ston.index(i, .{ .moves = ston.index(j, .{ .id = l.id, .level = l.level, }), }) }); } } for (game.machine_learnsets) |machine_learnset, i| { var j: u6 = 0; while (j < game.tms.len) : (j += 1) { try ston.serialize(writer, .{ .pokemons = ston.index(i, .{ .tms = ston.index(j, bit.isSet(u64, machine_learnset.value(), j)), }) }); } while (j < game.tms.len + game.hms.len) : (j += 1) { try ston.serialize(writer, .{ .pokemons = ston.index(i, .{ .hms = ston.index(j - game.tms.len, bit.isSet(u64, machine_learnset.value(), j)), }) }); } } for (game.pokemon_names) |str, i| { var fbs = io.fixedBufferStream(&buf); try gen3.encodings.decode(.en_us, &str, fbs.writer()); const decoded_name = fbs.getWritten(); try ston.serialize(writer, .{ .pokemons = ston.index(i, .{ .name = ston.string(escape.default.escapeFmt(decoded_name)), }) }); } for (game.ability_names) |str, i| { var fbs = io.fixedBufferStream(&buf); try gen3.encodings.decode(.en_us, &str, fbs.writer()); const decoded_name = fbs.getWritten(); try ston.serialize(writer, .{ .abilities = ston.index(i, .{ .name = ston.string(escape.default.escapeFmt(decoded_name)), }) }); } for (game.move_names) |str, i| { var fbs = io.fixedBufferStream(&buf); try gen3.encodings.decode(.en_us, &str, fbs.writer()); const decoded_name = fbs.getWritten(); try ston.serialize(writer, .{ .moves = ston.index(i, .{ .name = ston.string(escape.default.escapeFmt(decoded_name)), }) }); } for (game.type_names) |str, i| { var fbs = io.fixedBufferStream(&buf); try gen3.encodings.decode(.en_us, &str, fbs.writer()); const decoded_name = fbs.getWritten(); try ston.serialize(writer, .{ .types = ston.index(i, .{ .name = ston.string(escape.default.escapeFmt(decoded_name)), }) }); } for (game.items) |item, i| { try ston.serialize(writer, .{ .items = ston.index(i, .{ .price = item.price, .battle_effect = item.battle_effect, }) }); switch (game.version) { .ruby, .sapphire, .emerald => try ston.serialize(writer, .{ .items = ston.index(i, .{ .pocket = item.pocket.rse, }) }), .fire_red, .leaf_green => try ston.serialize(writer, .{ .items = ston.index(i, .{ .pocket = item.pocket.frlg, }) }), else => unreachable, } { var fbs = io.fixedBufferStream(&buf); try gen3.encodings.decode(.en_us, &item.name, fbs.writer()); const decoded_name = fbs.getWritten(); try ston.serialize(writer, .{ .items = ston.index(i, .{ .name = ston.string(escape.default.escapeFmt(decoded_name)), }) }); } if (item.description.toSliceZ(game.data)) |str| { var fbs = io.fixedBufferStream(&buf); try gen3.encodings.decode(.en_us, str, fbs.writer()); const decoded_description = fbs.getWritten(); try ston.serialize(writer, .{ .items = ston.index(i, .{ .description = ston.string(escape.default.escapeFmt(decoded_description)), }) }); } else |_| {} } switch (game.version) { .emerald => for (game.pokedex.emerald) |entry, i| { try ston.serialize(writer, .{ .pokedex = ston.index(i, .{ .height = entry.height, .weight = entry.weight, }) }); }, .ruby, .sapphire, .fire_red, .leaf_green, => for (game.pokedex.rsfrlg) |entry, i| { try ston.serialize(writer, .{ .pokedex = ston.index(i, .{ .height = entry.height, .weight = entry.weight, }) }); }, else => unreachable, } for (game.map_headers) |header, i| { try ston.serialize(writer, .{ .maps = ston.index(i, .{ .music = header.music, .cave = header.cave, .weather = header.weather, .type = header.map_type, .escape_rope = header.escape_rope, .battle_scene = header.map_battle_scene, .allow_cycling = header.flags.allow_cycling, .allow_escaping = header.flags.allow_escaping, .allow_running = header.flags.allow_running, .show_map_name = header.flags.show_map_name, }) }); } for (game.wild_pokemon_headers) |header, i| { if (header.land.toPtr(game.data)) |land| { const wilds = try land.wild_pokemons.toPtr(game.data); // Wonna see a bug with result locations in the compiler? Try lining this variable // into `ston.serialize` :) const area = .{ .encounter_rate = land.encounter_rate, .pokemons = wilds, }; try ston.serialize(writer, .{ .wild_pokemons = ston.index(i, .{ .grass_0 = area }) }); } else |_| {} if (header.surf.toPtr(game.data)) |surf| { const wilds = try surf.wild_pokemons.toPtr(game.data); const area = .{ .encounter_rate = surf.encounter_rate, .pokemons = wilds, }; try ston.serialize(writer, .{ .wild_pokemons = ston.index(i, .{ .surf_0 = area }) }); } else |_| {} if (header.rock_smash.toPtr(game.data)) |rock| { const wilds = try rock.wild_pokemons.toPtr(game.data); const area = .{ .encounter_rate = rock.encounter_rate, .pokemons = wilds, }; try ston.serialize(writer, .{ .wild_pokemons = ston.index(i, .{ .rock_smash = area }) }); } else |_| {} if (header.fishing.toPtr(game.data)) |fish| { const wilds = try fish.wild_pokemons.toPtr(game.data); const area = .{ .encounter_rate = fish.encounter_rate, .pokemons = wilds, }; try ston.serialize(writer, .{ .wild_pokemons = ston.index(i, .{ .fishing_0 = area }) }); } else |_| {} } for (game.text) |text_ptr, i| { const text = try text_ptr.toSliceZ(game.data); var fbs = io.fixedBufferStream(&buf); try gen3.encodings.decode(.en_us, text, fbs.writer()); const decoded_text = fbs.getWritten(); try ston.serialize(writer, .{ .text = ston.index(i, ston.string(escape.default.escapeFmt(decoded_text))), }); } } fn outputGen4Data(game: gen4.Game, writer: anytype) !void { const header = game.rom.header(); try ston.serialize(writer, .{ .version = game.info.version, .game_title = ston.string(escape.default.escapeFmt(header.game_title.span())), .gamecode = ston.string(escape.default.escapeFmt(&header.gamecode)), .instant_text = false, .starters = game.ptrs.starters, .tms = game.ptrs.tms, .hms = game.ptrs.hms, .static_pokemons = game.ptrs.static_pokemons, .given_pokemons = game.ptrs.given_pokemons, .pokeball_items = game.ptrs.pokeball_items, }); for (game.ptrs.trainers) |trainer, i| { try ston.serialize(writer, .{ .trainers = ston.index(i, .{ .party_size = trainer.party_size, .party_type = trainer.party_type, .class = trainer.class, .items = trainer.items, }) }); const parties = game.owned.trainer_parties; if (parties.len <= i) continue; for (parties[i][0..trainer.party_size]) |member, j| { try ston.serialize(writer, .{ .trainers = ston.index(i, .{ .party = ston.index(j, .{ .ability = member.base.gender_ability.ability, .level = member.base.level, .species = member.base.species, }), }) }); if (trainer.party_type == .item or trainer.party_type == .both) { try ston.serialize(writer, .{ .trainers = ston.index(i, .{ .party = ston.index(j, .{ .item = member.item }), }) }); } if (trainer.party_type == .moves or trainer.party_type == .both) { for (member.moves) |move, k| { try ston.serialize(writer, .{ .trainers = ston.index(i, .{ .party = ston.index(j, .{ .moves = ston.index(k, move), }) }) }); } } } } for (game.ptrs.moves) |move, i| { try ston.serialize(writer, .{ .moves = ston.index(i, .{ .category = move.category, .power = move.power, .type = move.type, .accuracy = move.accuracy, .pp = move.pp, }) }); } for (game.ptrs.pokemons) |pokemon, i| { // Wonna crash the compiler? Follow this one simple trick!!! // Remove these variables and do the initialization directly in `ston.serialize` const stats = pokemon.stats; const ev_yield = .{ .hp = pokemon.ev_yield.hp, .attack = pokemon.ev_yield.attack, .defense = pokemon.ev_yield.defense, .speed = pokemon.ev_yield.speed, .sp_attack = pokemon.ev_yield.sp_attack, .sp_defense = pokemon.ev_yield.sp_defense, }; try ston.serialize(writer, .{ .pokemons = ston.index(i, .{ .stats = stats, .catch_rate = pokemon.catch_rate, .base_exp_yield = pokemon.base_exp_yield, .ev_yield = ev_yield, .gender_ratio = pokemon.gender_ratio, .egg_cycles = pokemon.egg_cycles, .base_friendship = pokemon.base_friendship, .growth_rate = pokemon.growth_rate, .color = pokemon.color.color, .types = pokemon.types, .items = pokemon.items, .egg_groups = pokemon.egg_groups, .abilities = pokemon.abilities, }) }); const machine_learnset = pokemon.machine_learnset; var j: u7 = 0; while (j < game.ptrs.tms.len) : (j += 1) { try ston.serialize(writer, .{ .pokemons = ston.index(i, .{ .tms = ston.index(j, bit.isSet(u128, machine_learnset.value(), j)), }) }); } while (j < game.ptrs.tms.len + game.ptrs.hms.len) : (j += 1) { try ston.serialize(writer, .{ .pokemons = ston.index(i, .{ .hms = ston.index(j - game.ptrs.tms.len, bit.isSet(u128, machine_learnset.value(), j)), }) }); } } for (game.ptrs.species_to_national_dex) |dex_entry, i| { try ston.serialize(writer, .{ .pokemons = ston.index(i + 1, .{ .pokedex_entry = dex_entry, }) }); } for (game.ptrs.evolutions) |evos, i| { for (evos.items) |evo, j| { if (evo.method == .unused) continue; try ston.serialize(writer, .{ .pokemons = ston.index(i, .{ .evos = ston.index(j, .{ .method = evo.method, .param = evo.param, .target = evo.target, }), }) }); } } for (game.ptrs.level_up_moves.fat) |_, i| { const bytes = game.ptrs.level_up_moves.fileData(.{ .i = @intCast(u32, i) }); const level_up_moves = mem.bytesAsSlice(gen4.LevelUpMove, bytes); for (level_up_moves) |move, j| { if (std.meta.eql(move, gen4.LevelUpMove.term)) break; try ston.serialize(writer, .{ .pokemons = ston.index(i, .{ .moves = ston.index(j, .{ .id = move.id, .level = move.level, }), }) }); } } for (game.ptrs.pokedex_heights) |height, i| { try ston.serialize(writer, .{ .pokedex = ston.index(i, .{ .height = height, }) }); } for (game.ptrs.pokedex_weights) |weight, i| { try ston.serialize(writer, .{ .pokedex = ston.index(i, .{ .weight = weight, }) }); } for (game.ptrs.items) |item, i| { try ston.serialize(writer, .{ .items = ston.index(i, .{ .price = item.price, .battle_effect = item.battle_effect, .pocket = item.pocket.pocket, }) }); } switch (game.info.version) { .diamond, .pearl, .platinum, => for (game.ptrs.wild_pokemons.dppt) |wild_mons, i| { const rate = .{ .encounter_rate = wild_mons.grass_rate }; // Result location crash alert try ston.serialize(writer, .{ .wild_pokemons = ston.index(i, .{ .grass_0 = rate, }) }); for (wild_mons.grass) |grass, j| { const pokemon = .{ .pokemons = ston.index(j, .{ .min_level = grass.level, .max_level = grass.level, .species = grass.species, }) }; // Result location crash alert try ston.serialize(writer, .{ .wild_pokemons = ston.index(i, .{ .grass_0 = pokemon, }) }); } inline for ([_][]const u8{ "swarm_replace", "day_replace", "night_replace", "radar_replace", "unknown_replace", "gba_replace", }) |area_name, area_i| { for (@field(wild_mons, area_name)) |replacement, j| { const out_name = std.fmt.comptimePrint("grass_{}", .{area_i + 1}); try ston.serialize(writer, .{ .wild_pokemons = ston.index( i, ston.field(out_name, .{ .pokemons = ston.index(j, .{ .species = replacement.species, }) }), ) }); } } inline for ([_][]const u8{ "surf", "sea_unknown", }) |area_name, area_i| { const out_name = std.fmt.comptimePrint("surf_{}", .{area_i}); try ston.serialize(writer, .{ .wild_pokemons = ston.index( i, ston.field(out_name, .{ .encounter_rate = @field(wild_mons, area_name).rate, }), ) }); for (@field(wild_mons, area_name).mons) |mon, j| { try ston.serialize(writer, .{ .wild_pokemons = ston.index( i, ston.field(out_name, .{ .pokemons = ston.index(j, .{ .min_level = mon.min_level, .max_level = mon.max_level, .species = mon.species, }) }), ) }); } } inline for ([_][]const u8{ "old_rod", "good_rod", "super_rod", }) |area_name, area_i| { const out_name = std.fmt.comptimePrint("fishing_{}", .{area_i}); try ston.serialize(writer, .{ .wild_pokemons = ston.index( i, ston.field(out_name, .{ .encounter_rate = @field(wild_mons, area_name).rate, }), ) }); for (@field(wild_mons, area_name).mons) |mon, j| { try ston.serialize(writer, .{ .wild_pokemons = ston.index( i, ston.field(out_name, .{ .pokemons = ston.index(j, .{ .min_level = mon.min_level, .max_level = mon.max_level, .species = mon.species, }) }), ) }); } } }, .heart_gold, .soul_silver, => for (game.ptrs.wild_pokemons.hgss) |wild_mons, i| { // TODO: Get rid of inline for in favor of a function to call inline for ([_][]const u8{ "grass_morning", "grass_day", "grass_night", }) |area_name, area_i| { const out_name = std.fmt.comptimePrint("grass_{}", .{area_i}); try ston.serialize(writer, .{ .wild_pokemons = ston.index( i, ston.field(out_name, .{ .encounter_rate = wild_mons.grass_rate, }), ) }); for (@field(wild_mons, area_name)) |species, j| { try ston.serialize(writer, .{ .wild_pokemons = ston.index( i, ston.field(out_name, .{ .pokemons = ston.index(j, .{ .min_level = wild_mons.grass_levels[j], .max_level = wild_mons.grass_levels[j], .species = species, }) }), ) }); } } // TODO: Get rid of inline for in favor of a function to call inline for ([_][]const u8{ "surf", "sea_unknown", }) |area_name, j| { const out_name = std.fmt.comptimePrint("surf_{}", .{j}); try ston.serialize(writer, .{ .wild_pokemons = ston.index( i, ston.field(out_name, .{ .encounter_rate = wild_mons.sea_rates[j], }), ) }); for (@field(wild_mons, area_name)) |sea, k| { try ston.serialize(writer, .{ .wild_pokemons = ston.index( i, ston.field(out_name, .{ .pokemons = ston.index(k, .{ .min_level = sea.min_level, .max_level = sea.max_level, .species = sea.species, }) }), ) }); } } inline for ([_][]const u8{ "old_rod", "good_rod", "super_rod", }) |area_name, j| { const out_name = std.fmt.comptimePrint("fishing_{}", .{j}); try ston.serialize(writer, .{ .wild_pokemons = ston.index( i, ston.field(out_name, .{ .encounter_rate = wild_mons.sea_rates[j + 2], }), ) }); for (@field(wild_mons, area_name)) |sea, k| { try ston.serialize(writer, .{ .wild_pokemons = ston.index( i, ston.field(out_name, .{ .pokemons = ston.index(k, .{ .min_level = sea.min_level, .max_level = sea.max_level, .species = sea.species, }) }), ) }); } } // TODO: radio, swarm }, else => unreachable, } try outputGen4StringTable(writer, "pokemons", "name", game.owned.text.pokemon_names); try outputGen4StringTable(writer, "moves", "name", game.owned.text.move_names); try outputGen4StringTable(writer, "moves", "description", game.owned.text.move_descriptions); try outputGen4StringTable(writer, "abilities", "name", game.owned.text.ability_names); try outputGen4StringTable(writer, "items", "name", game.owned.text.item_names); try outputGen4StringTable(writer, "items", "description", game.owned.text.item_descriptions); try outputGen4StringTable(writer, "types", "name", game.owned.text.type_names); } fn outputGen4StringTable( writer: anytype, array_name: []const u8, field_name: []const u8, table: gen4.StringTable, ) !void { var i: usize = 0; while (i < table.number_of_strings) : (i += 1) try outputString(writer, array_name, i, field_name, table.getSpan(i)); } fn outputGen5Data(game: gen5.Game, writer: anytype) !void { const header = game.rom.header(); try ston.serialize(writer, .{ .version = game.info.version, .game_title = ston.string(escape.default.escapeFmt(header.game_title.span())), .gamecode = ston.string(escape.default.escapeFmt(&header.gamecode)), .instant_text = false, .hms = game.ptrs.hms, .static_pokemons = game.ptrs.static_pokemons, .given_pokemons = game.ptrs.given_pokemons, .pokeball_items = game.ptrs.pokeball_items, }); for (game.ptrs.tms1) |tm, i| try ston.serialize(writer, .{ .tms = ston.index(i, tm) }); for (game.ptrs.tms2) |tm, i| try ston.serialize(writer, .{ .tms = ston.index(i + game.ptrs.tms1.len, tm) }); for (game.ptrs.starters) |starter_ptrs, i| { const first = starter_ptrs[0]; for (starter_ptrs[1..]) |starter| { if (first.value() != starter.value()) log.warn("all starter positions are not the same. {} {}\n", .{ first.value(), starter.value() }); } try ston.serialize(writer, .{ .starters = ston.index(i, first) }); } for (game.ptrs.trainers) |trainer, index| { const i = index + 1; try ston.serialize(writer, .{ .trainers = ston.index(i, .{ .party_size = trainer.party_size, .party_type = trainer.party_type, .class = trainer.class, .items = trainer.items, }) }); const parties = game.owned.trainer_parties; if (parties.len <= i) continue; for (parties[i][0..trainer.party_size]) |member, j| { try ston.serialize(writer, .{ .trainers = ston.index(i, .{ .party = ston.index(j, .{ .ability = member.base.gender_ability.ability, .level = member.base.level, .species = member.base.species, }), }) }); if (trainer.party_type == .item or trainer.party_type == .both) { try ston.serialize(writer, .{ .trainers = ston.index(i, .{ .party = ston.index(j, .{ .item = member.item }), }) }); } if (trainer.party_type == .moves or trainer.party_type == .both) { for (member.moves) |move, k| { try ston.serialize(writer, .{ .trainers = ston.index(i, .{ .party = ston.index(j, .{ .moves = ston.index(k, move), }) }) }); } } } } for (game.ptrs.moves) |move, i| { try ston.serialize(writer, .{ .moves = ston.index(i, .{ .type = move.type, .category = move.category, .power = move.power, .accuracy = move.accuracy, .pp = move.pp, .priority = move.priority, .target = move.target, }) }); } const number_of_pokemons = 649; for (game.ptrs.pokemons.fat) |_, i| { const pokemon = try game.ptrs.pokemons.fileAs(.{ .i = @intCast(u32, i) }, gen5.BasePokemon); // Wonna crash the compiler? Follow this one simple trick!!! // Remove these variables and do the initialization directly in `ston.serialize` const stats = pokemon.stats; const ev_yield = .{ .hp = pokemon.ev_yield.hp, .attack = pokemon.ev_yield.attack, .defense = pokemon.ev_yield.defense, .speed = pokemon.ev_yield.speed, .sp_attack = pokemon.ev_yield.sp_attack, .sp_defense = pokemon.ev_yield.sp_defense, }; try ston.serialize(writer, .{ .pokemons = ston.index(i, .{ .pokedex_entry = i, .stats = stats, .base_exp_yield = pokemon.base_exp_yield, .catch_rate = pokemon.catch_rate, .ev_yield = ev_yield, .gender_ratio = pokemon.gender_ratio, .egg_cycles = pokemon.egg_cycles, .base_friendship = pokemon.base_friendship, .growth_rate = pokemon.growth_rate, .types = pokemon.types, .items = pokemon.items, .abilities = pokemon.abilities, }) }); // HACK: For some reason, a release build segfaults here for PokΓ©mons // with id above 'number_of_pokemons'. You would think this is // because of an index out of bounds during @tagName, but // common.EggGroup is a u4 enum and has a tag for all possible // values, so it really should not. if (i < number_of_pokemons) { for (pokemon.egg_groups) |group, j| { try ston.serialize(writer, .{ .pokemons = ston.index(i, .{ .egg_groups = ston.index(j, group), }) }); } } const machine_learnset = pokemon.machine_learnset; var j: u7 = 0; while (j < game.ptrs.tms1.len + game.ptrs.tms2.len) : (j += 1) { try ston.serialize(writer, .{ .pokemons = ston.index(i, .{ .tms = ston.index(j, bit.isSet(u128, machine_learnset.value(), j)), }) }); } while (j < game.ptrs.tms1.len + game.ptrs.tms2.len + game.ptrs.hms.len) : (j += 1) { try ston.serialize(writer, .{ .pokemons = ston.index(i, .{ .hms = ston.index(j - (game.ptrs.tms1.len + game.ptrs.tms2.len), bit.isSet(u128, machine_learnset.value(), j)), }) }); } } for (game.ptrs.evolutions) |evos, i| { for (evos.items) |evo, j| { if (evo.method == .unused) continue; try ston.serialize(writer, .{ .pokemons = ston.index(i, .{ .evos = ston.index(j, .{ .method = evo.method, .param = evo.param, .target = evo.target, }), }) }); } } for (game.ptrs.level_up_moves.fat) |_, i| { const bytes = game.ptrs.level_up_moves.fileData(.{ .i = @intCast(u32, i) }); const level_up_moves = mem.bytesAsSlice(gen5.LevelUpMove, bytes); for (level_up_moves) |move, j| { if (std.meta.eql(move, gen5.LevelUpMove.term)) break; try ston.serialize(writer, .{ .pokemons = ston.index(i, .{ .moves = ston.index(j, .{ .id = move.id, .level = move.level, }), }) }); } } for (game.ptrs.items) |item, i| { // Price in gen5 is actually price * 10. I imagine they where trying to avoid // having price be more than a u16 try ston.serialize(writer, .{ .items = ston.index(i, .{ .price = @as(usize, item.price.value()) * 10, .battle_effect = item.battle_effect, .pocket = item.pocket.pocket, }) }); } for (game.ptrs.map_headers) |map_header, i| { try ston.serialize(writer, .{ .maps = ston.index(i, .{ .music = map_header.music, .battle_scene = map_header.battle_scene, }) }); } for (game.ptrs.wild_pokemons.fat) |_, i| { const file = nds.fs.File{ .i = @intCast(u32, i) }; const wilds = game.ptrs.wild_pokemons.fileAs(file, [4]gen5.WildPokemons) catch try game.ptrs.wild_pokemons.fileAs(file, [1]gen5.WildPokemons); for (wilds) |wild_mons, wild_i| { inline for ([_][]const u8{ "grass", "dark_grass", "rustling_grass", "surf", "ripple_surf", "fishing", "ripple_fishing", }) |area_name, j| { var buf: [20]u8 = undefined; const out_name = std.fmt.bufPrint(&buf, "{s}_{}", .{ area_name, wild_i }) catch unreachable; try ston.serialize(writer, .{ .wild_pokemons = ston.index( i, ston.field(out_name, .{ .encounter_rate = wild_mons.rates[j], }), ) }); for (@field(wild_mons, area_name)) |mon, k| { try ston.serialize(writer, .{ .wild_pokemons = ston.index( i, ston.field(out_name, .{ .pokemons = ston.index(k, .{ .species = mon.species.species(), .min_level = mon.min_level, .max_level = mon.max_level, }) }), ) }); } } } } if (game.ptrs.hidden_hollows) |hidden_hollows| { // The nesting is real :) for (hidden_hollows) |hollow, i| { for (hollow.pokemons) |group, j| { for (group.species) |s, k| { try ston.serialize(writer, .{ .hidden_hollows = ston.index(i, .{ .groups = ston.index(j, .{ .pokemons = ston.index(k, .{ .species = s, }), }), }), }); } } try ston.serialize(writer, .{ .hidden_hollows = ston.index(i, .{ .items = hollow.items, }), }); } } try outputGen5StringTable(writer, "pokemons", 0, "name", game.owned.text.pokemon_names); try outputGen5StringTable(writer, "pokedex", 0, "category", game.owned.text.pokedex_category_names); try outputGen5StringTable(writer, "moves", 0, "name", game.owned.text.move_names); try outputGen5StringTable(writer, "moves", 0, "description", game.owned.text.move_descriptions); try outputGen5StringTable(writer, "abilities", 0, "name", game.owned.text.ability_names); try outputGen5StringTable(writer, "items", 0, "name", game.owned.text.item_names); try outputGen5StringTable(writer, "items", 0, "description", game.owned.text.item_descriptions); try outputGen5StringTable(writer, "types", 0, "name", game.owned.text.type_names); try outputGen5StringTable(writer, "trainers", 1, "name", game.owned.text.trainer_names); } fn outputGen5StringTable( writer: anytype, array_name: []const u8, start: usize, field_name: []const u8, table: gen5.StringTable, ) !void { for (table.keys[start..]) |_, i| try outputString(writer, array_name, i + start, field_name, table.getSpan(i + start)); } fn outputString( writer: anytype, array_name: []const u8, i: usize, field_name: []const u8, string: []const u8, ) !void { try ston.serialize(writer, ston.field(array_name, ston.index( i, ston.field(field_name, ston.string(escape.default.escapeFmt(string))), ))); } test { std.testing.refAllDecls(@This()); }
src/core/tm35-load.zig
const std = @import("std"); const parseUnsigned = std.fmt.parseUnsigned; /// Represents text and background color defined in one of the /// several color palletes supported by terminal emulators. pub const Color = union(enum) { /// Default foreground / background color. Note that many terminal /// emulators allow this color to be defined separately from the 16 /// basic colors. default: void, /// 4-bit color. 0-7 are "normal" colors, while 8-15 are "bright" colors. basic: u4, /// 8-bit color, supporting 256 unique colors. Colors 0-15 correspond /// to the same values as basic colors 0-15, while 16-255 are unique. extended: u8, /// 24-bit "true color." Supports the full range of colors used in modern /// graphical applications, but is not supported in older environments. /// Termcon will fall back to 8-bit color where 24-bit color is unsupported. rgb: struct { red: u8, green: u8, blue: u8, }, /// Parse a string of 6 hex digits into a 24-bit color structure. This /// function does not handle a leading # character. If you need to handle /// strings with a leading #, simply slice them accordingly. Also, shorthand /// notation is not permitted: this function only handles 6-digit hex strings /// as they are the most ubiquitous way of specifying color. pub fn parseHex(str: []const u8) error{InvalidHexString}!Color { if (str.len != 6) return error.InvalidHexString; return Color{ .rgb = .{ .red = parseUnsigned(u8, str[0..2], 16) catch return error.InvalidHexString, .green = parseUnsigned(u8, str[2..4], 16) catch return error.InvalidHexString, .blue = parseUnsigned(u8, str[4..6], 16) catch return error.InvalidHexString, }, }; } }; /// Various text attributes that are supported by a few terminal emulators. /// Use at your own risk, and prefer extended or RGB color as some attributes /// may change the displayed color for basic 4-bit color. pub const Attributes = struct { dim: bool = false, bold: bool = false, italic: bool = false, reverse: bool = false, underline: bool = false, blinking: bool = false, }; test "termcon.style.parseHex" { const expectEqual = std.testing.expectEqual; const expectError = std.testing.expectError; const color = Color{ .rgb = .{ .red = 240, .green = 128, .blue = 255, }, }; expectEqual(color, try Color.parseHex("f080ff")); expectEqual(color, comptime (Color.parseHex("f080ff") catch unreachable)); expectError(error.InvalidHexString, Color.parseHex("455")); expectError(error.InvalidHexString, Color.parseHex("z7y8g9")); expectError(error.InvalidHexString, Color.parseHex("+000000")); expectError(error.InvalidHexString, Color.parseHex("-000000")); }
src/style.zig
const std = @import("std"); const testing = std.testing; const stringtime = @import("stringtime"); const Lexer = stringtime.Lexer; const Parser = stringtime.Parser; test "Lex single character token" { const TestInput = [_]struct { input: []const u8, expected: Lexer.Token, }{ .{ .input = "(", .expected = Lexer.Token.left_paren }, .{ .input = ")", .expected = Lexer.Token.right_paren }, .{ .input = "|", .expected = Lexer.Token.vertical_line }, .{ .input = ",", .expected = Lexer.Token.comma }, .{ .input = ".", .expected = Lexer.Token.dot }, }; for (TestInput) |test_input| { var lexer = try Lexer.init(test_input.input); var token_opt = try lexer.next(); testing.expect(token_opt != null); if (token_opt) |token| { testing.expect(std.meta.activeTag(token) == test_input.expected); } } } test "Lex number" { const TestInput = [_]struct { input: []const u8, expected: usize, }{ .{ .input = "0", .expected = 0 }, .{ .input = "1", .expected = 1 }, .{ .input = "200", .expected = 200 }, .{ .input = "1024", .expected = 1024 }, .{ .input = "2077", .expected = 2077 }, .{ .input = "1986", .expected = 1986 }, .{ .input = " \t\r\n1986", .expected = 1986 }, }; for (TestInput) |test_input| { var lexer = try Lexer.init(test_input.input); var token_opt = try lexer.next(); testing.expect(token_opt != null); if (token_opt) |token| { testing.expect(token == .number); testing.expectEqual(test_input.expected, token.number); } } } test "Lex identifier" { const TestInput = [_][]const u8{ "name", "first_name", "last_name", "_ident", "last01", "last_02", }; for (TestInput) |test_input| { var lexer = try Lexer.init(test_input); var token_opt = try lexer.next(); testing.expect(token_opt != null); if (token_opt) |token| { testing.expect(token == .identifier); testing.expectEqualStrings(test_input, token.identifier); } } } test "Lex keywords" { const TestInput = [_]struct { input: []const u8, expected: Lexer.Token, }{ .{ .input = "for", .expected = Lexer.Token.for_loop }, .{ .input = "end", .expected = Lexer.Token.end }, }; for (TestInput) |test_input| { var lexer = try Lexer.init(test_input.input); var token_opt = try lexer.next(); testing.expect(token_opt != null); if (token_opt) |token| { testing.expect(std.meta.activeTag(token) == test_input.expected); } } } test "Lex range" { var lexer = try Lexer.init(".."); var token_opt = try lexer.next(); testing.expect(token_opt != null); if (token_opt) |token| { testing.expect(token == .range); } } test "Lex end of template" { var lexer = try Lexer.init("}}"); var token_opt = try lexer.next(); testing.expect(token_opt != null); if (token_opt) |token| { testing.expect(token == .end_template); } } test "Lex for range loop" { const Expected = [_]@TagType(Lexer.Token){ Lexer.Token.for_loop, Lexer.Token.left_paren, Lexer.Token.number, Lexer.Token.range, Lexer.Token.number, Lexer.Token.right_paren, Lexer.Token.end_template, }; var lexer = try Lexer.init("for(0..10) }}"); var index: usize = 0; while (try lexer.next()) |token| { testing.expect(std.meta.activeTag(token) == Expected[index]); index += 1; } testing.expectEqual(Expected.len, index); } test "Error lexing end_template" { var lexer = try Lexer.init("}"); var token_opt = lexer.next(); testing.expectError(error.MismatchedTemplateDelimiter, token_opt); } test "Error lexing invalid_token" { var lexer = try Lexer.init("!"); var token_opt = lexer.next(); testing.expectError(error.InvalidToken, token_opt); } test "Parse field qualifier expression" { const Input = "first_name \t\r\n}}"; var parser = try Parser.init(testing.allocator, Input); var result_opt = try parser.parse(); testing.expect(result_opt != null); if (result_opt) |result| { defer result.deinit(); testing.expect(result == .field_qualifier); testing.expectEqualStrings("first_name", result.field_qualifier); } } test "Parse end statement" { const Input = "end}}"; var parser = try Parser.init(testing.allocator, Input); var result_opt = try parser.parse(); testing.expect(result_opt != null); if (result_opt) |result| { defer result.deinit(); testing.expect(result == .end); } } test "Parse for range loop" { const Input = "for (0..4) }}"; var parser = try Parser.init(testing.allocator, Input); var result_opt = try parser.parse(); testing.expect(result_opt != null); if (result_opt) |result| { defer result.deinit(); testing.expect(result == .for_loop); testing.expect(result.for_loop.expression == .range); testing.expectEqual(@as(usize, 0), result.for_loop.expression.range.start); testing.expectEqual(@as(usize, 4), result.for_loop.expression.range.end); } } test "Error on missing terminator" { const Input = "for (0..4)"; var parser = try Parser.init(testing.allocator, Input); var result_opt = parser.parse(); testing.expectError(error.MismatchedTemplateDelimiter, result_opt); } test "Error on missing end of range" { const Input = "for (0..) }}"; var parser = try Parser.init(testing.allocator, Input); var result_opt = parser.parse(); testing.expectError(error.ParseError, result_opt); } test "Error on missing right parenthesis" { const Input = "for (0..4 }}"; var parser = try Parser.init(testing.allocator, Input); var result_opt = parser.parse(); testing.expectError(error.ParseError, result_opt); } test "Error on missing left parenthesis" { const Input = "for 0..4) }}"; var parser = try Parser.init(testing.allocator, Input); var result_opt = parser.parse(); testing.expectError(error.ParseError, result_opt); } test "Parse variable capture" { const Input = "for (0..4) |patate| }}"; var parser = try Parser.init(testing.allocator, Input); var result_opt = try parser.parse(); testing.expect(result_opt != null); if (result_opt) |result| { defer result.deinit(); testing.expect(result == .for_loop); testing.expect(result.for_loop.expression == .range); testing.expectEqual(@as(usize, 0), result.for_loop.expression.range.start); testing.expectEqual(@as(usize, 4), result.for_loop.expression.range.end); testing.expectEqual(@as(usize, 1), result.for_loop.variable_captures.items.len); testing.expectEqualStrings("patate", result.for_loop.variable_captures.items[0]); } } test "Error on missing right vertical line in variable capture" { const Input = "for (0..4) |patate }}"; var parser = try Parser.init(testing.allocator, Input); var result_opt = parser.parse(); testing.expectError(error.ParseError, result_opt); } test "Parse foreach loop" { const Input = "for (list) |item| }}"; var parser = try Parser.init(testing.allocator, Input); var result_opt = try parser.parse(); testing.expect(result_opt != null); if (result_opt) |result| { defer result.deinit(); testing.expect(result == .for_loop); testing.expect(result.for_loop.expression == .field_qualifier); testing.expectEqualStrings("list", result.for_loop.expression.field_qualifier); testing.expectEqual(@as(usize, 1), result.for_loop.variable_captures.items.len); testing.expectEqualStrings("item", result.for_loop.variable_captures.items[0]); } } test "Parse fully qualified struct field access" { const TestInput = [_]struct { input: []const u8, expected: []const u8, }{ .{ .input = "name }}", .expected = "name" }, .{ .input = "blog.title }}", .expected = "blog.title" }, .{ .input = "blog.date.created }}", .expected = "blog.date.created" }, .{ .input = "blog.date.start.current }}", .expected = "blog.date.start.current" }, }; for (TestInput) |entry| { var parser = try Parser.init(testing.allocator, entry.input); var result_opt = try parser.parse(); testing.expect(result_opt != null); if (result_opt) |result| { defer result.deinit(); testing.expect(result == .field_qualifier); testing.expectEqualStrings(entry.expected, result.field_qualifier); } } }
tests/parser_tests.zig
const std = @import("std"); const clap = @import("clap"); pub fn main() !void { const stdout = std.io.getStdOut().writer(); const stderr = std.io.getStdErr().writer(); const params = comptime [_]clap.Param(clap.Help){ clap.parseParam("-h, --help Display this help and exit.") catch unreachable, clap.parseParam("--header Display Header ") catch unreachable, clap.parseParam("--sections Display Sections ") catch unreachable, clap.parseParam("--symbols Display Symbols ") catch unreachable, clap.parseParam("--relocations Display Relocations ") catch unreachable, clap.parseParam("--programheaders Display Program Headers ") catch unreachable, clap.parseParam("-a, --all Display All ") catch unreachable, clap.parseParam("<file> The input file. ") catch unreachable, }; var args = try clap.parse(clap.Help, &params, .{}); defer args.deinit(); if (args.flag("--help")) { try clap.help(stderr, &params); return; } if (args.positionals().len != 1) return error.ExpectedFileArgument; const file = try std.fs.cwd().openFile(args.positionals()[0], .{}); defer file.close(); const all = args.flag("--all"); const is_64 = (try std.elf.Header.read(file)).is_64; if (is_64) { const map = try Mapping(true).initFromFile(file); defer map.deinit(); if (args.flag("--header") or all) try dumpHeader(stdout, map); if (args.flag("--sections") or all) try dumpSections(stdout, map); if (args.flag("--symbols") or all) try dumpSymbols(stdout, map); if (args.flag("--relocations") or all) try dumpRelocations(stdout, map); if (args.flag("--programheaders") or all) try dumpProgramHeaders(stdout, map); } else { const map = try Mapping(false).initFromFile(file); defer map.deinit(); if (args.flag("--header") or all) try dumpHeader(stdout, map); if (args.flag("--sections") or all) try dumpSections(stdout, map); if (args.flag("--symbols") or all) try dumpSymbols(stdout, map); if (args.flag("--relocations") or all) try dumpRelocations(stdout, map); if (args.flag("--programheaders") or all) try dumpProgramHeaders(stdout, map); } } fn Mapping(comptime is_64: bool) type { return struct { const Map = @This(); const Shdr = if (is_64) std.elf.Elf64_Shdr else std.elf.Elf32_Shdr; const Ehdr = if (is_64) std.elf.Elf64_Ehdr else std.elf.Elf32_Ehdr; const Phdr = if (is_64) std.elf.Elf64_Phdr else std.elf.Elf32_Phdr; const Sym = if (is_64) std.elf.Elf64_Sym else std.elf.Elf32_Sym; const Dyn = if (is_64) std.elf.Elf64_Dyn else std.elf.Elf32_Dyn; const Rela = if (is_64) Rela_64 else Rela_32; raw: []align(std.mem.page_size) const u8, fn initFromFile(file: std.fs.File) !Map { return Map{ .raw = try std.os.mmap( null, @intCast(usize, (try file.stat()).size), std.os.PROT.READ, std.os.MAP.PRIVATE, file.handle, 0, ), }; } fn deinit(self: Map) void { std.os.munmap(self.raw); } fn header(self: Map) std.elf.Header { //reading 0..@sizeOf(Elf64_Ehdr) is reading more than necessary on 32 bit elf files //but works around a compile error... and should be totally harmless return std.elf.Header.parse(self.raw.ptr[0..@sizeOf(std.elf.Elf64_Ehdr)]) catch unreachable; } fn sectionHeaders(self: Map) []const Shdr { const h = self.header(); return @ptrCast( [*]const Shdr, @alignCast(@alignOf(Shdr), self.raw.ptr + h.shoff), )[0..h.shnum]; } fn sectionNameZ(self: Map, section_header: Shdr) [*:0]const u8 { const h = self.header(); return @ptrCast( [*:0]const u8, self.raw.ptr + self.sectionHeaders()[h.shstrndx].sh_offset + section_header.sh_name, ); } fn sectionName(self: Map, section_header: Shdr) []const u8 { return std.mem.span(self.sectionNameZ(section_header)); } fn symbols(self: Map) []const Sym { return @ptrCast( [*]const Sym, @alignCast(@alignOf(Sym), self.raw.ptr + self.symtab().sh_offset), )[0 .. self.symtab().sh_size / @sizeOf(Sym)]; } fn symbolNameZ(self: Map, symbol: Sym) [*:0]const u8 { return @ptrCast( [*:0]const u8, self.raw.ptr + self.strtab().sh_offset + symbol.st_name, ); } fn symbolName(self: Map, symbol: Sym) []const u8 { return std.mem.span(self.symbolNameZ(symbol)); } fn symtab(self: Map) Shdr { return for (self.sectionHeaders()) |section_header| { const name = self.sectionName(section_header); if (std.mem.eql(u8, ".symtab", name)) break section_header; } else @panic("No .symtab section"); } fn strtab(self: Map) Shdr { return for (self.sectionHeaders()) |section_header| { const name = self.sectionName(section_header); if (std.mem.eql(u8, ".strtab", name)) break section_header; } else @panic("No .strtab section"); } fn dynsym(self: Map) Shdr { return for (self.sectionHeaders()) |section_header| { const name = self.sectionName(section_header); if (std.mem.eql(u8, ".dynsym", name)) break section_header; } else @panic("No .dynsym section"); } fn dynstr(self: Map) Shdr { return for (self.sectionHeaders()) |section_header| { const name = self.sectionName(section_header); if (std.mem.eql(u8, ".dynstr", name)) break section_header; } else @panic("No .dynstr section"); } fn relocationsRela(self: Map, section_header: Shdr) []const Rela { std.debug.assert(section_header.sh_type == std.elf.SHT_RELA); return @ptrCast( [*]const Rela, @alignCast(@alignOf(Rela), self.raw.ptr + section_header.sh_offset), )[0 .. section_header.sh_size / section_header.sh_entsize]; } fn programHeaders(self: Map) []const Phdr { const h = self.header(); return @ptrCast( [*]const Phdr, @alignCast(@alignOf(Phdr), self.raw.ptr + h.phoff), )[0..h.phnum]; } }; } fn dumpHeader(writer: anytype, map: anytype) !void { try writer.print("{}\n", .{map.header()}); } fn dumpSections(writer: anytype, map: anytype) !void { for (map.sectionHeaders()) |section_header| { try writer.print("\"{s}\"\n {}\n", .{ map.sectionName(section_header), section_header }); } } fn dumpSymbols(writer: anytype, map: anytype) !void { for (map.symbols()) |symbol| { try writer.print("\"{s}\"\n {}\n", .{ map.symbolName(symbol), symbol }); } } fn dumpRelocations(writer: anytype, map: anytype) !void { for (map.sectionHeaders()) |section_header| switch (section_header.sh_type) { std.elf.SHT_RELA => for (map.relocationsRela(section_header)) |rela| { const symbolType: enum { symtab, dynsym } = blk: { const section_name = map.sectionName(map.sectionHeaders()[section_header.sh_link]); if (std.mem.eql(u8, ".symtab", section_name)) break :blk .symtab else if (std.mem.eql(u8, ".dynsym", section_name)) break :blk .dynsym else unreachable; //TODO: properly handle }; if (symbolType == .dynsym) @panic("SHT_RELA .dynsym unimplemented"); const symbol_name = map.symbolName(map.symbols()[rela.r_info.sym]); const symbol_section_name = map.sectionName(map.sectionHeaders()[map.symbols()[rela.r_info.sym].st_shndx]); //NOTE: this is what readelf -r seems to do... const name = if (symbol_name.len > 0) symbol_name else symbol_section_name; try writer.print( " {x:0>12} {x:0>12} {s: <16} {s} + {x}\n", .{ rela.r_offset, @bitCast(u64, rela.r_info), @tagName(rela.r_info.type_id), name, rela.r_addend, }, ); }, std.elf.SHT_REL => @panic("SHT_REL unimplemented"), else => {}, }; } fn dumpProgramHeaders(writer: anytype, map: anytype) !void { for (map.programHeaders()) |program_header| { try writer.print("{}\n", .{program_header}); } } const Reloc = enum(u8) { AMD64_NONE, AMD64_64, AMD64_PC32, AMD64_GOT32, AMD64_PLT32, AMD64_COPY, AMD64_GLOB_DAT, AMD64_JUMP_SLOT, AMD64_RELATIVE, AMD64_GOTPCREL, AMD64_32, AMD64_32s, AMD64_16, AMD64_PC16, AMD64_8, AMD64_PC8, AMD64_PC64, AMD64_GOTOFF64, AMD64_GOTPC32, AMD64_SIZE32, AMD64_SIZE64, _, }; const R_INFO = packed struct { type_id: Reloc, byte1: u8, //part of type_info, workaround for packed struct bugs byte2: u8, //part of type_info, workaround for packed struct bugs byte3: u8, //part of type_info, workaround for packed struct bugs sym: u32, fn type_info(self: @This()) u24 { return @bitCast(u24, [_]u8{ self.byte1, self.byte2, self.byte3 }); } }; const Rela_64 = packed struct { r_offset: u64, r_info: R_INFO, r_addend: i64, }; const Rela_32 = packed struct { r_offset: u32, r_info: R_INFO, r_addend: i32, };
src/main.zig
const std = @import("std"); const assert = std.debug.assert; const Camera = @import("Camera.zig"); const Light = @import("Light.zig"); const Material = @import("Material.zig"); const Mesh = @import("Mesh.zig"); const Renderer = @import("Renderer.zig"); const zp = @import("../../zplay.zig"); const drawcall = zp.graphics.common.drawcall; const ShaderProgram = zp.graphics.common.ShaderProgram; const VertexArray = zp.graphics.common.VertexArray; const alg = zp.deps.alg; const Mat4 = alg.Mat4; const Vec2 = alg.Vec2; const Vec3 = alg.Vec3; const Self = @This(); const max_point_light_num = 16; const max_spot_light_num = 16; pub const Error = error{ TooManyPointLights, TooManySpotLights, RendererNotActive, }; /// vertex attribute locations pub const ATTRIB_LOCATION_POS = 0; pub const ATTRIB_LOCATION_NORMAL = 1; pub const ATTRIB_LOCATION_TEX = 2; const vs = \\#version 330 core \\layout (location = 0) in vec3 a_pos; \\layout (location = 1) in vec3 a_normal; \\layout (location = 2) in vec2 a_tex; \\ \\out vec3 v_pos; \\out vec3 v_normal; \\out vec2 v_tex; \\ \\uniform mat4 u_model; \\uniform mat4 u_normal; \\uniform mat4 u_view; \\uniform mat4 u_project; \\ \\void main() \\{ \\ gl_Position = u_project * u_view * u_model * vec4(a_pos, 1.0); \\ v_pos = vec3(u_model * vec4(a_pos, 1.0)); \\ v_normal = mat3(u_normal) * a_normal; \\ v_tex = a_tex; \\} ; const fs = \\#version 330 core \\out vec4 frag_color; \\ \\in vec3 v_pos; \\in vec3 v_normal; \\in vec2 v_tex; \\ \\uniform vec3 u_view_pos; \\ \\struct DirectionalLight { \\ vec3 ambient; \\ vec3 diffuse; \\ vec3 specular; \\ vec3 direction; \\}; \\uniform DirectionalLight u_directional_light; \\ \\struct PointLight { \\ vec3 ambient; \\ vec3 diffuse; \\ vec3 specular; \\ vec3 position; \\ float constant; \\ float linear; \\ float quadratic; \\}; \\#define NR_POINT_LIGHTS 16 \\uniform int u_point_light_count; \\uniform PointLight u_point_lights[NR_POINT_LIGHTS]; \\ \\struct SpotLight { \\ vec3 ambient; \\ vec3 diffuse; \\ vec3 specular; \\ vec3 position; \\ vec3 direction; \\ float constant; \\ float linear; \\ float quadratic; \\ float cutoff; \\ float outer_cutoff; \\}; \\#define NR_SPOT_LIGHTS 16 \\uniform int u_spot_light_count; \\uniform SpotLight u_spot_lights[NR_SPOT_LIGHTS]; \\ \\struct Material { \\ sampler2D diffuse; \\ sampler2D specular; \\ float shiness; \\}; \\uniform Material u_material; \\ \\vec3 ambientColor(vec3 light_color, \\ vec3 material_ambient) \\{ \\ return light_color * material_ambient; \\} \\ \\vec3 diffuseColor(vec3 light_dir, \\ vec3 light_color, \\ vec3 vertex_normal, \\ vec3 material_diffuse) \\{ \\ vec3 norm = normalize(vertex_normal); \\ float diff = max(dot(norm, light_dir), 0.0); \\ return light_color * (diff * material_diffuse); \\} \\ \\vec3 specularColor(vec3 light_dir, \\ vec3 light_color, \\ vec3 view_dir, \\ vec3 vertex_normal, \\ vec3 material_specular, \\ float material_shiness) \\{ \\ vec3 norm = normalize(vertex_normal); \\ vec3 reflect_dir = reflect(-light_dir, norm); \\ float spec = pow(max(dot(view_dir, reflect_dir), 0.0), material_shiness); \\ return light_color * (spec * material_specular); \\} \\ \\vec3 applyDirectionalLight(DirectionalLight light, vec3 material_diffuse, vec3 material_specular, float shiness) \\{ \\ vec3 light_dir = normalize(-light.direction); \\ vec3 view_dir = normalize(u_view_pos - v_pos); \\ vec3 ambient_color = ambientColor(light.ambient, material_diffuse); \\ vec3 diffuse_color = diffuseColor(light_dir, light.diffuse, v_normal, material_diffuse); \\ vec3 specular_color = specularColor(light_dir, light.specular, view_dir, \\ v_normal, material_specular, shiness); \\ vec3 result = ambient_color + diffuse_color + specular_color; \\ return result; \\} \\ \\vec3 applyPointLight(PointLight light, vec3 material_diffuse, vec3 material_specular, float shiness) \\{ \\ vec3 light_dir = normalize(light.position - v_pos); \\ vec3 view_dir = normalize(u_view_pos - v_pos); \\ float distance = length(light.position - v_pos); \\ float attenuation = 1.0 / (light.constant + light.linear * distance + \\ light.quadratic * distance * distance); \\ \\ vec3 ambient_color = ambientColor(light.ambient, material_diffuse); \\ vec3 diffuse_color = diffuseColor(light_dir, light.diffuse, v_normal, material_diffuse); \\ vec3 specular_color = specularColor(light_dir, light.specular, view_dir, \\ v_normal, material_specular, shiness); \\ vec3 result = (ambient_color + diffuse_color + specular_color) * attenuation; \\ return result; \\} \\ \\vec3 applySpotLight(SpotLight light, vec3 material_diffuse, vec3 material_specular, float shiness) \\{ \\ vec3 light_dir = normalize(light.position - v_pos); \\ vec3 view_dir = normalize(u_view_pos - v_pos); \\ float distance = length(light.position - v_pos); \\ float attenuation = 1.0 / (light.constant + light.linear * distance + \\ light.quadratic * distance * distance); \\ float theta = dot(light_dir, normalize(-light.direction)); \\ float epsilon = light.cutoff - light.outer_cutoff; \\ float intensity = clamp((theta - light.outer_cutoff) / epsilon, 0.0, 1.0); \\ \\ vec3 ambient_color = ambientColor(light.ambient, material_diffuse); \\ vec3 diffuse_color = diffuseColor(light_dir, light.diffuse, v_normal, material_diffuse); \\ vec3 specular_color = specularColor(light_dir, light.specular, view_dir, \\ v_normal, material_specular, shiness); \\ vec3 result = ambient_color + (diffuse_color + specular_color) * intensity; \\ \\ return result * attenuation; \\} \\ \\void main() \\{ \\ vec3 material_diffuse = vec3(texture(u_material.diffuse, v_tex)); \\ vec3 material_specular = vec3(texture(u_material.specular, v_tex)); \\ float shiness = u_material.shiness; \\ vec3 result = applyDirectionalLight(u_directional_light, material_diffuse, material_specular, shiness); \\ for (int i = 0; i < u_point_light_count; i++) { \\ result += applyPointLight(u_point_lights[i], material_diffuse, material_specular, shiness); \\ } \\ for (int i = 0; i < u_spot_light_count; i++) { \\ result += applySpotLight(u_spot_lights[i], material_diffuse, material_specular, shiness); \\ } \\ frag_color = vec4(result, 1.0); \\} ; /// lighting program program: ShaderProgram = undefined, /// various lights dir_light: Light = undefined, point_lights: std.ArrayList(Light) = undefined, spot_lights: std.ArrayList(Light) = undefined, /// create a Phong lighting renderer pub fn init(allocator: std.mem.Allocator) Self { return .{ .program = ShaderProgram.init(vs, fs), .dir_light = Light.init( .{ .directional = .{ .ambient = alg.Vec3.new(0.1, 0.1, 0.1), .diffuse = alg.Vec3.new(0.1, 0.1, 0.1), .specular = alg.Vec3.new(0.1, 0.1, 0.1), .direction = alg.Vec3.one().negate(), }, }, ), .point_lights = std.ArrayList(Light).init(allocator), .spot_lights = std.ArrayList(Light).init(allocator), }; } /// free resources pub fn deinit(self: *Self) void { self.program.deinit(); self.point_lights.deinit(); self.spot_lights.deinit(); } /// get renderer pub fn renderer(self: *Self) Renderer { return Renderer.init(self, begin, end, render, renderMesh); } /// set directional light pub fn setDirLight(self: *Self, light: Light) void { std.debug.assert(light.getType() == .directional); self.dir_light = light; } /// add point/spot light pub fn addLight(self: *Self, light: Light) !u32 { switch (light.getType()) { .point => { if (self.point_lights.items.len == max_point_light_num) return error.TooManyPointLights; try self.point_lights.append(light); return @intCast(u32, self.point_lights.items.len - 1); }, .spot => { if (self.spot_lights.items.len == max_spot_light_num) return error.TooManySpotLights; try self.spot_lights.append(light); return @intCast(u32, self.spot_lights.items.len - 1); }, else => { std.debug.panic("invalid light type!", .{}); }, } } /// clear point lights pub fn clearPointLights(self: *Self) void { self.point_lights.resize(0) catch unreachable; } /// clear spot lights pub fn clearSpotLights(self: *Self) void { self.spot_lights.resize(0) catch unreachable; } /// begin rendering fn begin(self: *Self) void { // enable program self.program.use(); // directional light self.dir_light.apply(&self.program, "u_directional_light"); // point lights var buf = [_]u8{0} ** 64; self.program.setUniformByName("u_point_light_count", self.point_lights.items.len); for (self.point_lights.items) |*light, i| { const name = std.fmt.bufPrintZ(&buf, "u_point_lights[{d}]", .{i}) catch unreachable; light.apply(&self.program, name); } // spot lights self.program.setUniformByName("u_spot_light_count", self.spot_lights.items.len); for (self.spot_lights.items) |*light, i| { const name = std.fmt.bufPrintZ(&buf, "u_spot_lights[{d}]", .{i}) catch unreachable; light.apply(&self.program, name); } } /// end rendering fn end(self: *Self) void { self.program.disuse(); } /// use material data fn applyMaterial(self: *Self, material: Material) void { assert(material.data == .phong); var buf: [64]u8 = undefined; self.program.setUniformByName( std.fmt.bufPrintZ(&buf, "u_material.diffuse", .{}) catch unreachable, material.data.phong.diffuse_map.tex.getTextureUnit(), ); self.program.setUniformByName( std.fmt.bufPrintZ(&buf, "u_material.specular", .{}) catch unreachable, material.data.phong.specular_map.tex.getTextureUnit(), ); self.program.setUniformByName( std.fmt.bufPrintZ(&buf, "u_material.shiness", .{}) catch unreachable, material.data.phong.shiness, ); } /// render geometries fn render( self: *Self, vertex_array: VertexArray, use_elements: bool, primitive: drawcall.PrimitiveType, offset: u32, count: u32, model: Mat4, projection: Mat4, camera: ?Camera, material: ?Material, instance_count: ?u32, ) !void { if (!self.program.isUsing()) { return error.RendererNotActive; } // set uniforms self.program.setUniformByName("u_model", model); self.program.setUniformByName("u_normal", model.inv().transpose()); self.program.setUniformByName("u_project", projection); self.program.setUniformByName("u_view", camera.?.getViewMatrix()); self.program.setUniformByName("u_view_pos", camera.?.position); self.applyMaterial(material.?); // issue draw call vertex_array.use(); defer vertex_array.disuse(); if (use_elements) { drawcall.drawElements(primitive, offset, count, u32, instance_count); } else { drawcall.drawBuffer(primitive, offset, count, instance_count); } } fn renderMesh( self: *Self, mesh: Mesh, model: Mat4, projection: Mat4, camera: ?Camera, material: ?Material, instance_count: ?u32, ) !void { if (!self.program.isUsing()) { return error.RendererNotActive; } mesh.vertex_array.use(); defer mesh.vertex_array.disuse(); // attribute settings mesh.vertex_array.setAttribute(Mesh.vbo_positions, ATTRIB_LOCATION_POS, 3, f32, false, 0, 0); assert(mesh.normals != null); mesh.vertex_array.setAttribute(Mesh.vbo_normals, ATTRIB_LOCATION_NORMAL, 3, f32, false, 0, 0); assert(mesh.texcoords != null); mesh.vertex_array.setAttribute(Mesh.vbo_texcoords, ATTRIB_LOCATION_TEX, 2, f32, false, 0, 0); // set uniforms self.program.setUniformByName("u_model", model); self.program.setUniformByName("u_normal", model.inv().transpose()); self.program.setUniformByName("u_project", projection); self.program.setUniformByName("u_view", camera.?.getViewMatrix()); self.program.setUniformByName("u_view_pos", camera.?.position); self.applyMaterial(material.?); // issue draw call if (mesh.indices) |ids| { drawcall.drawElements(mesh.primitive_type, 0, @intCast(u32, ids.items.len), u32, instance_count); } else { drawcall.drawBuffer(mesh.primitive_type, 0, @intCast(u32, mesh.positions.items.len), instance_count); } }
src/graphics/3d/PhongRenderer.zig
const std = @import("std"); const raylibFlags = &[_][]const u8{ "-std=gnu99", "-DPLATFORM_DESKTOP", "-DGL_SILENCE_DEPRECATION", "-fno-sanitize=undefined", // https://github.com/raysan5/raylib/issues/1891 }; fn addRayLib(exe: *std.build.LibExeObjStep) void { exe.addIncludeDir("raylib/include"); exe.addLibPath("raylib/lib"); exe.addIncludeDir("./lib/raylib/src"); exe.addIncludeDir("./lib/raylib/src/external/glfw/include"); exe.addCSourceFile("./lib/raylib/src/rcore.c", raylibFlags); exe.addCSourceFile("./lib/raylib/src/rmodels.c", raylibFlags); exe.addCSourceFile("./lib/raylib/src/raudio.c", raylibFlags); exe.addCSourceFile("./lib/raylib/src/rshapes.c", raylibFlags); exe.addCSourceFile("./lib/raylib/src/rtext.c", raylibFlags); exe.addCSourceFile("./lib/raylib/src/rtextures.c", raylibFlags); exe.addCSourceFile("./lib/raylib/src/utils.c", raylibFlags); exe.addCSourceFile("./lib/raylib/src/rglfw.c", raylibFlags); exe.linkSystemLibrary("GL"); exe.linkSystemLibrary("rt"); exe.linkSystemLibrary("dl"); exe.linkSystemLibrary("m"); exe.linkSystemLibrary("X11"); } pub fn build(b: *std.build.Builder) void { const target = b.standardTargetOptions(.{}); const mode = b.standardReleaseOptions(); // Sandbox const sandbox_exe = b.addExecutable("sandbox", "src/sandbox.zig"); sandbox_exe.setTarget(target); sandbox_exe.setBuildMode(mode); sandbox_exe.linkLibC(); sandbox_exe.linkSystemLibrary("libudev"); addRayLib(sandbox_exe); sandbox_exe.install(); const sandbox_cmd = sandbox_exe.run(); sandbox_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { sandbox_cmd.addArgs(args); } const sandbox_step = b.step("sandbox", "Run the sandbox"); sandbox_step.dependOn(&sandbox_cmd.step); // Main const main_exe = b.addExecutable("cleartouch", "src/main.zig"); main_exe.setTarget(target); main_exe.setBuildMode(mode); main_exe.linkLibC(); main_exe.linkSystemLibrary("libudev"); addRayLib(main_exe); main_exe.addPackagePath("pike", "lib/pike/pike.zig"); main_exe.addPackagePath("clap", "lib/clap/clap.zig"); main_exe.install(); const run_cmd = main_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 builtin = @import("builtin"); const std = @import("std"); const expect = std.testing.expect; const expectEqualSlices = std.testing.expectEqualSlices; const expectEqual = std.testing.expectEqual; const mem = std.mem; // comptime array passed as slice argument comptime { const S = struct { fn indexOfScalarPos(comptime T: type, slice: []const T, start_index: usize, value: T) ?usize { var i: usize = start_index; while (i < slice.len) : (i += 1) { if (slice[i] == value) return i; } return null; } fn indexOfScalar(comptime T: type, slice: []const T, value: T) ?usize { return indexOfScalarPos(T, slice, 0, value); } }; const unsigned = [_]type{ c_uint, c_ulong, c_ulonglong }; const list: []const type = &unsigned; var pos = S.indexOfScalar(type, list, c_ulong).?; if (pos != 1) @compileError("bad pos"); } test "slicing" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; var array: [20]i32 = undefined; array[5] = 1234; var slice = array[5..10]; if (slice.len != 5) unreachable; const ptr = &slice[0]; if (ptr.* != 1234) unreachable; var slice_rest = array[10..]; if (slice_rest.len != 10) unreachable; } test "const slice" { comptime { const a = "1234567890"; try expect(a.len == 10); const b = a[1..2]; try expect(b.len == 1); try expect(b[0] == '2'); } } test "comptime slice of undefined pointer of length 0" { const slice1 = @as([*]i32, undefined)[0..0]; try expect(slice1.len == 0); const slice2 = @as([*]i32, undefined)[100..100]; try expect(slice2.len == 0); } test "implicitly cast array of size 0 to slice" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; var msg = [_]u8{}; try assertLenIsZero(&msg); } fn assertLenIsZero(msg: []const u8) !void { try expect(msg.len == 0); } test "access len index of sentinel-terminated slice" { if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO const S = struct { fn doTheTest() !void { var slice: [:0]const u8 = "hello"; try expect(slice.len == 5); try expect(slice[5] == 0); } }; try S.doTheTest(); comptime try S.doTheTest(); } test "comptime slice of slice preserves comptime var" { comptime { var buff: [10]u8 = undefined; buff[0..][0..][0] = 1; try expect(buff[0..][0..][0] == 1); } } test "slice of type" { comptime { var types_array = [_]type{ i32, f64, type }; for (types_array) |T, i| { switch (i) { 0 => try expect(T == i32), 1 => try expect(T == f64), 2 => try expect(T == type), else => unreachable, } } for (types_array[0..]) |T, i| { switch (i) { 0 => try expect(T == i32), 1 => try expect(T == f64), 2 => try expect(T == type), else => unreachable, } } } } test "generic malloc free" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; const a = memAlloc(u8, 10) catch unreachable; memFree(u8, a); } var some_mem: [100]u8 = undefined; fn memAlloc(comptime T: type, n: usize) anyerror![]T { return @ptrCast([*]T, &some_mem[0])[0..n]; } fn memFree(comptime T: type, memory: []T) void { _ = memory; } test "slice of hardcoded address to pointer" { const S = struct { fn doTheTest() !void { const pointer = @intToPtr([*]u8, 0x04)[0..2]; comptime try expect(@TypeOf(pointer) == *[2]u8); const slice: []const u8 = pointer; try expect(@ptrToInt(slice.ptr) == 4); try expect(slice.len == 2); } }; try S.doTheTest(); } test "comptime slice of pointer preserves comptime var" { comptime { var buff: [10]u8 = undefined; var a = @ptrCast([*]u8, &buff); a[0..1][0] = 1; try expect(buff[0..][0..][0] == 1); } } test "comptime pointer cast array and then slice" { const array = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8 }; const ptrA: [*]const u8 = @ptrCast([*]const u8, &array); const sliceA: []const u8 = ptrA[0..2]; const ptrB: [*]const u8 = &array; const sliceB: []const u8 = ptrB[0..2]; try expect(sliceA[1] == 2); try expect(sliceB[1] == 2); } test "slicing zero length array" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; const s1 = ""[0..]; const s2 = ([_]u32{})[0..]; try expect(s1.len == 0); try expect(s2.len == 0); try expect(mem.eql(u8, s1, "")); try expect(mem.eql(u32, s2, &[_]u32{})); } const x = @intToPtr([*]i32, 0x1000)[0..0x500]; const y = x[0x100..]; test "compile time slice of pointer to hard coded address" { if (builtin.zig_backend == .stage1) return error.SkipZigTest; if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; try expect(@ptrToInt(x) == 0x1000); try expect(x.len == 0x500); try expect(@ptrToInt(y) == 0x1400); try expect(y.len == 0x400); } test "slice string literal has correct type" { comptime { try expect(@TypeOf("aoeu"[0..]) == *const [4:0]u8); const array = [_]i32{ 1, 2, 3, 4 }; try expect(@TypeOf(array[0..]) == *const [4]i32); } var runtime_zero: usize = 0; comptime try expect(@TypeOf("aoeu"[runtime_zero..]) == [:0]const u8); const array = [_]i32{ 1, 2, 3, 4 }; comptime try expect(@TypeOf(array[runtime_zero..]) == []const i32); } test "result location zero sized array inside struct field implicit cast to slice" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO const E = struct { entries: []u32, }; var foo = E{ .entries = &[_]u32{} }; try expect(foo.entries.len == 0); } test "runtime safety lets us slice from len..len" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; var an_array = [_]u8{ 1, 2, 3 }; try expect(mem.eql(u8, sliceFromLenToLen(an_array[0..], 3, 3), "")); } fn sliceFromLenToLen(a_slice: []u8, start: usize, end: usize) []u8 { return a_slice[start..end]; } test "C pointer" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; var buf: [*c]const u8 = "kjdhfkjdhfdkjhfkfjhdfkjdhfkdjhfdkjhf"; var len: u32 = 10; var slice = buf[0..len]; try expect(mem.eql(u8, "kjdhfkjdhf", slice)); } test "C pointer slice access" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; var buf: [10]u32 = [1]u32{42} ** 10; const c_ptr = @ptrCast([*c]const u32, &buf); var runtime_zero: usize = 0; comptime try expectEqual([]const u32, @TypeOf(c_ptr[runtime_zero..1])); comptime try expectEqual(*const [1]u32, @TypeOf(c_ptr[0..1])); for (c_ptr[0..5]) |*cl| { try expect(@as(u32, 42) == cl.*); } } test "comptime slices are disambiguated" { try expect(sliceSum(&[_]u8{ 1, 2 }) == 3); try expect(sliceSum(&[_]u8{ 3, 4 }) == 7); } fn sliceSum(comptime q: []const u8) i32 { comptime var result = 0; inline for (q) |item| { result += item; } return result; } test "slice type with custom alignment" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; const LazilyResolvedType = struct { anything: i32, }; var slice: []align(32) LazilyResolvedType = undefined; var array: [10]LazilyResolvedType align(32) = undefined; slice = &array; slice[1].anything = 42; try expect(array[1].anything == 42); } test "obtaining a null terminated slice" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // here we have a normal array var buf: [50]u8 = undefined; buf[0] = 'a'; buf[1] = 'b'; buf[2] = 'c'; buf[3] = 0; // now we obtain a null terminated slice: const ptr = buf[0..3 :0]; _ = ptr; var runtime_len: usize = 3; const ptr2 = buf[0..runtime_len :0]; // ptr2 is a null-terminated slice comptime try expect(@TypeOf(ptr2) == [:0]u8); comptime try expect(@TypeOf(ptr2[0..2]) == *[2]u8); var runtime_zero: usize = 0; comptime try expect(@TypeOf(ptr2[runtime_zero..2]) == []u8); } test "empty array to slice" { const S = struct { fn doTheTest() !void { const empty: []align(16) u8 = &[_]u8{}; const align_1: []align(1) u8 = empty; const align_4: []align(4) u8 = empty; const align_16: []align(16) u8 = empty; try expect(1 == @typeInfo(@TypeOf(align_1)).Pointer.alignment); try expect(4 == @typeInfo(@TypeOf(align_4)).Pointer.alignment); try expect(16 == @typeInfo(@TypeOf(align_16)).Pointer.alignment); } }; try S.doTheTest(); comptime try S.doTheTest(); } test "@ptrCast slice to pointer" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; const S = struct { fn doTheTest() !void { var array align(@alignOf(u16)) = [5]u8{ 0xff, 0xff, 0xff, 0xff, 0xff }; var slice: []u8 = &array; var ptr = @ptrCast(*u16, slice); try expect(ptr.* == 65535); } }; try S.doTheTest(); comptime try S.doTheTest(); } test "slice syntax resulting in pointer-to-array" { if (builtin.zig_backend != .stage1) return error.SkipZigTest; // TODO const S = struct { fn doTheTest() !void { try testArray(); try testArrayZ(); try testArray0(); try testArrayAlign(); try testPointer(); try testPointerZ(); try testPointer0(); try testPointerAlign(); try testSlice(); try testSliceZ(); try testSlice0(); try testSliceOpt(); try testSliceAlign(); } fn testArray() !void { var array = [5]u8{ 1, 2, 3, 4, 5 }; var slice = array[1..3]; comptime try expect(@TypeOf(slice) == *[2]u8); try expect(slice[0] == 2); try expect(slice[1] == 3); } fn testArrayZ() !void { var array = [5:0]u8{ 1, 2, 3, 4, 5 }; comptime try expect(@TypeOf(array[1..3]) == *[2]u8); comptime try expect(@TypeOf(array[1..5]) == *[4:0]u8); comptime try expect(@TypeOf(array[1..]) == *[4:0]u8); comptime try expect(@TypeOf(array[1..3 :4]) == *[2:4]u8); } fn testArray0() !void { { var array = [0]u8{}; var slice = array[0..0]; comptime try expect(@TypeOf(slice) == *[0]u8); } { var array = [0:0]u8{}; var slice = array[0..0]; comptime try expect(@TypeOf(slice) == *[0:0]u8); try expect(slice[0] == 0); } } fn testArrayAlign() !void { var array align(4) = [5]u8{ 1, 2, 3, 4, 5 }; var slice = array[4..5]; comptime try expect(@TypeOf(slice) == *align(4) [1]u8); try expect(slice[0] == 5); comptime try expect(@TypeOf(array[0..2]) == *align(4) [2]u8); } fn testPointer() !void { var array = [5]u8{ 1, 2, 3, 4, 5 }; var pointer: [*]u8 = &array; var slice = pointer[1..3]; comptime try expect(@TypeOf(slice) == *[2]u8); try expect(slice[0] == 2); try expect(slice[1] == 3); } fn testPointerZ() !void { var array = [5:0]u8{ 1, 2, 3, 4, 5 }; var pointer: [*:0]u8 = &array; comptime try expect(@TypeOf(pointer[1..3]) == *[2]u8); comptime try expect(@TypeOf(pointer[1..3 :4]) == *[2:4]u8); } fn testPointer0() !void { var pointer: [*]const u0 = &[1]u0{0}; var slice = pointer[0..1]; comptime try expect(@TypeOf(slice) == *const [1]u0); try expect(slice[0] == 0); } fn testPointerAlign() !void { var array align(4) = [5]u8{ 1, 2, 3, 4, 5 }; var pointer: [*]align(4) u8 = &array; var slice = pointer[4..5]; comptime try expect(@TypeOf(slice) == *align(4) [1]u8); try expect(slice[0] == 5); comptime try expect(@TypeOf(pointer[0..2]) == *align(4) [2]u8); } fn testSlice() !void { var array = [5]u8{ 1, 2, 3, 4, 5 }; var src_slice: []u8 = &array; var slice = src_slice[1..3]; comptime try expect(@TypeOf(slice) == *[2]u8); try expect(slice[0] == 2); try expect(slice[1] == 3); } fn testSliceZ() !void { var array = [5:0]u8{ 1, 2, 3, 4, 5 }; var slice: [:0]u8 = &array; comptime try expect(@TypeOf(slice[1..3]) == *[2]u8); comptime try expect(@TypeOf(slice[1..]) == [:0]u8); comptime try expect(@TypeOf(slice[1..3 :4]) == *[2:4]u8); } fn testSliceOpt() !void { var array: [2]u8 = [2]u8{ 1, 2 }; var slice: ?[]u8 = &array; comptime try expect(@TypeOf(&array, slice) == ?[]u8); if (builtin.zig_backend != .stage1) { // stage1 is not passing this case comptime try expect(@TypeOf(slice, &array) == ?[]u8); } comptime try expect(@TypeOf(slice.?[0..2]) == *[2]u8); } fn testSlice0() !void { { var array = [0]u8{}; var src_slice: []u8 = &array; var slice = src_slice[0..0]; comptime try expect(@TypeOf(slice) == *[0]u8); } { var array = [0:0]u8{}; var src_slice: [:0]u8 = &array; var slice = src_slice[0..0]; comptime try expect(@TypeOf(slice) == *[0]u8); } } fn testSliceAlign() !void { var array align(4) = [5]u8{ 1, 2, 3, 4, 5 }; var src_slice: []align(4) u8 = &array; var slice = src_slice[4..5]; comptime try expect(@TypeOf(slice) == *align(4) [1]u8); try expect(slice[0] == 5); comptime try expect(@TypeOf(src_slice[0..2]) == *align(4) [2]u8); } fn testConcatStrLiterals() !void { try expectEqualSlices("a"[0..] ++ "b"[0..], "ab"); try expectEqualSlices("a"[0.. :0] ++ "b"[0.. :0], "ab"); } }; try S.doTheTest(); comptime try S.doTheTest(); } test "type coercion of pointer to anon struct literal to pointer to slice" { if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO const S = struct { const U = union { a: u32, b: bool, c: []const u8, }; fn doTheTest() !void { var x1: u8 = 42; const t1 = &.{ x1, 56, 54 }; var slice1: []const u8 = t1; try expect(slice1.len == 3); try expect(slice1[0] == 42); try expect(slice1[1] == 56); try expect(slice1[2] == 54); var x2: []const u8 = "hello"; const t2 = &.{ x2, ", ", "world!" }; // @compileLog(@TypeOf(t2)); var slice2: []const []const u8 = t2; try expect(slice2.len == 3); try expect(mem.eql(u8, slice2[0], "hello")); try expect(mem.eql(u8, slice2[1], ", ")); try expect(mem.eql(u8, slice2[2], "world!")); } }; try S.doTheTest(); comptime try S.doTheTest(); } test "array concat of slices gives slice" { if (builtin.zig_backend != .stage1) return error.SkipZigTest; // TODO comptime { var a: []const u8 = "aoeu"; var b: []const u8 = "asdf"; const c = a ++ b; try expect(std.mem.eql(u8, c, "aoeuasdf")); } } test "slice bounds in comptime concatenation" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO const bs = comptime blk: { const b = "........1........"; break :blk b[8..9]; }; const str = "" ++ bs; try expect(str.len == 1); try expect(std.mem.eql(u8, str, "1")); const str2 = bs ++ ""; try expect(str2.len == 1); try expect(std.mem.eql(u8, str2, "1")); } test "slice sentinel access at comptime" { { const str0 = &[_:0]u8{ '1', '2', '3' }; const slice0: [:0]const u8 = str0; try expect(slice0.len == 3); try expect(slice0[slice0.len] == 0); } { const str0 = "123"; _ = &str0[0]; const slice0: [:0]const u8 = str0; try expect(slice0.len == 3); try expect(slice0[slice0.len] == 0); } }
test/behavior/slice.zig
const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; const maxInt = std.math.maxInt; const minInt = std.math.minInt; /// Returns the binary exponent of x as an integer. /// /// Special Cases: /// - ilogb(+-inf) = maxInt(i32) /// - ilogb(0) = maxInt(i32) /// - ilogb(nan) = maxInt(i32) pub fn ilogb(x: var) i32 { const T = @typeOf(x); return switch (T) { f32 => ilogb32(x), f64 => ilogb64(x), else => @compileError("ilogb not implemented for " ++ @typeName(T)), }; } // NOTE: Should these be exposed publicly? const fp_ilogbnan = -1 - @as(i32, maxInt(u32) >> 1); const fp_ilogb0 = fp_ilogbnan; fn ilogb32(x: f32) i32 { var u = @bitCast(u32, x); var e = @intCast(i32, (u >> 23) & 0xFF); // TODO: We should be able to merge this with the lower check. if (math.isNan(x)) { return maxInt(i32); } if (e == 0) { u <<= 9; if (u == 0) { math.raiseInvalid(); return fp_ilogb0; } // subnormal e = -0x7F; while (u >> 31 == 0) : (u <<= 1) { e -= 1; } return e; } if (e == 0xFF) { math.raiseInvalid(); if (u << 9 != 0) { return fp_ilogbnan; } else { return maxInt(i32); } } return e - 0x7F; } fn ilogb64(x: f64) i32 { var u = @bitCast(u64, x); var e = @intCast(i32, (u >> 52) & 0x7FF); if (math.isNan(x)) { return maxInt(i32); } if (e == 0) { u <<= 12; if (u == 0) { math.raiseInvalid(); return fp_ilogb0; } // subnormal e = -0x3FF; while (u >> 63 == 0) : (u <<= 1) { e -= 1; } return e; } if (e == 0x7FF) { math.raiseInvalid(); if (u << 12 != 0) { return fp_ilogbnan; } else { return maxInt(i32); } } return e - 0x3FF; } test "math.ilogb" { expect(ilogb(@as(f32, 0.2)) == ilogb32(0.2)); expect(ilogb(@as(f64, 0.2)) == ilogb64(0.2)); } test "math.ilogb32" { expect(ilogb32(0.0) == fp_ilogb0); expect(ilogb32(0.5) == -1); expect(ilogb32(0.8923) == -1); expect(ilogb32(10.0) == 3); expect(ilogb32(-123984) == 16); expect(ilogb32(2398.23) == 11); } test "math.ilogb64" { expect(ilogb64(0.0) == fp_ilogb0); expect(ilogb64(0.5) == -1); expect(ilogb64(0.8923) == -1); expect(ilogb64(10.0) == 3); expect(ilogb64(-123984) == 16); expect(ilogb64(2398.23) == 11); } test "math.ilogb32.special" { expect(ilogb32(math.inf(f32)) == maxInt(i32)); expect(ilogb32(-math.inf(f32)) == maxInt(i32)); expect(ilogb32(0.0) == minInt(i32)); expect(ilogb32(math.nan(f32)) == maxInt(i32)); } test "math.ilogb64.special" { expect(ilogb64(math.inf(f64)) == maxInt(i32)); expect(ilogb64(-math.inf(f64)) == maxInt(i32)); expect(ilogb64(0.0) == minInt(i32)); expect(ilogb64(math.nan(f64)) == maxInt(i32)); }
lib/std/math/ilogb.zig
const aoc = @import("../aoc.zig"); const std = @import("std"); const DeterministicDie = struct { current: u8 = 0, rolls: u16 = 0, fn roll(self: *DeterministicDie) [1]u8 { self.current = if (self.current == 100) 1 else self.current + 1; self.rolls += 1; return [_]u8{ self.current }; } }; const DiracDie = struct { fn roll(_: *DiracDie) [3]u8 { return [_]u8 { 1, 2, 3 }; } }; const Player = struct { position: u8, score: u16 = 0, fn move(self: *Player, roll: u8) void { self.position = (self.position + roll) % 10; } fn calcScore(self: *Player) u16 { self.score += if (self.position == 0) 10 else self.position; return self.score; } }; fn Game(comptime Die: type, comptime max_score: u16) type { return struct { const Self = @This(); const Stats = struct { player1_wins: usize = 0, player2_wins: usize = 0, last_winning_game: Self = undefined, }; die: Die = .{}, player1: Player, player2: Player, player1_turn: bool = true, player_rolls: u8 = 0, fn init(player1_position: u8, player2_position: u8) Self { return .{ .player1 = .{ .position = player1_position }, .player2= .{ .position = player2_position }, }; } fn play(self: *Self) Stats { var stats = Stats {}; for (self.die.roll()) |roll| { var new_game = self.*; new_game.playRecursive(&stats, roll, 1); } return stats; } // TODO keep track of per-universe stats fn playRecursive(self: *Self, stats: *Stats, roll: u8, depth: u16) void { // var i: u16 = 0; while (i < depth) : (i += 1) std.debug.print(" ", .{}); // std.debug.print("{} {} {} {} {}\n", .{roll, self.player1_turn, self.player_rolls, self.player1, self.player2}); var current_player = if (self.player1_turn) &self.player1 else &self.player2; current_player.move(roll); self.player_rolls += 1; if (self.player_rolls == 3) { if (current_player.calcScore() >= max_score) { if (self.player1_turn) stats.player1_wins += 1 else stats.player2_wins += 1; stats.last_winning_game = self.*; return; } self.player1_turn = !self.player1_turn; self.player_rolls = 0; } for (self.die.roll()) |next_roll| { var new_game = self.*; new_game.playRecursive(stats, next_roll, depth + 1); } } }; } pub fn run(problem: *aoc.Problem) !aoc.Solution { const player1_line = problem.line().?; const player1_position = player1_line[player1_line.len - 1] - '0'; const player2_line = problem.line().?; const player2_position = player2_line[player2_line.len - 1] - '0'; const s1 = blk: { var game = Game(DeterministicDie, 1000).init(player1_position, player2_position); const stats = game.play(); const loser: usize = if (stats.player1_wins == 0) stats.last_winning_game.player1.score else stats.last_winning_game.player2.score; break :blk loser * stats.last_winning_game.die.rolls; }; // const s2 = blk: { // var game = Game(DiracDie, 21).init(player1_position, player2_position); // const stats = game.play(); // break :blk std.math.max(stats.player1_wins, stats.player2_wins); // }; const s2: usize = 0; return problem.solution(s1, s2); }
src/main/zig/2021/day21.zig
const sabaton = @import("root").sabaton; const std = @import("std"); var data: []u8 = undefined; const BE = sabaton.util.BigEndian; const Header = packed struct { magic: BE(u32), totalsize: BE(u32), off_dt_struct: BE(u32), off_dt_strings: BE(u32), off_mem_rsvmap: BE(u32), version: BE(u32), last_comp_version: BE(u32), boot_cpuid_phys: BE(u32), size_dt_strings: BE(u32), size_dt_struct: BE(u32), }; pub fn find(comptime node_prefix: []const u8, comptime prop_name: []const u8) ![]u8 { const dtb = sabaton.platform.get_dtb(); const header = @ptrCast(*Header, dtb.ptr); std.debug.assert(header.magic.read() == 0xD00DFEED); std.debug.assert(header.totalsize.read() == dtb.len); var curr = @ptrCast([*]BE(u32), dtb.ptr + header.off_dt_struct.read()); var current_depth: usize = 0; var found_at_depth: ?usize = null; while(true) { const opcode = curr[0].read(); curr += 1; switch(opcode) { 0x00000001 => { // FDT_BEGIN_NODE const name = @ptrCast([*:0]u8, curr); const namelen = sabaton.util.strlen(name); if(sabaton.debug) sabaton.log("FDT_BEGIN_NODE(\"{s}\", {})\n", .{name[0..namelen], namelen}); current_depth += 1; if(found_at_depth == null and namelen >= node_prefix.len) { if(std.mem.eql(u8, name[0..node_prefix.len], node_prefix)) { found_at_depth = current_depth; } } curr += (namelen + 4) / 4; }, 0x00000002 => { // FDT_END_NODE if(sabaton.debug) sabaton.log("FDT_END_NODE\n", .{}); if(found_at_depth) |d| { if(d == current_depth) { found_at_depth = null; } } current_depth -= 1; }, 0x00000003 => { // FDT_PROP const nameoff = curr[1].read(); var len = curr[0].read(); const name = @ptrCast([*:0]u8, dtb.ptr + header.off_dt_strings.read() + nameoff); if(sabaton.debug) sabaton.log("FDT_PROP(\"{s}\"), len 0x{X}\n", .{name, len}); if(found_at_depth) |d| { if(d == current_depth) { // DID WE FIND IT?? if(std.mem.eql(u8, name[0..prop_name.len], prop_name) and name[prop_name.len] == 0) return @ptrCast([*]u8, curr + 2)[0..len]; } } len += 3; curr += len / 4 + 2; }, 0x00000004 => { }, // FDT_NOP 0x00000009 => break, // FDT_END else => { if(sabaton.safety) { sabaton.log_hex("Unknown DTB opcode: ", opcode); } unreachable; } } } return error.NotFound; }
src/lib/dtb.zig
const std = @import("std"); const c = @import("c.zig"); var xfb: *anyopaque = undefined; var rmode: *c.GXRModeObj = undefined; export fn main(argc: c_int, argv: [*]const [*:0]const u8) noreturn { _ = argc; _ = argv; // Initialise the video system c.VIDEO_Init(); // This function initialises the attached controllers _ = c.WPAD_Init(); // Obtain the preferred video mode from the system // This will correspond to the settings in the Wii menu rmode = c.VIDEO_GetPreferredMode(null); // Allocate memory for the display in the uncached region xfb = c.MEM_K0_TO_K1(c.SYS_AllocateFramebuffer(rmode)) orelse unreachable; // Initialise the console, required for printf c.console_init(xfb, 20, 20, rmode.fbWidth, rmode.xfbHeight, rmode.fbWidth * c.VI_DISPLAY_PIX_SZ); // Set up the video registers with the chosen mode c.VIDEO_Configure(rmode); // Tell the video hardware where our display memory is c.VIDEO_SetNextFramebuffer(xfb); // Make the display visible c.VIDEO_SetBlack(false); // Flush the video register changes to the hardware c.VIDEO_Flush(); // Wait for Video setup to complete c.VIDEO_WaitVSync(); if (rmode.viTVMode & c.VI_NON_INTERLACE != 0) c.VIDEO_WaitVSync(); // The console understands VT terminal escape codes // This positions the cursor on row 2, column 0 // we can use variables for this with format codes too // e.g. printf ("\x1b[%d;%dH", row, column ); _ = std.c.printf("\x1b[2;0H"); _ = std.c.printf("Hello world from Zig"); while (true) { // Call WPAD_ScanPads each loop, this reads the latest controller states _ = c.WPAD_ScanPads(); // WPAD_ButtonsDown tells us which buttons were pressed in this loop // this is a "one shot" state which will not fire again until the button has been released const pressed = c.WPAD_ButtonsDown(0); // We return to the launcher application via exit if (pressed & c.WPAD_BUTTON_HOME != 0) std.c.exit(0); // Wait for the next frame c.VIDEO_WaitVSync(); } }
src/main.zig
const std = @import("std"); const expect = std.testing.expect; const test_allocator = std.testing.allocator; const Allocator = std.mem.Allocator; const Display = struct { const Self = @This(); allocator: Allocator, inputs: [][][]const u8, outputs: [][][]const u8, pub fn load(allocator: Allocator, str: []const u8) !Self { var allOuts = std.ArrayList([][]const u8).init(allocator); defer allOuts.deinit(); var allIns = std.ArrayList([][]const u8).init(allocator); defer allIns.deinit(); var iter = std.mem.split(u8, str, "\n"); while (iter.next()) |line| { if (line.len != 0) { var outputStrs = std.ArrayList([]const u8).init(allocator); defer outputStrs.deinit(); var inStrs = std.ArrayList([]const u8).init(allocator); defer inStrs.deinit(); const trimmed = std.mem.trimRight(u8, line, "\n"); var halfIter = std.mem.split(u8, trimmed, " | "); var inIter = std.mem.tokenize(u8, halfIter.next().?, " "); while (inIter.next()) |in| { try inStrs.append(in); } try allIns.append(inStrs.toOwnedSlice()); var outIter = std.mem.tokenize(u8, halfIter.next().?, " "); while (outIter.next()) |out| { try outputStrs.append(out); } try allOuts.append(outputStrs.toOwnedSlice()); } } return Self{ .allocator = allocator, .inputs = allIns.toOwnedSlice(), .outputs = allOuts.toOwnedSlice() }; } pub fn deinit(self: *Self) void { for (self.outputs) |out| { self.allocator.free(out); } self.allocator.free(self.outputs); for (self.inputs) |in| { self.allocator.free(in); } self.allocator.free(self.inputs); } pub fn easyCount(self: Self) !i64 { var total: i64 = 0; for (self.outputs) |outputs| { for (outputs) |out| { switch (out.len) { 2, 4, 3, 7 => { total += 1; }, else => {}, } } } return total; } fn sumOutput(input: []const u8, output: []const u8) !i64 { } pub fn outputSum(self: Self) !i64 { var total: i64 = 0; for (self.inputs) |in, idx| { total += try sumOutput(in, self.outputs[idx]); } return total; } }; pub fn main() anyerror!void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); const str = @embedFile("../input.txt"); var d = try Display.load(allocator, str); defer d.deinit(); const stdout = std.io.getStdOut().writer(); const part1 = try d.easyCount(); try stdout.print("Part 1: {d}\n", .{part1}); const part2 = try d.outpuSum(); try stdout.print("Part 2: {d}\n", .{part2}); } test "part1 test" { const str = @embedFile("../test.txt"); var d = try Display.load(test_allocator, str); defer d.deinit(); const score = try d.easyCount(); std.debug.print("\nScore={d}\n", .{score}); try expect(26 == score); } test "part2 test" { const str = @embedFile("../test.txt"); var d = try Display.load(test_allocator, str); defer d.deinit(); const score = try d.outputSum(); std.debug.print("\nScore={d}\n", .{score}); try expect(61229 == score); }
day08/src/main.zig
const std = @import("std"); const assert = std.debug.assert; const tools = @import("tools"); pub const main = tools.defaultMain("2021/day05.txt", run); const Tile = @Vector(2, u2); // [0] only axis aligned, [1] all const Map = tools.Map(Tile, 1000, 1000, false); const Vec2 = tools.Vec2; fn rasterize(map: *Map, a: Vec2, b: Vec2) void { const delta = tools.Vec.clamp(b - a, Vec2{ -1, -1 }, Vec2{ 1, 1 }); const is_diag = @reduce(.And, delta != Vec2{ 0, 0 }); const inc = Tile{ @boolToInt(!is_diag), 1 }; var p = a; while (@reduce(.Or, p != b + delta)) : (p += delta) { const prev = map.get(p) orelse Tile{ 0, 0 }; map.set(p, prev +| inc); } } pub fn run(input: []const u8, gpa: std.mem.Allocator) tools.RunError![2][]const u8 { var map = Map{ .default_tile = Tile{ 0, 0 } }; { //var buf: [1000]u8 = undefined; //const Local = struct { // pub fn toChar(t: Tile) u8 { // const val = t[1]; // return if (val == 0) '.' else (@intCast(u8, val) + '0'); // } //}; var it = std.mem.tokenize(u8, input, "\n\r"); while (it.next()) |line| { if (tools.match_pattern("{},{} -> {},{}", line)) |val| { const a = Vec2{ @intCast(i32, val[0].imm), @intCast(i32, val[1].imm) }; const b = Vec2{ @intCast(i32, val[2].imm), @intCast(i32, val[3].imm) }; rasterize(&map, a, b); } else { std.debug.print("skipping {s}\n", .{line}); } //std.debug.print("trace {s}:\n{s}\n", .{line, map.printToBuf(&buf, .{ .tileToCharFn = Local.toChar })}); } //std.debug.print("map:\n{s}\n", .{map.printToBuf(&buf, .{ .tileToCharFn = Local.toChar })}); } const ans = ans: { var count = @Vector(2, u32){ 0, 0 }; var it = map.iter(null); while (it.next()) |v| count += @as(@Vector(2, u32), @bitCast(@Vector(2, u1), v > Tile{ 1, 1 })); // aka @boolToInt() break :ans count; }; return [_][]const u8{ try std.fmt.allocPrint(gpa, "{}", .{ans[0]}), try std.fmt.allocPrint(gpa, "{}", .{ans[1]}), }; } test { const res = try run( \\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 , std.testing.allocator); defer std.testing.allocator.free(res[0]); defer std.testing.allocator.free(res[1]); try std.testing.expectEqualStrings("5", res[0]); try std.testing.expectEqualStrings("12", res[1]); }
2021/day05.zig
const std = @import("std"); const expect = std.testing.expect; const expectError = std.testing.expectError; const expectEqual = std.testing.expectEqual; const mem = std.mem; test "error values" { const a = @errorToInt(error.err1); const b = @errorToInt(error.err2); try expect(a != b); } test "redefinition of error values allowed" { shouldBeNotEqual(error.AnError, error.SecondError); } fn shouldBeNotEqual(a: anyerror, b: anyerror) void { if (a == b) unreachable; } test "error binary operator" { const a = errBinaryOperatorG(true) catch 3; const b = errBinaryOperatorG(false) catch 3; try expect(a == 3); try expect(b == 10); } fn errBinaryOperatorG(x: bool) anyerror!isize { return if (x) error.ItBroke else @as(isize, 10); } test "empty error union" { const x = error{} || error{}; _ = x; } pub fn foo() anyerror!i32 { const x = try bar(); return x + 1; } pub fn bar() anyerror!i32 { return 13; } pub fn baz() anyerror!i32 { const y = foo() catch 1234; return y + 1; } test "error wrapping" { try expect((baz() catch unreachable) == 15); } test "unwrap simple value from error" { const i = unwrapSimpleValueFromErrorDo() catch unreachable; try expect(i == 13); } fn unwrapSimpleValueFromErrorDo() anyerror!isize { return 13; } test "error return in assignment" { doErrReturnInAssignment() catch unreachable; } fn doErrReturnInAssignment() anyerror!void { var x: i32 = undefined; x = try makeANonErr(); } fn makeANonErr() anyerror!i32 { return 1; } test "syntax: optional operator in front of error union operator" { comptime { try expect(?(anyerror!i32) == ?(anyerror!i32)); } } test "widen cast integer payload of error union function call" { const S = struct { fn errorable() !u64 { var x = @as(u64, try number()); return x; } fn number() anyerror!u32 { return 1234; } }; try expect((try S.errorable()) == 1234); } test "debug info for optional error set" { const SomeError = error{Hello}; var a_local_variable: ?SomeError = null; _ = a_local_variable; } test "implicit cast to optional to error union to return result loc" { const S = struct { fn entry() !void { var x: Foo = undefined; if (func(&x)) |opt| { try expect(opt != null); } else |_| @panic("expected non error"); } fn func(f: *Foo) anyerror!?*Foo { return f; } const Foo = struct { field: i32, }; }; try S.entry(); //comptime S.entry(); TODO }
test/behavior/error.zig
const std = @import("std"); const wayland = @import("wayland.zig"); pub const Object = opaque {}; pub const Message = extern struct { name: [*:0]const u8, signature: [*:0]const u8, types: ?[*]const ?*const Interface, }; pub const Interface = extern struct { name: [*:0]const u8, version: c_int, method_count: c_int, methods: ?[*]const Message, event_count: c_int, events: ?[*]const Message, }; pub const Array = extern struct { size: usize, alloc: usize, data: ?*c_void, /// Does not clone memory pub fn fromArrayList(comptime T: type, list: std.ArrayList(T)) Array { return Array{ .size = list.items.len * @sizeOf(T), .alloc = list.capacity * @sizeOf(T), .data = list.items.ptr, }; } pub fn slice(array: Array, comptime T: type) []T { const ptr = @intToPtr([*]T, @ptrToInt(array.data orelse return &[0]T{})); return ptr[0 .. array.size / @sizeOf(T)]; } }; /// A 24.8 signed fixed-point number. pub const Fixed = extern enum(i32) { _, pub fn toInt(f: Fixed) i24 { return @truncate(i24, @enumToInt(f) >> 8); } pub fn fromInt(i: i24) Fixed { return @intToEnum(Fixed, @as(i32, i) << 8); } pub fn toDouble(f: Fixed) f64 { return @intToFloat(f64, @enumToInt(f)) / 256; } pub fn fromDouble(d: f64) Fixed { return @intToEnum(Fixed, @floatToInt(i32, d * 256)); } }; pub const Argument = extern union { i: i32, u: u32, f: Fixed, s: ?[*:0]const u8, o: ?*Object, n: u32, a: ?*Array, h: i32, }; pub fn Dispatcher(comptime Obj: type, comptime Data: type) type { const client = @hasDecl(Obj, "Event"); const Payload = if (client) Obj.Event else Obj.Request; return struct { pub fn dispatcher( implementation: ?*const c_void, object: if (client) *wayland.client.wl.Proxy else *wayland.server.wl.Resource, opcode: u32, message: *const Message, args: [*]Argument, ) callconv(.C) c_int { inline for (@typeInfo(Payload).Union.fields) |payload_field, payload_num| { if (payload_num == opcode) { var payload_data: payload_field.field_type = undefined; if (payload_field.field_type != void) { inline for (@typeInfo(payload_field.field_type).Struct.fields) |f, i| { switch (@typeInfo(f.field_type)) { // signed/unsigned ints, fds, new_ids, bitfield enums .Int, .Struct => @field(payload_data, f.name) = @bitCast(f.field_type, args[i].u), // objects, strings, arrays .Pointer, .Optional => @field(payload_data, f.name) = @intToPtr(f.field_type, @ptrToInt(args[i].o)), // non-bitfield enums .Enum => @field(payload_data, f.name) = @intToEnum(f.field_type, args[i].i), else => unreachable, } } } @ptrCast(fn (*Obj, Payload, Data) void, implementation)( @ptrCast(*Obj, object), @unionInit(Payload, payload_field.name, payload_data), @intToPtr(Data, @ptrToInt(object.getUserData())), ); return 0; } } unreachable; } }; } test "Fixed" { const testing = @import("std").testing; { const initial: f64 = 10.5301837; const val = Fixed.fromDouble(initial); try testing.expectApproxEqAbs(initial, val.toDouble(), 1.0 / 256.0); try testing.expectEqual(@as(i24, 10), val.toInt()); } { const val = Fixed.fromInt(10); try testing.expectEqual(@as(f64, 10.0), val.toDouble()); try testing.expectEqual(@as(i24, 10), val.toInt()); } }
src/common_core.zig
const std = @import("std"); const interop = @import("../interop.zig"); const iup = @import("../iup.zig"); const Impl = @import("../impl.zig").Impl; const CallbackHandler = @import("../callback_handler.zig").CallbackHandler; const debug = std.debug; const trait = std.meta.trait; const Element = iup.Element; const Handle = iup.Handle; const Error = iup.Error; const ChildrenIterator = iup.ChildrenIterator; const Size = iup.Size; const Margin = iup.Margin; pub const ImageRgba = opaque { pub const CLASS_NAME = "imagergba"; pub const NATIVE_TYPE = iup.NativeType.Image; const Self = @This(); /// /// FLOATING (non inheritable) (at children only): If a child has FLOATING=YES /// then its size and position will be ignored by the layout processing. /// Default: "NO". /// (since 3.0) pub const Floating = enum { Yes, Ignore, No, }; pub const Initializer = struct { last_error: ?anyerror = null, ref: *Self, /// /// Returns a pointer to IUP element or an error. /// Only top-level or detached elements needs to be unwraped, pub fn unwrap(self: Initializer) !*Self { if (self.last_error) |e| { return e; } else { return self.ref; } } /// /// Captures a reference into a external variable /// Allows to capture some references even using full declarative API pub fn capture(self: *Initializer, ref: **Self) Initializer { ref.* = self.ref; return self.*; } pub fn setStrAttribute(self: *Initializer, attributeName: [:0]const u8, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; Self.setStrAttribute(self.ref, attributeName, arg); return self.*; } pub fn setIntAttribute(self: *Initializer, attributeName: [:0]const u8, arg: i32) Initializer { if (self.last_error) |_| return self.*; Self.setIntAttribute(self.ref, attributeName, arg); return self.*; } pub fn setBoolAttribute(self: *Initializer, attributeName: [:0]const u8, arg: bool) Initializer { if (self.last_error) |_| return self.*; Self.setBoolAttribute(self.ref, attributeName, arg); return self.*; } pub fn setPtrAttribute(self: *Initializer, comptime T: type, attributeName: [:0]const u8, value: ?*T) Initializer { if (self.last_error) |_| return self.*; Self.setPtrAttribute(self.ref, T, attributeName, value); return self.*; } pub fn setHandle(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setHandle(self.ref, arg); return self.*; } pub fn resize(self: *Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "RESIZE", .{}, value); return self.*; } pub fn reshape(self: *Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "RESHAPE", .{}, value); return self.*; } pub fn setHotspot(self: *Initializer, x: i32, y: i32) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var value = iup.XYPos.intIntToString(&buffer, x, y, ':'); interop.setStrAttribute(self.ref, "HOTSPOT", .{}, value); return self.*; } pub fn setAutoScale(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "AUTOSCALE", .{}, arg); return self.*; } pub fn setHandleName(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "HANDLENAME", .{}, arg); return self.*; } pub fn clearCache(self: *Initializer) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "CLEARCACHE", .{}, null); return self.*; } pub fn setBgColor(self: *Initializer, rgb: iup.Rgb) Initializer { if (self.last_error) |_| return self.*; interop.setRgb(self.ref, "BGCOLOR", .{}, rgb); return self.*; } /// /// EXPANDWEIGHT (non inheritable) (at children only): If a child defines the /// expand weight, then it is used to multiply the free space used for expansion. /// (since 3.1) pub fn setExpandWeight(self: *Initializer, arg: f64) Initializer { if (self.last_error) |_| return self.*; interop.setDoubleAttribute(self.ref, "EXPANDWEIGHT", .{}, arg); return self.*; } /// /// FLOATING (non inheritable) (at children only): If a child has FLOATING=YES /// then its size and position will be ignored by the layout processing. /// Default: "NO". /// (since 3.0) pub fn setFloating(self: *Initializer, arg: ?Floating) Initializer { if (self.last_error) |_| return self.*; if (arg) |value| switch (value) { .Yes => interop.setStrAttribute(self.ref, "FLOATING", .{}, "YES"), .Ignore => interop.setStrAttribute(self.ref, "FLOATING", .{}, "IGNORE"), .No => interop.setStrAttribute(self.ref, "FLOATING", .{}, "NO"), } else { interop.clearAttribute(self.ref, "FLOATING", .{}); } return self.*; } /// /// TABIMAGEn (non inheritable): image name to be used in the respective tab. /// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name. /// n starts at 0. /// See also IupImage. /// In Motif, the image is shown only if TABTITLEn is NULL. /// In Windows and Motif set the BGCOLOR attribute before setting the image. /// When set after map will update the TABIMAGE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn setTabImage(self: *Initializer, index: i32, arg: anytype) Initializer { if (self.last_error) |_| return self.*; if (interop.validateHandle(.Image, arg)) { interop.setHandleAttribute(self.ref, "TABIMAGE", .{index}, arg); } else |err| { self.last_error = err; } return self.*; } pub fn setTabImageHandleName(self: *Initializer, index: i32, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "TABIMAGE", .{index}, arg); return self.*; } /// /// TABTITLEn (non inheritable): Contains the text to be shown in the /// respective tab title. /// n starts at 0. /// If this value is NULL, it will remain empty. /// The "&" character can be used to define a mnemonic, the next character will /// be used as key. /// Use "&&" to show the "&" character instead on defining a mnemonic. /// The button can be activated from any control in the dialog using the /// "Alt+key" combination. /// (mnemonic support since 3.3). /// When set after map will update the TABTITLE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn setTabTitle(self: *Initializer, index: i32, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "TABTITLE", .{index}, arg); return self.*; } }; pub fn setStrAttribute(self: *Self, attribute: [:0]const u8, arg: [:0]const u8) void { interop.setStrAttribute(self, attribute, .{}, arg); } pub fn getStrAttribute(self: *Self, attribute: [:0]const u8) [:0]const u8 { return interop.getStrAttribute(self, attribute, .{}); } pub fn setIntAttribute(self: *Self, attribute: [:0]const u8, arg: i32) void { interop.setIntAttribute(self, attribute, .{}, arg); } pub fn getIntAttribute(self: *Self, attribute: [:0]const u8) i32 { return interop.getIntAttribute(self, attribute, .{}); } pub fn setBoolAttribute(self: *Self, attribute: [:0]const u8, arg: bool) void { interop.setBoolAttribute(self, attribute, .{}, arg); } pub fn getBoolAttribute(self: *Self, attribute: [:0]const u8) bool { return interop.getBoolAttribute(self, attribute, .{}); } pub fn getPtrAttribute(self: *Self, comptime T: type, attribute: [:0]const u8) ?*T { return interop.getPtrAttribute(T, self, attribute, .{}); } pub fn setPtrAttribute(self: *Self, comptime T: type, attribute: [:0]const u8, value: ?*T) void { interop.setPtrAttribute(T, self, attribute, .{}, value); } pub fn setHandle(self: *Self, arg: [:0]const u8) void { interop.setHandle(self, arg); } pub fn fromHandleName(handle_name: [:0]const u8) ?*Self { return interop.fromHandleName(Self, handle_name); } /// /// Creates an image to be shown on a label, button, toggle, or as a cursor. /// width: Image width in pixels. /// height: Image height in pixels. /// pixels: Vector containing the value of each pixel. /// IupImage uses 1 value per pixel, IupImageRGB uses 3 values and IupImageRGBA uses 4 values per pixel. /// Each value is always 8 bit. /// Origin is at the top-left corner and data is oriented top to bottom, and left to right. /// The pixels array is duplicated internally so you can discard it after the call. pub fn init(width: i32, height: i32, imgdata: ?[]const u8) Initializer { var handle = interop.create_image(Self, width, height, imgdata); if (handle) |valid| { return .{ .ref = @ptrCast(*Self, valid), }; } else { return .{ .ref = undefined, .last_error = Error.NotInitialized }; } } /// /// Destroys an interface element and all its children. /// Only dialogs, timers, popup menus and images should be normally destroyed, but detached elements can also be destroyed. pub fn deinit(self: *Self) void { interop.destroy(self); } /// /// Creates (maps) the native interface objects corresponding to the given IUP interface elements. /// It will also called recursively to create the native element of all the children in the element's tree. /// The element must be already attached to a mapped container, except the dialog. A child can only be mapped if its parent is already mapped. /// This function is automatically called before the dialog is shown in IupShow, IupShowXY or IupPopup. /// If the element is a dialog then the abstract layout will be updated even if the dialog is already mapped. If the dialog is visible the elements will be immediately repositioned. Calling IupMap for an already mapped dialog is the same as only calling IupRefresh for the dialog. /// Calling IupMap for an already mapped element that is not a dialog does nothing. /// If you add new elements to an already mapped dialog you must call IupMap for that elements. And then call IupRefresh to update the dialog layout. /// If the WID attribute of an element is NULL, it means the element was not already mapped. Some containers do not have a native element associated, like VBOX and HBOX. In this case their WID is a fake value (void*)(-1). /// It is useful for the application to call IupMap when the value of the WID attribute must be known, i.e. the native element must exist, before a dialog is made visible. /// The MAP_CB callback is called at the end of the IupMap function, after all processing, so it can also be used to create other things that depend on the WID attribute. But notice that for non dialog elements it will be called before the dialog layout has been updated, so the element current size will still be 0x0 (since 3.14). pub fn map(self: *Self) !void { try interop.map(self); } /// /// pub fn getDialog(self: *Self) ?*iup.Dialog { return interop.getDialog(self); } /// /// Returns the the child element that has the NAME attribute equals to the given value on the same dialog hierarchy. /// Works also for children of a menu that is associated with a dialog. pub fn getDialogChild(self: *Self, byName: [:0]const u8) ?Element { return interop.getDialogChild(self, byName); } /// /// Updates the size and layout of all controls in the same dialog. /// To be used after changing size attributes, or attributes that affect the size of the control. Can be used for any element inside a dialog, but the layout of the dialog and all controls will be updated. It can change the layout of all the controls inside the dialog because of the dynamic layout positioning. pub fn refresh(self: *Self) void { Impl(Self).refresh(self); } pub fn resize(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "RESIZE", .{}, value); } pub fn getScaled(self: *Self) bool { return interop.getBoolAttribute(self, "SCALED", .{}); } pub fn getBpp(self: *Self) i32 { return interop.getIntAttribute(self, "BPP", .{}); } pub fn reshape(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "RESHAPE", .{}, value); } pub fn getChannels(self: *Self) i32 { return interop.getIntAttribute(self, "CHANNELS", .{}); } pub fn getHotspot(self: *Self) iup.XYPos { var str = interop.getStrAttribute(self, "HOTSPOT", .{}); return iup.XYPos.parse(str, ':'); } pub fn setHotspot(self: *Self, x: i32, y: i32) void { var buffer: [128]u8 = undefined; var value = iup.XYPos.intIntToString(&buffer, x, y, ':'); interop.setStrAttribute(self, "HOTSPOT", .{}, value); } pub fn getAutoScale(self: *Self) bool { return interop.getBoolAttribute(self, "AUTOSCALE", .{}); } pub fn setAutoScale(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "AUTOSCALE", .{}, arg); } pub fn getHandleName(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "HANDLENAME", .{}); } pub fn setHandleName(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "HANDLENAME", .{}, arg); } pub fn getHeight(self: *Self) i32 { return interop.getIntAttribute(self, "HEIGHT", .{}); } pub fn clearCache(self: *Self) void { interop.setStrAttribute(self, "CLEARCACHE", .{}, null); } pub fn getBgColor(self: *Self) ?iup.Rgb { return interop.getRgb(self, "BGCOLOR", .{}); } pub fn setBgColor(self: *Self, rgb: iup.Rgb) void { interop.setRgb(self, "BGCOLOR", .{}, rgb); } pub fn getOriginalScale(self: *Self) Size { var str = interop.getStrAttribute(self, "ORIGINALSCALE", .{}); return Size.parse(str); } pub fn getWidth(self: *Self) i32 { return interop.getIntAttribute(self, "WIDTH", .{}); } pub fn getRasterSize(self: *Self) Size { var str = interop.getStrAttribute(self, "RASTERSIZE", .{}); return Size.parse(str); } pub fn getWId(self: *Self) i32 { return interop.getIntAttribute(self, "WID", .{}); } /// /// EXPANDWEIGHT (non inheritable) (at children only): If a child defines the /// expand weight, then it is used to multiply the free space used for expansion. /// (since 3.1) pub fn getExpandWeight(self: *Self) f64 { return interop.getDoubleAttribute(self, "EXPANDWEIGHT", .{}); } /// /// EXPANDWEIGHT (non inheritable) (at children only): If a child defines the /// expand weight, then it is used to multiply the free space used for expansion. /// (since 3.1) pub fn setExpandWeight(self: *Self, arg: f64) void { interop.setDoubleAttribute(self, "EXPANDWEIGHT", .{}, arg); } /// /// FLOATING (non inheritable) (at children only): If a child has FLOATING=YES /// then its size and position will be ignored by the layout processing. /// Default: "NO". /// (since 3.0) pub fn getFloating(self: *Self) ?Floating { var ret = interop.getStrAttribute(self, "FLOATING", .{}); if (std.ascii.eqlIgnoreCase("YES", ret)) return .Yes; if (std.ascii.eqlIgnoreCase("IGNORE", ret)) return .Ignore; if (std.ascii.eqlIgnoreCase("NO", ret)) return .No; return null; } /// /// FLOATING (non inheritable) (at children only): If a child has FLOATING=YES /// then its size and position will be ignored by the layout processing. /// Default: "NO". /// (since 3.0) pub fn setFloating(self: *Self, arg: ?Floating) void { if (arg) |value| switch (value) { .Yes => interop.setStrAttribute(self, "FLOATING", .{}, "YES"), .Ignore => interop.setStrAttribute(self, "FLOATING", .{}, "IGNORE"), .No => interop.setStrAttribute(self, "FLOATING", .{}, "NO"), } else { interop.clearAttribute(self, "FLOATING", .{}); } } /// /// TABIMAGEn (non inheritable): image name to be used in the respective tab. /// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name. /// n starts at 0. /// See also IupImage. /// In Motif, the image is shown only if TABTITLEn is NULL. /// In Windows and Motif set the BGCOLOR attribute before setting the image. /// When set after map will update the TABIMAGE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn getTabImage(self: *Self, index: i32) ?iup.Element { if (interop.getHandleAttribute(self, "TABIMAGE", .{index})) |handle| { return iup.Element.fromHandle(handle); } else { return null; } } /// /// TABIMAGEn (non inheritable): image name to be used in the respective tab. /// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name. /// n starts at 0. /// See also IupImage. /// In Motif, the image is shown only if TABTITLEn is NULL. /// In Windows and Motif set the BGCOLOR attribute before setting the image. /// When set after map will update the TABIMAGE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn setTabImage(self: *Self, index: i32, arg: anytype) !void { try interop.validateHandle(.Image, arg); interop.setHandleAttribute(self, "TABIMAGE", .{index}, arg); } pub fn setTabImageHandleName(self: *Self, index: i32, arg: [:0]const u8) void { interop.setStrAttribute(self, "TABIMAGE", .{index}, arg); } /// /// TABTITLEn (non inheritable): Contains the text to be shown in the /// respective tab title. /// n starts at 0. /// If this value is NULL, it will remain empty. /// The "&" character can be used to define a mnemonic, the next character will /// be used as key. /// Use "&&" to show the "&" character instead on defining a mnemonic. /// The button can be activated from any control in the dialog using the /// "Alt+key" combination. /// (mnemonic support since 3.3). /// When set after map will update the TABTITLE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn getTabTitle(self: *Self, index: i32) [:0]const u8 { return interop.getStrAttribute(self, "TABTITLE", .{index}); } /// /// TABTITLEn (non inheritable): Contains the text to be shown in the /// respective tab title. /// n starts at 0. /// If this value is NULL, it will remain empty. /// The "&" character can be used to define a mnemonic, the next character will /// be used as key. /// Use "&&" to show the "&" character instead on defining a mnemonic. /// The button can be activated from any control in the dialog using the /// "Alt+key" combination. /// (mnemonic support since 3.3). /// When set after map will update the TABTITLE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn setTabTitle(self: *Self, index: i32, arg: [:0]const u8) void { interop.setStrAttribute(self, "TABTITLE", .{index}, arg); } };
src/elements/image_rgba.zig
const std = @import("std"); const builtin = @import("builtin"); const assert = std.debug.assert; const mem = std.mem; const config = @import("config.zig"); const Client = @import("test/cluster.zig").Client; const Cluster = @import("test/cluster.zig").Cluster; const Header = @import("vsr.zig").Header; const Replica = @import("test/cluster.zig").Replica; const StateChecker = @import("test/state_checker.zig").StateChecker; const StateMachine = @import("test/cluster.zig").StateMachine; const PartitionMode = @import("test/packet_simulator.zig").PartitionMode; /// The `log` namespace in this root file is required to implement our custom `log` function. const output = std.log.scoped(.state_checker); /// Set this to `false` if you want to see how literally everything works. /// This will run much slower but will trace all logic across the cluster. const log_state_transitions_only = builtin.mode != .Debug; /// You can fine tune your log levels even further (debug/info/notice/warn/err/crit/alert/emerg): pub const log_level: std.log.Level = if (log_state_transitions_only) .info else .debug; var cluster: *Cluster = undefined; pub fn main() !void { // TODO Use std.testing.allocator when all deinit() leaks are fixed. const allocator = std.heap.page_allocator; var args = std.process.args(); // Skip argv[0] which is the name of this executable: _ = args_next(&args, allocator); const seed_random = std.crypto.random.int(u64); const seed = seed_from_arg: { const arg_two = args_next(&args, allocator) orelse break :seed_from_arg seed_random; defer allocator.free(arg_two); break :seed_from_arg parse_seed(arg_two); }; if (builtin.mode == .ReleaseFast or builtin.mode == .ReleaseSmall) { // We do not support ReleaseFast or ReleaseSmall because they disable assertions. @panic("the simulator must be run with -OReleaseSafe"); } if (seed == seed_random) { if (builtin.mode != .ReleaseSafe) { // If no seed is provided, than Debug is too slow and ReleaseSafe is much faster. @panic("no seed provided: the simulator must be run with -OReleaseSafe"); } if (log_level == .debug) { output.warn("no seed provided: full debug logs are enabled, this will be slow", .{}); } } var prng = std.rand.DefaultPrng.init(seed); const random = prng.random(); const replica_count = 1 + random.uintLessThan(u8, config.replicas_max); const client_count = 1 + random.uintLessThan(u8, config.clients_max); const node_count = replica_count + client_count; const ticks_max = 100_000_000; const transitions_max = config.journal_size_max / config.message_size_max; const request_probability = 1 + random.uintLessThan(u8, 99); const idle_on_probability = random.uintLessThan(u8, 20); const idle_off_probability = 10 + random.uintLessThan(u8, 10); cluster = try Cluster.create(allocator, random, .{ .cluster = 0, .replica_count = replica_count, .client_count = client_count, .seed = random.int(u64), .network_options = .{ .packet_simulator_options = .{ .replica_count = replica_count, .client_count = client_count, .node_count = node_count, .seed = random.int(u64), .one_way_delay_mean = 3 + random.uintLessThan(u16, 10), .one_way_delay_min = random.uintLessThan(u16, 3), .packet_loss_probability = random.uintLessThan(u8, 30), .path_maximum_capacity = 2 + random.uintLessThan(u8, 19), .path_clog_duration_mean = random.uintLessThan(u16, 500), .path_clog_probability = random.uintLessThan(u8, 2), .packet_replay_probability = random.uintLessThan(u8, 50), .partition_mode = random_partition_mode(random), .partition_probability = random.uintLessThan(u8, 3), .unpartition_probability = 1 + random.uintLessThan(u8, 10), .partition_stability = 100 + random.uintLessThan(u32, 100), .unpartition_stability = random.uintLessThan(u32, 20), }, }, .storage_options = .{ .seed = random.int(u64), .read_latency_min = random.uintLessThan(u16, 3), .read_latency_mean = 3 + random.uintLessThan(u16, 10), .write_latency_min = random.uintLessThan(u16, 3), .write_latency_mean = 3 + random.uintLessThan(u16, 10), .read_fault_probability = random.uintLessThan(u8, 10), .write_fault_probability = random.uintLessThan(u8, 10), }, }); defer cluster.destroy(); cluster.state_checker = try StateChecker.init(allocator, cluster); defer cluster.state_checker.deinit(); for (cluster.replicas) |*replica| { replica.on_change_state = on_change_replica; } cluster.on_change_state = on_change_replica; output.info( \\ \\ SEED={} \\ \\ replicas={} \\ clients={} \\ request_probability={}% \\ idle_on_probability={}% \\ idle_off_probability={}% \\ one_way_delay_mean={} ticks \\ one_way_delay_min={} ticks \\ packet_loss_probability={}% \\ path_maximum_capacity={} messages \\ path_clog_duration_mean={} ticks \\ path_clog_probability={}% \\ packet_replay_probability={}% \\ partition_mode={} \\ partition_probability={}% \\ unpartition_probability={}% \\ partition_stability={} ticks \\ unpartition_stability={} ticks \\ read_latency_min={} \\ read_latency_mean={} \\ write_latency_min={} \\ write_latency_mean={} \\ read_fault_probability={}% \\ write_fault_probability={}% \\ , .{ seed, replica_count, client_count, request_probability, idle_on_probability, idle_off_probability, cluster.options.network_options.packet_simulator_options.one_way_delay_mean, cluster.options.network_options.packet_simulator_options.one_way_delay_min, cluster.options.network_options.packet_simulator_options.packet_loss_probability, cluster.options.network_options.packet_simulator_options.path_maximum_capacity, cluster.options.network_options.packet_simulator_options.path_clog_duration_mean, cluster.options.network_options.packet_simulator_options.path_clog_probability, cluster.options.network_options.packet_simulator_options.packet_replay_probability, cluster.options.network_options.packet_simulator_options.partition_mode, cluster.options.network_options.packet_simulator_options.partition_probability, cluster.options.network_options.packet_simulator_options.unpartition_probability, cluster.options.network_options.packet_simulator_options.partition_stability, cluster.options.network_options.packet_simulator_options.unpartition_stability, cluster.options.storage_options.read_latency_min, cluster.options.storage_options.read_latency_mean, cluster.options.storage_options.write_latency_min, cluster.options.storage_options.write_latency_mean, cluster.options.storage_options.read_fault_probability, cluster.options.storage_options.write_fault_probability, }); var requests_sent: u64 = 0; var idle = false; var tick: u64 = 0; while (tick < ticks_max) : (tick += 1) { for (cluster.storages) |*storage| storage.tick(); for (cluster.replicas) |*replica, i| { replica.tick(); cluster.state_checker.check_state(@intCast(u8, i)); } cluster.network.packet_simulator.tick(); for (cluster.clients) |*client| client.tick(); if (cluster.state_checker.transitions == transitions_max) { if (cluster.state_checker.convergence()) break; continue; } else { assert(cluster.state_checker.transitions < transitions_max); } if (requests_sent < transitions_max) { if (idle) { if (chance(random, idle_off_probability)) idle = false; } else { if (chance(random, request_probability)) { if (send_request(random)) requests_sent += 1; } if (chance(random, idle_on_probability)) idle = true; } } } if (cluster.state_checker.transitions < transitions_max) { output.err("you can reproduce this failure with seed={}", .{seed}); @panic("unable to complete transitions_max before ticks_max"); } assert(cluster.state_checker.convergence()); output.info("\n PASSED ({} ticks)", .{tick}); } /// Returns true, `p` percent of the time, else false. fn chance(random: std.rand.Random, p: u8) bool { assert(p <= 100); return random.uintLessThan(u8, 100) < p; } /// Returns the next argument for the simulator or null (if none available) fn args_next(args: *std.process.ArgIterator, allocator: std.mem.Allocator) ?[:0]const u8 { const err_or_bytes = args.next(allocator) orelse return null; return err_or_bytes catch @panic("Unable to extract next value from args"); } fn on_change_replica(replica: *Replica) void { assert(cluster.state_machines[replica.replica].state == replica.state_machine.state); cluster.state_checker.check_state(replica.replica); } fn send_request(random: std.rand.Random) bool { const client_index = random.uintLessThan(u8, cluster.options.client_count); const client = &cluster.clients[client_index]; const checker_request_queue = &cluster.state_checker.client_requests[client_index]; // Ensure that we don't shortchange testing of the full client request queue length: assert(client.request_queue.buffer.len <= checker_request_queue.buffer.len); if (client.request_queue.full()) return false; if (checker_request_queue.full()) return false; const message = client.get_message(); defer client.unref(message); const body_size_max = config.message_size_max - @sizeOf(Header); const body_size: u32 = switch (random.uintLessThan(u8, 100)) { 0...10 => 0, 11...89 => random.uintLessThan(u32, body_size_max), 90...99 => body_size_max, else => unreachable, }; const body = message.buffer[@sizeOf(Header)..][0..body_size]; if (chance(random, 10)) { std.mem.set(u8, body, 0); } else { random.bytes(body); } // While hashing the client ID with the request body prevents input collisions across clients, // it's still possible for the same client to generate the same body, and therefore input hash. const client_input = StateMachine.hash(client.id, body); checker_request_queue.push_assume_capacity(client_input); std.log.scoped(.test_client).debug("client {} sending input={x}", .{ client_index, client_input, }); client.request(0, client_callback, .hash, message, body_size); return true; } fn client_callback( user_data: u128, operation: StateMachine.Operation, results: Client.Error![]const u8, ) void { _ = operation; _ = results catch unreachable; assert(user_data == 0); } /// Returns a random partitioning mode, excluding .custom fn random_partition_mode(random: std.rand.Random) PartitionMode { const typeInfo = @typeInfo(PartitionMode).Enum; var enumAsInt = random.uintAtMost(typeInfo.tag_type, typeInfo.fields.len - 2); if (enumAsInt >= @enumToInt(PartitionMode.custom)) enumAsInt += 1; return @intToEnum(PartitionMode, enumAsInt); } fn parse_seed(bytes: []const u8) u64 { return std.fmt.parseUnsigned(u64, bytes, 10) catch |err| switch (err) { error.Overflow => @panic("seed exceeds a 64-bit unsigned integer"), error.InvalidCharacter => @panic("seed contains an invalid character"), }; } pub fn log( comptime level: std.log.Level, comptime scope: @TypeOf(.EnumLiteral), comptime format: []const u8, args: anytype, ) void { if (log_state_transitions_only and scope != .state_checker) return; const prefix_default = "[" ++ @tagName(level) ++ "] " ++ "(" ++ @tagName(scope) ++ "): "; const prefix = if (log_state_transitions_only) "" else prefix_default; // Print the message to stdout, silently ignoring any errors const stderr = std.io.getStdErr().writer(); std.debug.getStderrMutex().lock(); defer std.debug.getStderrMutex().unlock(); nosuspend stderr.print(prefix ++ format ++ "\n", args) catch return; }
src/simulator.zig
const cuckoo = @import("./lib/zig-cuckoofilter.zig"); const redis = @import("./redismodule.zig"); pub const CUCKOO_FILTER_ENCODING_VERSION = 2; pub var Type8: ?*redis.RedisModuleType = null; pub var Type16: ?*redis.RedisModuleType = null; pub var Type32: ?*redis.RedisModuleType = null; // `s` is the prng state. It's persisted for each key // in order to provide fully deterministic behavior for // insertions. pub const Filter8 = struct { s: [2]u64, cf: cuckoo.Filter8, }; pub const Filter16 = struct { s: [2]u64, cf: cuckoo.Filter16, }; pub const Filter32 = struct { s: [2]u64, cf: cuckoo.Filter32, }; pub fn RegisterTypes(ctx: *redis.RedisModuleCtx) !void { // 8 bit fingerprint Type8 = redis.RedisModule_CreateDataType.?(ctx, c"ccf-kff-1", CUCKOO_FILTER_ENCODING_VERSION, &redis.RedisModuleTypeMethods{ .version = redis.REDISMODULE_TYPE_METHOD_VERSION, .rdb_load = CFLoad8, .rdb_save = CFSave8, .aof_rewrite = CFRewrite, .free = CFFree8, .mem_usage = CFMemUsage8, .digest = CFDigest, }); if (Type8 == null) return error.RegisterError; // 16 bit fingerprint Type16 = redis.RedisModule_CreateDataType.?(ctx, c"ccf-kff-2", CUCKOO_FILTER_ENCODING_VERSION, &redis.RedisModuleTypeMethods{ .version = redis.REDISMODULE_TYPE_METHOD_VERSION, .rdb_load = CFLoad16, .rdb_save = CFSave16, .aof_rewrite = CFRewrite, .free = CFFree16, .mem_usage = CFMemUsage16, .digest = CFDigest, }); if (Type16 == null) return error.RegisterError; // 32 bit fingerprint Type32 = redis.RedisModule_CreateDataType.?(ctx, c"ccf-kff-4", CUCKOO_FILTER_ENCODING_VERSION, &redis.RedisModuleTypeMethods{ .version = redis.REDISMODULE_TYPE_METHOD_VERSION, .rdb_load = CFLoad32, .rdb_save = CFSave32, .aof_rewrite = CFRewrite, .free = CFFree32, .mem_usage = CFMemUsage32, .digest = CFDigest, }); if (Type32 == null) return error.RegisterError; } export fn CFLoad8(rdb: ?*redis.RedisModuleIO, encver: c_int) ?*c_void { return CFLoadImpl(Filter8, rdb, encver); } export fn CFLoad16(rdb: ?*redis.RedisModuleIO, encver: c_int) ?*c_void { return CFLoadImpl(Filter16, rdb, encver); } export fn CFLoad32(rdb: ?*redis.RedisModuleIO, encver: c_int) ?*c_void { return CFLoadImpl(Filter32, rdb, encver); } inline fn CFLoadImpl(comptime CFType: type, rdb: ?*redis.RedisModuleIO, encver: c_int) ?*c_void { if (encver != CUCKOO_FILTER_ENCODING_VERSION) { // We should actually log an error here, or try to implement // the ability to load older versions of our data structure. return null; } // Allocate cf struct var cf = @ptrCast(*CFType, @alignCast(@alignOf(usize), redis.RedisModule_Alloc.?(@sizeOf(CFType)))); // Load const realCFType = @typeOf(cf.cf); cf.* = CFType{ .s = [2]u64{ redis.RedisModule_LoadUnsigned.?(rdb), redis.RedisModule_LoadUnsigned.?(rdb) }, .cf = realCFType{ .rand_fn = null, .homeless_fp = @intCast(realCFType.FPType, redis.RedisModule_LoadUnsigned.?(rdb)), .homeless_bucket_idx = @intCast(usize, redis.RedisModule_LoadUnsigned.?(rdb)), .fpcount = redis.RedisModule_LoadUnsigned.?(rdb), .broken = redis.RedisModule_LoadUnsigned.?(rdb) != 0, .buckets = blk: { var bytes_len: usize = undefined; const buckets_ptr = @alignCast(@alignOf(usize), redis.RedisModule_LoadStringBuffer.?(rdb, &bytes_len))[0..bytes_len]; break :blk realCFType.bytesToBuckets(buckets_ptr) catch @panic("trying to load corrupted buckets from RDB!"); }, }, }; return cf; } export fn CFSave8(rdb: ?*redis.RedisModuleIO, value: ?*c_void) void { CFSaveImpl(Filter8, rdb, value); } export fn CFSave16(rdb: ?*redis.RedisModuleIO, value: ?*c_void) void { CFSaveImpl(Filter16, rdb, value); } export fn CFSave32(rdb: ?*redis.RedisModuleIO, value: ?*c_void) void { CFSaveImpl(Filter32, rdb, value); } inline fn CFSaveImpl(comptime CFType: type, rdb: ?*redis.RedisModuleIO, value: ?*c_void) void { const cf = @ptrCast(*CFType, @alignCast(@alignOf(usize), value)); // Write cuckoo struct data redis.RedisModule_SaveUnsigned.?(rdb, cf.s[0]); redis.RedisModule_SaveUnsigned.?(rdb, cf.s[1]); redis.RedisModule_SaveUnsigned.?(rdb, cf.cf.homeless_fp); redis.RedisModule_SaveUnsigned.?(rdb, cf.cf.homeless_bucket_idx); redis.RedisModule_SaveUnsigned.?(rdb, cf.cf.fpcount); if (cf.cf.broken) redis.RedisModule_SaveUnsigned.?(rdb, 1) else redis.RedisModule_SaveUnsigned.?(rdb, 0); // Write buckets const bytes = @sliceToBytes(cf.cf.buckets); redis.RedisModule_SaveStringBuffer.?(rdb, bytes.ptr, bytes.len); } export fn CFFree8(cf: ?*c_void) void { CFFreeImpl(Filter8, cf); } export fn CFFree16(cf: ?*c_void) void { CFFreeImpl(Filter16, cf); } export fn CFFree32(cf: ?*c_void) void { CFFreeImpl(Filter32, cf); } inline fn CFFreeImpl(comptime CFType: type, value: ?*c_void) void { const cf = @ptrCast(*CFType, @alignCast(@alignOf(usize), value)); redis.RedisModule_Free.?(cf.cf.buckets.ptr); redis.RedisModule_Free.?(cf); } export fn CFMemUsage8(value: ?*const c_void) usize { return CFMemUsageImpl(Filter8, value); } export fn CFMemUsage16(value: ?*const c_void) usize { return CFMemUsageImpl(Filter16, value); } export fn CFMemUsage32(value: ?*const c_void) usize { return CFMemUsageImpl(Filter32, value); } inline fn CFMemUsageImpl(comptime CFType: type, value: ?*const c_void) usize { const cf = @ptrCast(*const CFType, @alignCast(@alignOf(usize), value)); const realCFType = @typeOf(cf.cf); return @sizeOf(CFType) + (@sliceToBytes(cf.cf.buckets).len * @sizeOf(realCFType.FPType)); } export fn CFRewrite(aof: ?*redis.RedisModuleIO, key: ?*redis.RedisModuleString, value: ?*c_void) void {} export fn CFDigest(digest: ?*redis.RedisModuleDigest, value: ?*c_void) void {}
src/t_cuckoofilter.zig
const std = @import("std"); const testing = std.testing; const mem = std.mem; const assert = std.debug.assert; const kisa = @import("kisa"); /// Text buffer implementation. const tbi = @import("text_buffer_array.zig"); /// How Server sees a Client. pub const Client = struct { id: Workspace.Id, active_display_state: ActiveDisplayState, const Self = @This(); pub fn deinit(self: Self) void { _ = self; } }; /// Currently active elements that are displayed on the client. Each client has 1 such struct /// assigned but it is stored on the server still. /// Assumes that these values can only be changed via 1 client and are always present in Workspace. pub const ActiveDisplayState = struct { display_window_id: Workspace.Id, window_pane_id: Workspace.Id, window_tab_id: Workspace.Id, pub const empty = ActiveDisplayState{ .display_window_id = 0, .window_pane_id = 0, .window_tab_id = 0, }; }; // More possible modes: // * searching inside a file // * typing in a command to execute // * moving inside a file // * ... // // More generally we can have these patterns for modes: // * Type a full string and press Enter, e.g. type a named command to be executed // * Type a string and we get an incremental changing of the result, e.g. search window // continuously displays different result based on the search term // * Type a second key to complete the command, e.g. gj moves to the bottom and gk moves to the top // of a file, as a mnemocis "goto" and a direction with hjkl keys // * Variation of the previous mode but it is "sticky", meaning it allows for several presses of // a key with a changed meaning, examples are "insert" mode and a "scrolling" mode /// Modes are different states of an editor which allow to interpret same key presses differently. pub const EditorMode = enum { normal, insert, }; // Workspace supports actions, some optionally take a filename parameter which means they create new // text buffer: // * pane [filename] - create new window pane with current orientation and open last buffer // * panev [filename] - for horizontal/vertical layout, create new window pane vertically // aligned and open last buffer // * tab [filename] - create new tab and open last buffer // * edit filename - open new or existing text buffer in current window pane // * quit - close current window pane but keep text buffer, closes tab and/or editor if // current window pane is a single pane in the tab/editor // * open-buffer - open existing text buffer in current window pane // * delete-buffer - close current text buffer and open the next on in the current window pane // * buffer-only - delete all text buffers but current buffer // * next-buffer - open next text buffer in current window pane // * prev-buffer - open previous text buffer in current window pane // * last-buffer - open last opened buffer for current pane (not globally last opened) // * next-pane - move active pane to next one // * left-pane - for horizontal/vertical layout, move active pane to the left one // * right-pane - for horizontal/vertical layout, move active pane to the right one // * quit-editor - fully deinitialize all the state // // * pane - newWindowPane(orientation: vertical, fileparams: null) // * pane filename - newWindowPane(orientation: vertical, fileparams: data) // * panev - newWindowPane(orientation: horizontal, fileparams: null) // * panev filename - newWindowPane(orientation: horizontal, fileparams: data) // * tab - newWindowTab(fileparams: null) // * tab filename - newWindowTab(fileparams: data) // * edit filename - newTextBuffer(fileparams: data) / openTextBuffer() // * quit - closeWindowPane() // * open-buffer - openTextBuffer() // * delete-buffer - closeTextBuffer() // * delete-all-buffers - closeAllTextBuffers() // * only-buffer - closeAllTextBuffersButCurrent() // * next-buffer - switchTextBuffer(direction: next) // * prev-buffer - switchTextBuffer(direction: previous) // * last-buffer - switchTextBuffer(direction: last) // * next-pane - switchWindowPane(direction: next) // * prev-pane - switchWindowPane(direction: previous) // * last-pane - switchWindowPane(direction: last) // * left-pane - switchWindowPane(direction: left) // * right-pane - switchWindowPane(direction: right) // * quit-editor - deinit() /// Workspace is a collection of all elements in code editor that can be considered a state, /// as well as a set of actions to operate on them from a high-level perspective. /// Workspace is responsible for managing the resources of all the parts of the state. pub const Workspace = struct { ally: *mem.Allocator, text_buffers: std.TailQueue(TextBuffer) = std.TailQueue(TextBuffer){}, display_windows: std.TailQueue(DisplayWindow) = std.TailQueue(DisplayWindow){}, window_tabs: std.TailQueue(WindowTab) = std.TailQueue(WindowTab){}, window_panes: std.TailQueue(WindowPane) = std.TailQueue(WindowPane){}, text_buffer_id_counter: Id = 0, display_window_id_counter: Id = 0, window_tab_id_counter: Id = 0, window_pane_id_counter: Id = 0, pub const Id = u32; const Self = @This(); const TextBufferNode = std.TailQueue(TextBuffer).Node; const DisplayWindowNode = std.TailQueue(DisplayWindow).Node; const WindowTabNode = std.TailQueue(WindowTab).Node; const WindowPaneNode = std.TailQueue(WindowPane).Node; const IdNode = std.TailQueue(Id).Node; const debug_buffer_id = 1; const scratch_buffer_id = 2; pub fn init(ally: *mem.Allocator) Self { return Self{ .ally = ally }; } pub fn initDefaultBuffers(self: *Self) !void { const debug_buffer = try self.createTextBuffer(TextBuffer.InitParams{ .path = null, .name = "*debug*", .contents = "Debug buffer for error messages and debug information", .readonly = true, }); errdefer self.destroyTextBuffer(debug_buffer.data.id); const scratch_buffer = try self.createTextBuffer(TextBuffer.InitParams{ .path = null, .name = "*scratch*", .contents = "Scratch buffer for notes and drafts", }); errdefer self.destroyTextBuffer(scratch_buffer.data.id); assert(debug_buffer.data.id == debug_buffer_id); assert(scratch_buffer.data.id == scratch_buffer_id); } pub fn deinit(self: Self) void { var text_buffer = self.text_buffers.first; while (text_buffer) |tb| { text_buffer = tb.next; tb.data.deinit(); self.ally.destroy(tb); } var display_window = self.display_windows.first; while (display_window) |dw| { display_window = dw.next; dw.data.deinit(); self.ally.destroy(dw); } var window_pane = self.window_panes.first; while (window_pane) |wp| { window_pane = wp.next; wp.data.deinit(); self.ally.destroy(wp); } var window_tab = self.window_tabs.first; while (window_tab) |wt| { window_tab = wt.next; wt.data.deinit(); self.ally.destroy(wt); } } fn checkInit(self: Self) void { var text_buffer = self.text_buffers.first; while (text_buffer) |tb| { text_buffer = tb.next; assert(tb.data.id != 0); } var display_window = self.display_windows.first; while (display_window) |dw| { display_window = dw.next; assert(dw.data.id != 0); } var window_pane = self.window_panes.first; while (window_pane) |wp| { window_pane = wp.next; assert(wp.data.id != 0); } var window_tab = self.window_tabs.first; while (window_tab) |wt| { window_tab = wt.next; assert(wt.data.id != 0); } } /// Initializes all the state elements for a new Client. pub fn new( self: *Self, text_buffer_init_params: TextBuffer.InitParams, window_pane_init_params: WindowPane.InitParams, ) !ActiveDisplayState { var text_buffer = try self.createTextBuffer(text_buffer_init_params); errdefer self.destroyTextBuffer(text_buffer.data.id); var display_window = try self.createDisplayWindow(); errdefer self.destroyDisplayWindow(display_window.data.id); var window_pane = try self.createWindowPane(window_pane_init_params); errdefer self.destroyWindowPane(window_pane.data.id); var window_tab = try self.createWindowTab(); errdefer self.destroyWindowTab(window_tab.data.id); try text_buffer.data.addDisplayWindowId(display_window.data.id); errdefer text_buffer.data.removeDisplayWindowId(display_window.data.id); try window_tab.data.addWindowPaneId(window_pane.data.id); errdefer window_tab.data.removeWindowPaneId(window_pane.data.id); display_window.data.text_buffer_id = text_buffer.data.id; window_pane.data.window_tab_id = window_tab.data.id; display_window.data.window_pane_id = window_pane.data.id; window_pane.data.display_window_id = display_window.data.id; self.checkInit(); return ActiveDisplayState{ .display_window_id = display_window.data.id, .window_pane_id = window_pane.data.id, .window_tab_id = window_tab.data.id, }; } // TODO: rewrite pub fn draw(self: Self, active_display_state: ActiveDisplayState) kisa.DrawData { _ = self; _ = active_display_state; return kisa.DrawData{ .lines = &[_]kisa.DrawData.Line{.{ .number = 1, .contents = "hello", }}, }; } /// Adds text buffer, display window, removes old display window. pub fn newTextBuffer( self: *Self, active_display_state: ActiveDisplayState, text_buffer_init_params: TextBuffer.InitParams, ) !ActiveDisplayState { var text_buffer = try self.createTextBuffer(text_buffer_init_params); errdefer self.destroyTextBuffer(text_buffer.data.id); return self.openTextBuffer( active_display_state, text_buffer.data.id, ) catch |err| switch (err) { error.TextBufferNotFound => unreachable, else => |e| return e, }; } /// Adds display window, removes old display window. pub fn openTextBuffer( self: *Self, active_display_state: ActiveDisplayState, text_buffer_id: Id, ) !ActiveDisplayState { if (self.findTextBuffer(text_buffer_id)) |text_buffer| { var display_window = try self.createDisplayWindow(); errdefer self.destroyDisplayWindow(display_window.data.id); try text_buffer.data.addDisplayWindowId(display_window.data.id); errdefer text_buffer.data.removeDisplayWindowId(display_window.data.id); display_window.data.text_buffer_id = text_buffer.data.id; display_window.data.window_pane_id = active_display_state.window_pane_id; var window_pane = self.findWindowPane(active_display_state.window_pane_id).?; window_pane.data.display_window_id = display_window.data.id; text_buffer.data.removeDisplayWindowId(active_display_state.display_window_id); self.destroyDisplayWindow(active_display_state.display_window_id); return ActiveDisplayState{ .display_window_id = display_window.data.id, .window_pane_id = active_display_state.window_pane_id, .window_tab_id = active_display_state.window_tab_id, }; } else { return error.TextBufferNotFound; } } pub fn newWindowPane( self: *Self, active_display_state: ActiveDisplayState, window_pane_init_params: WindowPane.InitParams, ) !ActiveDisplayState { var window_pane = try self.createWindowPane(window_pane_init_params); errdefer self.destroyWindowPane(window_pane.data.id); var display_window = try self.createDisplayWindow(); errdefer self.destroyDisplayWindow(display_window.data.id); var window_tab = self.findWindowTab(active_display_state.window_tab_id).?; try window_tab.data.addWindowPaneId(window_pane.data.id); errdefer window_tab.data.removeWindowPaneId(window_pane.data.id); window_pane.data.window_tab_id = active_display_state.window_tab_id; window_pane.data.display_window_id = display_window.data.id; display_window.data.window_pane_id = window_pane.data.id; var text_buffer = self.text_buffers.last orelse return error.LastTextBufferAbsent; try text_buffer.data.addDisplayWindowId(display_window.data.id); errdefer text_buffer.data.removeDisplayWindowId(display_window.data.id); display_window.data.text_buffer_id = text_buffer.data.id; return self.openWindowPane( active_display_state, window_pane.data.id, ) catch |err| switch (err) { error.WindowPaneNotFound => unreachable, else => |e| return e, }; } /// Switch active display state only. pub fn openWindowPane( self: *Self, active_display_state: ActiveDisplayState, window_pane_id: Id, ) !ActiveDisplayState { _ = active_display_state; if (self.findWindowPane(window_pane_id)) |window_pane| { return ActiveDisplayState{ .display_window_id = window_pane.data.display_window_id, .window_pane_id = window_pane.data.id, .window_tab_id = window_pane.data.window_tab_id, }; } else { return error.WindowPaneNotFound; } } // TODO: decide on the errors during `close` functions. // TODO: solve when we close current tab and switch to the next tab. /// When several window panes on same tab - Destroy DisplayWindow, WindowPane. pub fn closeWindowPane( self: *Self, active_display_state: ActiveDisplayState, window_pane_id: Id, ) !ActiveDisplayState { if (self.window_panes.len == 1) { // TODO: tell the outer world about our deinitialization and deinit. @panic("not implemented"); } else { var window_tab = self.findWindowTab(active_display_state.window_tab_id).?; window_tab.data.removeWindowPaneId(window_pane_id); // errdefer window_tab.data.addWindowPaneId(window_pane_id) catch {}; const display_window = self.findDisplayWindow(active_display_state.display_window_id).?; var text_buffer = self.findTextBuffer( display_window.data.text_buffer_id, ) orelse return error.ActiveTextBufferAbsent; text_buffer.data.removeDisplayWindowId(display_window.data.id); self.destroyDisplayWindow(active_display_state.display_window_id); self.destroyWindowPane(window_pane_id); const last_window_pane = self.window_panes.last.?; return ActiveDisplayState{ .display_window_id = last_window_pane.data.display_window_id, .window_pane_id = last_window_pane.data.id, .window_tab_id = active_display_state.window_tab_id, }; } } fn createTextBuffer(self: *Self, init_params: TextBuffer.InitParams) !*TextBufferNode { var text_buffer = try self.ally.create(TextBufferNode); errdefer self.ally.destroy(text_buffer); text_buffer.data = try TextBuffer.init(self, init_params); self.text_buffer_id_counter += 1; text_buffer.data.id = self.text_buffer_id_counter; self.text_buffers.append(text_buffer); return text_buffer; } fn createDisplayWindow(self: *Self) !*DisplayWindowNode { var display_window = try self.ally.create(DisplayWindowNode); errdefer self.ally.destroy(display_window); display_window.data = try DisplayWindow.init(self); self.display_window_id_counter += 1; display_window.data.id = self.display_window_id_counter; self.display_windows.append(display_window); return display_window; } fn createWindowPane(self: *Self, init_params: WindowPane.InitParams) !*WindowPaneNode { var window_pane = try self.ally.create(WindowPaneNode); window_pane.data = WindowPane.init(self, init_params); self.window_pane_id_counter += 1; window_pane.data.id = self.window_pane_id_counter; self.window_panes.append(window_pane); return window_pane; } fn createWindowTab(self: *Self) !*WindowTabNode { var window_tab = try self.ally.create(WindowTabNode); window_tab.data = WindowTab.init(self); self.window_tab_id_counter += 1; window_tab.data.id = self.window_tab_id_counter; self.window_tabs.append(window_tab); return window_tab; } fn findTextBuffer(self: Self, id: Id) ?*TextBufferNode { var text_buffer = self.text_buffers.first; while (text_buffer) |tb| : (text_buffer = tb.next) { if (tb.data.id == id) return tb; } return null; } fn findDisplayWindow(self: Self, id: Id) ?*DisplayWindowNode { var display_window = self.display_windows.first; while (display_window) |dw| : (display_window = dw.next) { if (dw.data.id == id) return dw; } return null; } fn findWindowPane(self: Self, id: Id) ?*WindowPaneNode { var window_pane = self.window_panes.first; while (window_pane) |wp| : (window_pane = wp.next) { if (wp.data.id == id) return wp; } return null; } fn findWindowTab(self: Self, id: Id) ?*WindowTabNode { var window_tab = self.window_tabs.first; while (window_tab) |wt| : (window_tab = wt.next) { if (wt.data.id == id) return wt; } return null; } fn destroyTextBuffer(self: *Self, id: Id) void { if (self.findTextBuffer(id)) |text_buffer| { self.text_buffers.remove(text_buffer); text_buffer.data.deinit(); self.ally.destroy(text_buffer); } } fn destroyDisplayWindow(self: *Self, id: Id) void { if (self.findDisplayWindow(id)) |display_window| { self.display_windows.remove(display_window); display_window.data.deinit(); self.ally.destroy(display_window); } } fn destroyWindowPane(self: *Self, id: Id) void { if (self.findWindowPane(id)) |window_pane| { self.window_panes.remove(window_pane); window_pane.data.deinit(); self.ally.destroy(window_pane); } } fn destroyWindowTab(self: *Self, id: Id) void { if (self.findWindowTab(id)) |window_tab| { self.window_tabs.remove(window_tab); window_tab.data.deinit(); self.ally.destroy(window_tab); } } }; /// Assumes that all the currently active elements are the very last ones. fn checkLastStateItemsCongruence(workspace: Workspace, active_display_state: ActiveDisplayState) !void { const window_tab = workspace.window_tabs.last.?; const window_pane = workspace.window_panes.last.?; const display_window = workspace.display_windows.last.?; const text_buffer = workspace.text_buffers.last.?; try testing.expectEqual(display_window.data.id, window_pane.data.display_window_id); try testing.expectEqual(window_tab.data.id, window_pane.data.window_tab_id); try testing.expectEqual(window_pane.data.id, display_window.data.window_pane_id); try testing.expectEqual(text_buffer.data.id, display_window.data.text_buffer_id); try testing.expectEqual(display_window.data.id, text_buffer.data.display_window_ids.last.?.data); try testing.expectEqual(window_pane.data.id, window_tab.data.window_pane_ids.last.?.data); try testing.expectEqual(window_pane.data.id, active_display_state.window_pane_id); try testing.expectEqual(window_tab.data.id, active_display_state.window_tab_id); try testing.expectEqual(display_window.data.id, active_display_state.display_window_id); } test "state: new workspace" { var workspace = Workspace.init(testing.allocator); defer workspace.deinit(); try workspace.initDefaultBuffers(); const text_buffer_init_params = TextBuffer.InitParams{ .contents = "hello", .path = null, .name = "name", }; const window_pane_init_params = WindowPane.InitParams{ .text_area_rows = 1, .text_area_cols = 1 }; const active_display_state = try workspace.new(text_buffer_init_params, window_pane_init_params); try testing.expectEqual(@as(usize, 3), workspace.text_buffers.len); try testing.expectEqual(@as(usize, 1), workspace.display_windows.len); try testing.expectEqual(@as(usize, 1), workspace.window_panes.len); try testing.expectEqual(@as(usize, 1), workspace.window_tabs.len); try testing.expectEqual(@as(usize, 1), workspace.window_tabs.last.?.data.window_pane_ids.len); try testing.expectEqual(@as(usize, 1), workspace.text_buffers.last.?.data.display_window_ids.len); try checkLastStateItemsCongruence(workspace, active_display_state); } test "state: new text buffer" { var workspace = Workspace.init(testing.allocator); defer workspace.deinit(); try workspace.initDefaultBuffers(); const old_text_buffer_init_params = TextBuffer.InitParams{ .contents = "hello", .path = null, .name = "name", }; const window_pane_init_params = WindowPane.InitParams{ .text_area_rows = 1, .text_area_cols = 1 }; const old_active_display_state = try workspace.new(old_text_buffer_init_params, window_pane_init_params); const text_buffer_init_params = TextBuffer.InitParams{ .contents = "hello2", .path = null, .name = "name2", }; const active_display_state = try workspace.newTextBuffer( old_active_display_state, text_buffer_init_params, ); try testing.expectEqual(@as(usize, 4), workspace.text_buffers.len); try testing.expectEqual(@as(usize, 1), workspace.display_windows.len); try testing.expectEqual(@as(usize, 1), workspace.window_panes.len); try testing.expectEqual(@as(usize, 1), workspace.window_tabs.len); try testing.expectEqual(@as(usize, 1), workspace.window_tabs.last.?.data.window_pane_ids.len); try testing.expectEqual(@as(usize, 1), workspace.text_buffers.last.?.data.display_window_ids.len); try checkLastStateItemsCongruence(workspace, active_display_state); } test "state: open existing text buffer" { var workspace = Workspace.init(testing.allocator); defer workspace.deinit(); try workspace.initDefaultBuffers(); const text_buffer_init_params = TextBuffer.InitParams{ .contents = "hello", .path = null, .name = "name", }; const window_pane_init_params = WindowPane.InitParams{ .text_area_rows = 1, .text_area_cols = 1 }; const old_active_display_state = try workspace.new(text_buffer_init_params, window_pane_init_params); const active_display_state = try workspace.openTextBuffer( old_active_display_state, workspace.text_buffers.last.?.data.id, ); try testing.expectEqual(@as(usize, 3), workspace.text_buffers.len); try testing.expectEqual(@as(usize, 1), workspace.display_windows.len); try testing.expectEqual(@as(usize, 1), workspace.window_panes.len); try testing.expectEqual(@as(usize, 1), workspace.window_tabs.len); try testing.expectEqual(@as(usize, 1), workspace.window_tabs.last.?.data.window_pane_ids.len); try testing.expectEqual(@as(usize, 1), workspace.text_buffers.last.?.data.display_window_ids.len); try checkLastStateItemsCongruence(workspace, active_display_state); } test "state: handle failing conditions" { const failing_allocator = &testing.FailingAllocator.init(testing.allocator, 15).allocator; var workspace = Workspace.init(failing_allocator); defer workspace.deinit(); try workspace.initDefaultBuffers(); const text_buffer_init_params = TextBuffer.InitParams{ .contents = "hello", .path = null, .name = "name" }; const window_pane_init_params = WindowPane.InitParams{ .text_area_rows = 1, .text_area_cols = 1 }; const old_active_display_state = try workspace.new(text_buffer_init_params, window_pane_init_params); try testing.expectError(error.OutOfMemory, workspace.openTextBuffer( old_active_display_state, workspace.text_buffers.last.?.data.id, )); try checkLastStateItemsCongruence(workspace, old_active_display_state); } test "state: new window pane" { var workspace = Workspace.init(testing.allocator); defer workspace.deinit(); try workspace.initDefaultBuffers(); const text_buffer_init_params = TextBuffer.InitParams{ .contents = "hello", .path = null, .name = "name", }; const window_pane_init_params = WindowPane.InitParams{ .text_area_rows = 1, .text_area_cols = 1 }; const old_active_display_state = try workspace.new(text_buffer_init_params, window_pane_init_params); const active_display_state = try workspace.newWindowPane( old_active_display_state, window_pane_init_params, ); try testing.expectEqual(@as(usize, 3), workspace.text_buffers.len); try testing.expectEqual(@as(usize, 2), workspace.display_windows.len); try testing.expectEqual(@as(usize, 2), workspace.window_panes.len); try testing.expectEqual(@as(usize, 1), workspace.window_tabs.len); try testing.expectEqual(@as(usize, 2), workspace.window_tabs.last.?.data.window_pane_ids.len); try testing.expectEqual(@as(usize, 2), workspace.text_buffers.last.?.data.display_window_ids.len); try checkLastStateItemsCongruence(workspace, active_display_state); } test "state: close window pane when there are several window panes on window tab" { var workspace = Workspace.init(testing.allocator); defer workspace.deinit(); try workspace.initDefaultBuffers(); const text_buffer_init_params = TextBuffer.InitParams{ .contents = "hello", .path = null, .name = "name", }; const window_pane_init_params = WindowPane.InitParams{ .text_area_rows = 1, .text_area_cols = 1 }; const old_active_display_state = try workspace.new(text_buffer_init_params, window_pane_init_params); const med_active_display_state = try workspace.newWindowPane( old_active_display_state, window_pane_init_params, ); const active_display_state = try workspace.closeWindowPane( med_active_display_state, workspace.window_panes.last.?.data.id, ); try testing.expectEqual(@as(usize, 3), workspace.text_buffers.len); try testing.expectEqual(@as(usize, 1), workspace.display_windows.len); try testing.expectEqual(@as(usize, 1), workspace.window_panes.len); try testing.expectEqual(@as(usize, 1), workspace.window_tabs.len); try testing.expectEqual(@as(usize, 1), workspace.window_tabs.last.?.data.window_pane_ids.len); try testing.expectEqual(@as(usize, 1), workspace.text_buffers.last.?.data.display_window_ids.len); try checkLastStateItemsCongruence(workspace, active_display_state); } pub const TextBuffer = struct { workspace: *Workspace, id: Workspace.Id = 0, display_window_ids: std.TailQueue(Workspace.Id) = std.TailQueue(Workspace.Id){}, contents: tbi.Buffer, /// When path is null, it is a virtual buffer, meaning that it is not connected to a file. path: ?[]u8, /// A textual representation of the buffer name, either path or name for virtual buffer. name: []u8, readonly: bool, metrics: kisa.TextBufferMetrics, line_ending: kisa.TextBufferLineEnding, const Self = @This(); pub const InitParams = struct { path: ?[]const u8, name: []const u8, contents: ?[]const u8, readonly: bool = false, }; /// Takes ownership of `path` and `contents`, they must be allocated with `workspaces` allocator. pub fn init(workspace: *Workspace, init_params: InitParams) !Self { var contents = blk: { if (init_params.contents) |cont| { break :blk try tbi.Buffer.initWithText(workspace.ally, cont); } else if (init_params.path) |p| { var file = std.fs.openFileAbsolute( p, .{}, ) catch |err| switch (err) { error.PipeBusy => unreachable, error.NotDir => unreachable, error.PathAlreadyExists => unreachable, error.WouldBlock => unreachable, error.FileLocksNotSupported => unreachable, error.SharingViolation, error.AccessDenied, error.SymLinkLoop, error.ProcessFdQuotaExceeded, error.SystemFdQuotaExceeded, error.FileNotFound, error.SystemResources, error.NameTooLong, error.NoDevice, error.DeviceBusy, error.FileTooBig, error.NoSpaceLeft, error.IsDir, error.BadPathName, error.InvalidUtf8, error.Unexpected, => |e| return e, }; defer file.close(); break :blk try tbi.Buffer.initWithFile(workspace.ally, file); } else { return error.InitParamsMustHaveEitherPathOrContent; } }; errdefer contents.deinit(); const path = blk: { if (init_params.path) |p| { break :blk try workspace.ally.dupe(u8, p); } else { break :blk null; } }; errdefer if (path) |p| workspace.ally.free(p); const name = try workspace.ally.dupe(u8, init_params.name); errdefer workspace.ally.free(name); var result = Self{ .workspace = workspace, .contents = contents, .path = path, .name = name, .readonly = init_params.readonly, .metrics = kisa.TextBufferMetrics{}, .line_ending = .unix, }; return result; } pub fn deinit(self: *Self) void { var display_window_id = self.display_window_ids.first; while (display_window_id) |dw_id| { display_window_id = dw_id.next; self.workspace.ally.destroy(dw_id); } self.contents.deinit(); if (self.path) |p| self.workspace.ally.free(p); self.workspace.ally.free(self.name); } pub fn addDisplayWindowId(self: *Self, id: Workspace.Id) !void { var display_window_id = try self.workspace.ally.create(Workspace.IdNode); display_window_id.data = id; self.display_window_ids.append(display_window_id); } pub fn removeDisplayWindowId(self: *Self, id: Workspace.Id) void { var display_window_id = self.display_window_ids.first; while (display_window_id) |dw_id| : (display_window_id = dw_id.next) { if (dw_id.data == id) { self.display_window_ids.remove(dw_id); self.workspace.ally.destroy(dw_id); return; } } } // TODO: what do we do with the `Commands` in the main.zig? pub fn command( self: *Self, // display_window_id: Workspace.id, display_window_node: *Workspace.DisplayWindowNode, command_kind: kisa.CommandKind, ) void { switch (command_kind) { .cursor_move_left => { self.cursorMoveLeft(&display_window_node.data.selections); }, else => @panic("not implemented"), } } pub fn cursorMoveLeft(self: *Self, selections: *kisa.Selections) void { _ = self; for (selections.items) |*selection| { if (selection.cursor != 0) { selection.cursor -= 1; if (!selection.anchored and selection.anchor != 0) { selection.anchor -= 1; } } } } }; test "state: text buffer cursor commands" { var workspace = Workspace.init(testing.allocator); defer workspace.deinit(); var text_buffer = try TextBuffer.init( &workspace, TextBuffer.InitParams{ .path = null, .name = "text buffer name", .contents = "Hello", }, ); defer text_buffer.deinit(); var display_window_node = try testing.allocator.create(Workspace.DisplayWindowNode); defer testing.allocator.destroy(display_window_node); display_window_node.data = try DisplayWindow.init(&workspace); defer display_window_node.data.deinit(); display_window_node.data.id = 1; { const selection = display_window_node.data.selections.items[0]; try testing.expectEqual(@as(usize, 0), selection.cursor); try testing.expectEqual(@as(usize, 0), selection.anchor); try testing.expectEqual(true, selection.primary); } text_buffer.command(display_window_node, .cursor_move_left); { const selection = display_window_node.data.selections.items[0]; try testing.expectEqual(@as(usize, 0), selection.cursor); try testing.expectEqual(@as(usize, 0), selection.anchor); try testing.expectEqual(true, selection.primary); } display_window_node.data.selections.items[0] = kisa.Selection{ .cursor = 1, .anchor = 1 }; text_buffer.command(display_window_node, .cursor_move_left); { const selection = display_window_node.data.selections.items[0]; try testing.expectEqual(@as(usize, 0), selection.cursor); try testing.expectEqual(@as(usize, 0), selection.anchor); try testing.expectEqual(true, selection.primary); } } /// Manages the data of what the user sees on the screen. Sends all the necessary data /// to UI to display it on the screen. Also keeps the state of the opened window such /// as cursor, mode etc. pub const DisplayWindow = struct { workspace: *Workspace, id: Workspace.Id = 0, window_pane_id: Workspace.Id = 0, text_buffer_id: Workspace.Id = 0, first_line_number: u32, mode: EditorMode, selections: std.ArrayList(kisa.Selection), const Self = @This(); // TODO: add variables customizing the position in the text. pub fn init(workspace: *Workspace) !Self { var selections = std.ArrayList(kisa.Selection).init(workspace.ally); try selections.append(kisa.Selection{ .cursor = 0, .anchor = 0 }); return Self{ .workspace = workspace, .first_line_number = 1, .mode = .normal, .selections = selections, }; } pub fn deinit(self: Self) void { self.selections.deinit(); } /// Text buffer could have been removed from server, it is not fully controlled by /// current display window. pub fn textBuffer(self: Self) ?*Workspace.TextBufferNode { self.workspace.findTextBuffer(self.text_buffer_id); } }; /// Editor tab can have several panes, each pane can have several display windows. pub const WindowPane = struct { workspace: *Workspace, id: Workspace.Id = 0, window_tab_id: Workspace.Id = 0, display_window_id: Workspace.Id = 0, /// y dimension of available space. text_area_rows: u32, /// x dimension of available space. text_area_cols: u32, const Self = @This(); pub const InitParams = struct { text_area_rows: u32, text_area_cols: u32, }; pub fn init(workspace: *Workspace, init_params: InitParams) Self { assert(init_params.text_area_rows != 0); assert(init_params.text_area_cols != 0); return Self{ .workspace = workspace, .text_area_rows = init_params.text_area_rows, .text_area_cols = init_params.text_area_cols, }; } pub fn deinit(self: Self) void { _ = self; } }; /// Editor can have several tabs, each tab can have several window panes. pub const WindowTab = struct { workspace: *Workspace, id: Workspace.Id = 0, window_pane_ids: std.TailQueue(Workspace.Id) = std.TailQueue(Workspace.Id){}, const Self = @This(); pub fn init(workspace: *Workspace) Self { return Self{ .workspace = workspace }; } pub fn deinit(self: Self) void { var window_pane_id = self.window_pane_ids.first; while (window_pane_id) |wp_id| { window_pane_id = wp_id.next; self.workspace.ally.destroy(wp_id); } } pub fn addWindowPaneId(self: *Self, id: Workspace.Id) !void { var window_pane_id = try self.workspace.ally.create(Workspace.IdNode); window_pane_id.data = id; self.window_pane_ids.append(window_pane_id); } pub fn removeWindowPaneId(self: *Self, id: Workspace.Id) void { var window_pane_id = self.window_pane_ids.first; while (window_pane_id) |wp_id| : (window_pane_id = wp_id.next) { if (wp_id.data == id) { self.window_pane_ids.remove(wp_id); self.workspace.ally.destroy(wp_id); return; } } } };
src/state.zig
const Emit = @This(); const std = @import("std"); const math = std.math; const Mir = @import("Mir.zig"); const bits = @import("bits.zig"); const link = @import("../../link.zig"); const Module = @import("../../Module.zig"); const ErrorMsg = Module.ErrorMsg; const assert = std.debug.assert; const DW = std.dwarf; const leb128 = std.leb; const Instruction = bits.Instruction; const Register = bits.Register; const DebugInfoOutput = @import("../../codegen.zig").DebugInfoOutput; mir: Mir, bin_file: *link.File, debug_output: DebugInfoOutput, target: *const std.Target, err_msg: ?*ErrorMsg = null, src_loc: Module.SrcLoc, code: *std.ArrayList(u8), prev_di_line: u32, prev_di_column: u32, /// Relative to the beginning of `code`. prev_di_pc: usize, const InnerError = error{ OutOfMemory, EmitFail, }; pub fn emitMir( emit: *Emit, ) !void { const mir_tags = emit.mir.instructions.items(.tag); for (mir_tags) |tag, index| { const inst = @intCast(u32, index); switch (tag) { .add_immediate => try emit.mirAddSubtractImmediate(inst), .sub_immediate => try emit.mirAddSubtractImmediate(inst), .b => try emit.mirBranch(inst), .bl => try emit.mirBranch(inst), .blr => try emit.mirUnconditionalBranchRegister(inst), .ret => try emit.mirUnconditionalBranchRegister(inst), .brk => try emit.mirExceptionGeneration(inst), .svc => try emit.mirExceptionGeneration(inst), .call_extern => try emit.mirCallExtern(inst), .dbg_line => try emit.mirDbgLine(inst), .dbg_prologue_end => try emit.mirDebugPrologueEnd(), .dbg_epilogue_begin => try emit.mirDebugEpilogueBegin(), .load_memory => try emit.mirLoadMemory(inst), .ldp => try emit.mirLoadStoreRegisterPair(inst), .stp => try emit.mirLoadStoreRegisterPair(inst), .ldr => try emit.mirLoadStoreRegister(inst), .ldrb => try emit.mirLoadStoreRegister(inst), .ldrh => try emit.mirLoadStoreRegister(inst), .str => try emit.mirLoadStoreRegister(inst), .strb => try emit.mirLoadStoreRegister(inst), .strh => try emit.mirLoadStoreRegister(inst), .mov_register => try emit.mirMoveRegister(inst), .mov_to_from_sp => try emit.mirMoveRegister(inst), .movk => try emit.mirMoveWideImmediate(inst), .movz => try emit.mirMoveWideImmediate(inst), .nop => try emit.mirNop(), } } } fn writeInstruction(emit: *Emit, instruction: Instruction) !void { const endian = emit.target.cpu.arch.endian(); std.mem.writeInt(u32, try emit.code.addManyAsArray(4), instruction.toU32(), endian); } fn fail(emit: *Emit, comptime format: []const u8, args: anytype) InnerError { @setCold(true); assert(emit.err_msg == null); emit.err_msg = try ErrorMsg.create(emit.bin_file.allocator, emit.src_loc, format, args); return error.EmitFail; } fn moveImmediate(emit: *Emit, reg: Register, imm64: u64) !void { try emit.writeInstruction(Instruction.movz(reg, @truncate(u16, imm64), 0)); if (imm64 > math.maxInt(u16)) { try emit.writeInstruction(Instruction.movk(reg, @truncate(u16, imm64 >> 16), 16)); } if (imm64 > math.maxInt(u32)) { try emit.writeInstruction(Instruction.movk(reg, @truncate(u16, imm64 >> 32), 32)); } if (imm64 > math.maxInt(u48)) { try emit.writeInstruction(Instruction.movk(reg, @truncate(u16, imm64 >> 48), 48)); } } fn dbgAdvancePCAndLine(self: *Emit, line: u32, column: u32) !void { const delta_line = @intCast(i32, line) - @intCast(i32, self.prev_di_line); const delta_pc: usize = self.code.items.len - self.prev_di_pc; switch (self.debug_output) { .dwarf => |dbg_out| { // TODO Look into using the DWARF special opcodes to compress this data. // It lets you emit single-byte opcodes that add different numbers to // both the PC and the line number at the same time. try dbg_out.dbg_line.ensureUnusedCapacity(11); dbg_out.dbg_line.appendAssumeCapacity(DW.LNS.advance_pc); leb128.writeULEB128(dbg_out.dbg_line.writer(), delta_pc) catch unreachable; if (delta_line != 0) { dbg_out.dbg_line.appendAssumeCapacity(DW.LNS.advance_line); leb128.writeILEB128(dbg_out.dbg_line.writer(), delta_line) catch unreachable; } dbg_out.dbg_line.appendAssumeCapacity(DW.LNS.copy); self.prev_di_pc = self.code.items.len; self.prev_di_line = line; self.prev_di_column = column; self.prev_di_pc = self.code.items.len; }, .plan9 => |dbg_out| { if (delta_pc <= 0) return; // only do this when the pc changes // we have already checked the target in the linker to make sure it is compatable const quant = @import("../../link/Plan9/aout.zig").getPCQuant(self.target.cpu.arch) catch unreachable; // increasing the line number try @import("../../link/Plan9.zig").changeLine(dbg_out.dbg_line, delta_line); // increasing the pc const d_pc_p9 = @intCast(i64, delta_pc) - quant; if (d_pc_p9 > 0) { // minus one because if its the last one, we want to leave space to change the line which is one quanta try dbg_out.dbg_line.append(@intCast(u8, @divExact(d_pc_p9, quant) + 128) - quant); if (dbg_out.pcop_change_index.*) |pci| dbg_out.dbg_line.items[pci] += 1; dbg_out.pcop_change_index.* = @intCast(u32, dbg_out.dbg_line.items.len - 1); } else if (d_pc_p9 == 0) { // we don't need to do anything, because adding the quant does it for us } else unreachable; if (dbg_out.start_line.* == null) dbg_out.start_line.* = self.prev_di_line; dbg_out.end_line.* = line; // only do this if the pc changed self.prev_di_line = line; self.prev_di_column = column; self.prev_di_pc = self.code.items.len; }, .none => {}, } } fn mirAddSubtractImmediate(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const rr_imm12_sh = emit.mir.instructions.items(.data)[inst].rr_imm12_sh; switch (tag) { .add_immediate => try emit.writeInstruction(Instruction.add( rr_imm12_sh.rd, rr_imm12_sh.rn, rr_imm12_sh.imm12, rr_imm12_sh.sh == 1, )), .sub_immediate => try emit.writeInstruction(Instruction.sub( rr_imm12_sh.rd, rr_imm12_sh.rn, rr_imm12_sh.imm12, rr_imm12_sh.sh == 1, )), else => unreachable, } } fn mirBranch(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const target_inst = emit.mir.instructions.items(.data)[inst].inst; _ = tag; _ = target_inst; switch (tag) { .b => return emit.fail("Implement mirBranch", .{}), .bl => return emit.fail("Implement mirBranch", .{}), else => unreachable, } } fn mirUnconditionalBranchRegister(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const reg = emit.mir.instructions.items(.data)[inst].reg; switch (tag) { .blr => try emit.writeInstruction(Instruction.blr(reg)), .ret => try emit.writeInstruction(Instruction.ret(reg)), else => unreachable, } } fn mirExceptionGeneration(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const imm16 = emit.mir.instructions.items(.data)[inst].imm16; switch (tag) { .brk => try emit.writeInstruction(Instruction.brk(imm16)), .svc => try emit.writeInstruction(Instruction.svc(imm16)), else => unreachable, } } fn mirDbgLine(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const dbg_line_column = emit.mir.instructions.items(.data)[inst].dbg_line_column; switch (tag) { .dbg_line => try emit.dbgAdvancePCAndLine(dbg_line_column.line, dbg_line_column.column), else => unreachable, } } fn mirDebugPrologueEnd(self: *Emit) !void { switch (self.debug_output) { .dwarf => |dbg_out| { try dbg_out.dbg_line.append(DW.LNS.set_prologue_end); try self.dbgAdvancePCAndLine(self.prev_di_line, self.prev_di_column); }, .plan9 => {}, .none => {}, } } fn mirDebugEpilogueBegin(self: *Emit) !void { switch (self.debug_output) { .dwarf => |dbg_out| { try dbg_out.dbg_line.append(DW.LNS.set_epilogue_begin); try self.dbgAdvancePCAndLine(self.prev_di_line, self.prev_di_column); }, .plan9 => {}, .none => {}, } } fn mirCallExtern(emit: *Emit, inst: Mir.Inst.Index) !void { assert(emit.mir.instructions.items(.tag)[inst] == .call_extern); const n_strx = emit.mir.instructions.items(.data)[inst].extern_fn; if (emit.bin_file.cast(link.File.MachO)) |macho_file| { const offset = blk: { const offset = @intCast(u32, emit.code.items.len); // bl try emit.writeInstruction(Instruction.bl(0)); break :blk offset; }; // Add relocation to the decl. try macho_file.active_decl.?.link.macho.relocs.append(emit.bin_file.allocator, .{ .offset = offset, .target = .{ .global = n_strx }, .addend = 0, .subtractor = null, .pcrel = true, .length = 2, .@"type" = @enumToInt(std.macho.reloc_type_arm64.ARM64_RELOC_BRANCH26), }); } else { return emit.fail("Implement call_extern for linking backends != MachO", .{}); } } fn mirLoadMemory(emit: *Emit, inst: Mir.Inst.Index) !void { assert(emit.mir.instructions.items(.tag)[inst] == .load_memory); const payload = emit.mir.instructions.items(.data)[inst].payload; const load_memory = emit.mir.extraData(Mir.LoadMemory, payload).data; const reg = @intToEnum(Register, load_memory.register); const addr = load_memory.addr; if (emit.bin_file.options.pie) { // PC-relative displacement to the entry in the GOT table. // adrp const offset = @intCast(u32, emit.code.items.len); try emit.writeInstruction(Instruction.adrp(reg, 0)); // ldr reg, reg, offset try emit.writeInstruction(Instruction.ldr(reg, .{ .register = .{ .rn = reg, .offset = Instruction.LoadStoreOffset.imm(0), }, })); if (emit.bin_file.cast(link.File.MachO)) |macho_file| { // TODO I think the reloc might be in the wrong place. const decl = macho_file.active_decl.?; // Page reloc for adrp instruction. try decl.link.macho.relocs.append(emit.bin_file.allocator, .{ .offset = offset, .target = .{ .local = addr }, .addend = 0, .subtractor = null, .pcrel = true, .length = 2, .@"type" = @enumToInt(std.macho.reloc_type_arm64.ARM64_RELOC_GOT_LOAD_PAGE21), }); // Pageoff reloc for adrp instruction. try decl.link.macho.relocs.append(emit.bin_file.allocator, .{ .offset = offset + 4, .target = .{ .local = addr }, .addend = 0, .subtractor = null, .pcrel = false, .length = 2, .@"type" = @enumToInt(std.macho.reloc_type_arm64.ARM64_RELOC_GOT_LOAD_PAGEOFF12), }); } else { return emit.fail("TODO implement load_memory for PIE GOT indirection on this platform", .{}); } } else { // The value is in memory at a hard-coded address. // If the type is a pointer, it means the pointer address is at this memory location. try emit.moveImmediate(reg, addr); try emit.writeInstruction(Instruction.ldr( reg, .{ .register = .{ .rn = reg, .offset = Instruction.LoadStoreOffset.none } }, )); } } fn mirLoadStoreRegisterPair(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const load_store_register_pair = emit.mir.instructions.items(.data)[inst].load_store_register_pair; switch (tag) { .stp => try emit.writeInstruction(Instruction.stp( load_store_register_pair.rt, load_store_register_pair.rt2, load_store_register_pair.rn, load_store_register_pair.offset, )), .ldp => try emit.writeInstruction(Instruction.ldp( load_store_register_pair.rt, load_store_register_pair.rt2, load_store_register_pair.rn, load_store_register_pair.offset, )), else => unreachable, } } fn mirLoadStoreRegister(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const load_store_register = emit.mir.instructions.items(.data)[inst].load_store_register; switch (tag) { .ldr => try emit.writeInstruction(Instruction.ldr( load_store_register.rt, .{ .register = .{ .rn = load_store_register.rn, .offset = load_store_register.offset } }, )), .ldrb => try emit.writeInstruction(Instruction.ldrb( load_store_register.rt, load_store_register.rn, .{ .offset = load_store_register.offset }, )), .ldrh => try emit.writeInstruction(Instruction.ldrh( load_store_register.rt, load_store_register.rn, .{ .offset = load_store_register.offset }, )), .str => try emit.writeInstruction(Instruction.str( load_store_register.rt, load_store_register.rn, .{ .offset = load_store_register.offset }, )), .strb => try emit.writeInstruction(Instruction.strb( load_store_register.rt, load_store_register.rn, .{ .offset = load_store_register.offset }, )), .strh => try emit.writeInstruction(Instruction.strh( load_store_register.rt, load_store_register.rn, .{ .offset = load_store_register.offset }, )), else => unreachable, } } fn mirMoveRegister(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const rr = emit.mir.instructions.items(.data)[inst].rr; switch (tag) { .mov_register => try emit.writeInstruction(Instruction.orr(rr.rd, .xzr, rr.rn, Instruction.Shift.none)), .mov_to_from_sp => try emit.writeInstruction(Instruction.add(rr.rd, rr.rn, 0, false)), else => unreachable, } } fn mirMoveWideImmediate(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const r_imm16_sh = emit.mir.instructions.items(.data)[inst].r_imm16_sh; switch (tag) { .movz => try emit.writeInstruction(Instruction.movz(r_imm16_sh.rd, r_imm16_sh.imm16, @as(u6, r_imm16_sh.hw) << 4)), .movk => try emit.writeInstruction(Instruction.movk(r_imm16_sh.rd, r_imm16_sh.imm16, @as(u6, r_imm16_sh.hw) << 4)), else => unreachable, } } fn mirNop(emit: *Emit) !void { try emit.writeInstruction(Instruction.nop()); }
src/arch/aarch64/Emit.zig
const c = @cImport({ @cInclude("epoxy/gl.h"); }); const gl = @import("zgl.zig"); pub const Boolean = c.GLboolean; pub const Byte = c.GLbyte; pub const UByte = c.GLubyte; pub const Char = c.GLchar; pub const Short = c.GLshort; pub const UShort = c.GLushort; pub const Int = c.GLint; pub const UInt = c.GLuint; pub const Fixed = c.GLfixed; pub const Int64 = c.GLint64; pub const UInt64 = c.GLuint64; pub const SizeI = c.GLsizei; pub const Enum = c.GLenum; pub const IntPtr = c.GLintptr; pub const SizeIPtr = c.GLsizeiptr; pub const Sync = c.GLsync; pub const BitField = c.GLbitfield; pub const Half = c.GLhalf; pub const Float = c.GLfloat; pub const ClampF = c.GLclampf; pub const Double = c.GLdouble; pub const ClampD = c.GLclampd; pub const VertexArray = enum(UInt) { invalid = 0, _, pub const create = gl.createVertexArray; pub const delete = gl.deleteVertexArray; pub const gen = gl.genVertexArray; pub const bind = gl.bindVertexArray; pub const enableVertexAttribute = gl.enableVertexArrayAttrib; pub const disableVertexAttribute = gl.disableVertexArrayAttrib; pub const attribFormat = gl.vertexArrayAttribFormat; pub const attribIFormat = gl.vertexArrayAttribIFormat; pub const attribLFormat = gl.vertexArrayAttribLFormat; pub const attribBinding = gl.vertexArrayAttribBinding; pub const vertexBuffer = gl.vertexArrayVertexBuffer; pub const elementBuffer = gl.vertexArrayElementBuffer; }; pub const Buffer = enum(UInt) { invalid = 0, _, pub const create = gl.createBuffer; pub const gen = gl.genBuffer; pub const bind = gl.bindBuffer; pub const delete = gl.deleteBuffer; pub const data = gl.namedBufferData; pub const storage = gl.namedBufferStorage; pub const mapRange = gl.mapNamedBufferRange; pub const unmap = gl.unmapNamedBuffer; }; pub const Shader = enum(UInt) { invalid = 0, _, pub const create = gl.createShader; pub const delete = gl.deleteShader; pub const compile = gl.compileShader; pub const source = gl.shaderSource; pub const get = gl.getShader; pub const getCompileLog = gl.getShaderInfoLog; }; pub const Program = enum(UInt) { invalid = 0, _, pub const create = gl.createProgram; pub const delete = gl.deleteProgram; pub const attach = gl.attachShader; pub const detach = gl.detachShader; pub const link = gl.linkProgram; pub const use = gl.useProgram; pub const uniform1ui = gl.programUniform1ui; pub const uniform1i = gl.programUniform1i; pub const uniform3ui = gl.programUniform3ui; pub const uniform3i = gl.programUniform3i; pub const uniform2i = gl.programUniform2i; pub const uniform1f = gl.programUniform1f; pub const uniform2f = gl.programUniform2f; pub const uniform3f = gl.programUniform3f; pub const uniform4f = gl.programUniform4f; pub const uniformMatrix4 = gl.programUniformMatrix4; pub const get = gl.getProgram; pub const getCompileLog = gl.getProgramInfoLog; pub const uniformLocation = gl.getUniformLocation; }; pub const Texture = enum(UInt) { invalid = 0, _, pub const create = gl.createTexture; pub const delete = gl.deleteTexture; pub const bind = gl.bindTexture; pub const bindTo = gl.bindTextureUnit; pub const parameter = gl.textureParameter; pub const storage2D = gl.textureStorage2D; pub const storage3D = gl.textureStorage3D; pub const subImage2D = gl.textureSubImage2D; pub const subImage3D = gl.textureSubImage3D; };
types.zig
const std = @import("std"); const root = @import("main.zig"); const math = std.math; const expectEqual = std.testing.expectEqual; const expect = std.testing.expect; const panic = std.debug.panic; pub const Vec2 = GenericVector(2, f32); pub const Vec2_f64 = GenericVector(2, f64); pub const Vec2_i32 = GenericVector(2, i32); pub const Vec2_usize = GenericVector(2, usize); pub const Vec3 = GenericVector(3, f32); pub const Vec3_f64 = GenericVector(3, f64); pub const Vec3_i32 = GenericVector(3, i32); pub const Vec3_usize = GenericVector(3, usize); pub const Vec4 = GenericVector(4, f32); pub const Vec4_f64 = GenericVector(4, f64); pub const Vec4_i32 = GenericVector(4, i32); pub const Vec4_usize = GenericVector(4, usize); /// A generic vector. pub fn GenericVector(comptime dimensions: comptime_int, comptime T: type) type { if (@typeInfo(T) != .Float and @typeInfo(T) != .Int) { @compileError("Vectors not implemented for " ++ @typeName(T)); } if (dimensions < 2 or dimensions > 4) { @compileError("Dimensions must be 2, 3 or 4!"); } return extern struct { const Self = @This(); data: @Vector(dimensions, T), usingnamespace switch (dimensions) { 2 => extern struct { /// Construct new vector. pub fn new(vx: T, vy: T) Self { return .{ .data = [2]T{ vx, vy } }; } }, 3 => extern struct { /// Construct new vector. pub fn new(vx: T, vy: T, vz: T) Self { return .{ .data = [3]T{ vx, vy, vz } }; } pub fn z(self: Self) T { return self.data[2]; } /// Shorthand for (0, 0, 1). pub fn forward() Self { return new(0, 0, 1); } /// Shorthand for (0, 0, -1). pub fn back() Self { return forward().negate(); } /// Construct the cross product (as vector) from two vectors. pub fn cross(first_vector: Self, second_vector: Self) Self { const x1 = first_vector.x(); const y1 = first_vector.y(); const z1 = first_vector.z(); const x2 = second_vector.x(); const y2 = second_vector.y(); const z2 = second_vector.z(); const result_x = (y1 * z2) - (z1 * y2); const result_y = (z1 * x2) - (x1 * z2); const result_z = (x1 * y2) - (y1 * x2); return new(result_x, result_y, result_z); } }, 4 => extern struct { /// Construct new vector. pub fn new(vx: T, vy: T, vz: T, vw: T) Self { return .{ .data = [4]T{ vx, vy, vz, vw } }; } /// Shorthand for (0, 0, 1, 0). pub fn forward() Self { return new(0, 0, 1, 0); } /// Shorthand for (0, 0, -1, 0). pub fn back() Self { return forward().negate(); } pub fn z(self: Self) T { return self.data[2]; } pub fn w(self: Self) T { return self.data[3]; } }, else => unreachable, }; pub fn x(self: Self) T { return self.data[0]; } pub fn y(self: Self) T { return self.data[1]; } /// Set all components to the same given value. pub fn set(val: T) Self { const result = @splat(dimensions, val); return .{ .data = result }; } /// Shorthand for (0..). pub fn zero() Self { return set(0); } /// Shorthand for (1..). pub fn one() Self { return set(1); } /// Shorthand for (0, 1). pub fn up() Self { return switch (dimensions) { 2 => Self.new(0, 1), 3 => Self.new(0, 1, 0), 4 => Self.new(0, 1, 0, 0), else => unreachable, }; } /// Shorthand for (0, -1). pub fn down() Self { return up().negate(); } /// Shorthand for (1, 0). pub fn right() Self { return switch (dimensions) { 2 => Self.new(1, 0), 3 => Self.new(1, 0, 0), 4 => Self.new(1, 0, 0, 0), else => unreachable, }; } /// Shorthand for (-1, 0). pub fn left() Self { return right().negate(); } /// Negate the given vector. pub fn negate(self: Self) Self { return self.scale(-1); } /// Cast a type to another type. /// It's like builtins: @intCast, @floatCast, @intToFloat, @floatToInt. pub fn cast(self: Self, comptime dest_type: type) GenericVector(dimensions, dest_type) { const dest_info = @typeInfo(dest_type); if (dest_info != .Float and dest_info != .Int) { panic("Error, dest type should be integer or float.\n", .{}); } var result: [dimensions]dest_type = undefined; for (result) |_, i| { result[i] = math.lossyCast(dest_type, self.data[i]); } return .{ .data = result }; } /// Construct new vector from slice. pub fn fromSlice(slice: []const T) Self { const result = slice[0..dimensions].*; return .{ .data = result }; } /// Transform vector to array. pub fn toArray(self: Self) [dimensions]T { return self.data; } /// Return the angle (in degrees) between two vectors. pub fn getAngle(first_vector: Self, second_vector: Self) T { const dot_product = dot(norm(first_vector), norm(second_vector)); return root.toDegrees(math.acos(dot_product)); } /// Return the length (magnitude) of given vector. /// √[x^2 + y^2 + z^2 ...] pub fn length(self: Self) T { return @sqrt(self.dot(self)); } /// Return the distance between two points. /// √[(x1 - x2)^2 + (y1 - y2)^2 + (z1 - z2)^2 ...] pub fn distance(first_vector: Self, second_vector: Self) T { return length(first_vector.sub(second_vector)); } /// Construct new normalized vector from a given one. pub fn norm(self: Self) Self { const l = self.length(); if (l == 0) { return self; } const result = self.data / @splat(dimensions, l); return .{ .data = result }; } /// Return true if two vectors are equals. pub fn eql(first_vector: Self, second_vector: Self) bool { return @reduce(.And, first_vector.data == second_vector.data); } /// Substraction between two given vector. pub fn sub(first_vector: Self, second_vector: Self) Self { const result = first_vector.data - second_vector.data; return .{ .data = result }; } /// Addition betwen two given vector. pub fn add(first_vector: Self, second_vector: Self) Self { const result = first_vector.data + second_vector.data; return .{ .data = result }; } /// Component wise multiplication betwen two given vector. pub fn mul(first_vector: Self, second_vector: Self) Self { const result = first_vector.data * second_vector.data; return .{ .data = result }; } /// Construct vector from the max components in two vectors pub fn max(first_vector: Self, second_vector: Self) Self { const result = @maximum(first_vector.data, second_vector.data); return .{ .data = result }; } /// Construct vector from the min components in two vectors pub fn min(first_vector: Self, second_vector: Self) Self { const result = @minimum(first_vector.data, second_vector.data); return .{ .data = result }; } /// Construct new vector after multiplying each components by a given scalar pub fn scale(self: Self, scalar: T) Self { const result = self.data * @splat(dimensions, scalar); return .{ .data = result }; } /// Return the dot product between two given vector. /// (x1 * x2) + (y1 * y2) + (z1 * z2) ... pub fn dot(first_vector: Self, second_vector: Self) T { return @reduce(.Add, first_vector.data * second_vector.data); } /// Linear interpolation between two vectors pub fn lerp(first_vector: Self, second_vector: Self, t: T) Self { const from = first_vector.data; const to = second_vector.data; const result = from + (to - from) * @splat(dimensions, t); return .{ .data = result }; } }; } test "zalgebra.Vectors.eql" { // Vec2 { const a = Vec2.new(1, 2); const b = Vec2.new(1, 2); const c = Vec2.new(1.5, 2); try expectEqual(Vec2.eql(a, b), true); try expectEqual(Vec2.eql(a, c), false); } // Vec3 { const a = Vec3.new(1, 2, 3); const b = Vec3.new(1, 2, 3); const c = Vec3.new(1.5, 2, 3); try expectEqual(Vec3.eql(a, b), true); try expectEqual(Vec3.eql(a, c), false); } // Vec4 { const a = Vec4.new(1, 2, 3, 4); const b = Vec4.new(1, 2, 3, 4); const c = Vec4.new(1.5, 2, 3, 4); try expectEqual(Vec4.eql(a, b), true); try expectEqual(Vec4.eql(a, c), false); } } test "zalgebra.Vectors.set" { // Vec2 { const a = Vec2.new(2.5, 2.5); const b = Vec2.set(2.5); try expectEqual(a, b); } // Vec3 { const a = Vec3.new(2.5, 2.5, 2.5); const b = Vec3.set(2.5); try expectEqual(a, b); } // Vec4 { const a = Vec4.new(2.5, 2.5, 2.5, 2.5); const b = Vec4.set(2.5); try expectEqual(a, b); } } test "zalgebra.Vectors.add" { // Vec2 { const a = Vec2.one(); const b = Vec2.one(); try expectEqual(a.add(b), Vec2.set(2)); } // Vec3 { const a = Vec3.one(); const b = Vec3.one(); try expectEqual(a.add(b), Vec3.set(2)); } // Vec4 { const a = Vec4.one(); const b = Vec4.one(); try expectEqual(a.add(b), Vec4.set(2)); } } test "zalgebra.Vectors.negate" { // Vec2 { const a = Vec2.set(5); const a_negated = Vec2.set(-5); try expectEqual(a.negate(), a_negated); } // Vec3 { const a = Vec3.set(5); const a_negated = Vec3.set(-5); try expectEqual(a.negate(), a_negated); } // Vec4 { const a = Vec4.set(5); const a_negated = Vec4.set(-5); try expectEqual(a.negate(), a_negated); } } test "zalgebra.Vectors.getAngle" { // Vec2 { const a = Vec2.right(); const b = Vec2.up(); const c = Vec2.left(); const d = Vec2.one(); try expectEqual(a.getAngle(a), 0); try expectEqual(a.getAngle(b), 90); try expectEqual(a.getAngle(c), 180); try expectEqual(a.getAngle(d), 45); } // Vec3 { const a = Vec3.right(); const b = Vec3.up(); const c = Vec3.left(); const d = Vec3.new(1, 1, 0); try expectEqual(a.getAngle(a), 0); try expectEqual(a.getAngle(b), 90); try expectEqual(a.getAngle(c), 180); try expectEqual(a.getAngle(d), 45); } // Vec4 { const a = Vec4.right(); const b = Vec4.up(); const c = Vec4.left(); const d = Vec4.new(1, 1, 0, 0); try expectEqual(a.getAngle(a), 0); try expectEqual(a.getAngle(b), 90); try expectEqual(a.getAngle(c), 180); try expectEqual(a.getAngle(d), 45); } } test "zalgebra.Vectors.toArray" { //Vec2 { const a = Vec2.up().toArray(); const b = [_]f32{ 0, 1 }; try std.testing.expectEqualSlices(f32, &a, &b); } //Vec3 { const a = Vec3.up().toArray(); const b = [_]f32{ 0, 1, 0 }; try std.testing.expectEqualSlices(f32, &a, &b); } //Vec4 { const a = Vec4.up().toArray(); const b = [_]f32{ 0, 1, 0, 0 }; try std.testing.expectEqualSlices(f32, &a, &b); } } test "zalgebra.Vectors.length" { // Vec2 { const a = Vec2.new(1.5, 2.6); try expectEqual(a.length(), 3.00166606); } // Vec3 { const a = Vec3.new(1.5, 2.6, 3.7); try expectEqual(a.length(), 4.7644519); } // Vec4 { const a = Vec4.new(1.5, 2.6, 3.7, 4.7); try expectEqual(a.length(), 6.69253301); } } test "zalgebra.Vectors.distance" { // Vec2 { const a = Vec2.zero(); const b = Vec2.left(); const c = Vec2.new(0, 5); try expectEqual(a.distance(b), 1); try expectEqual(a.distance(c), 5); } // Vec3 { const a = Vec3.zero(); const b = Vec3.left(); const c = Vec3.new(0, 5, 0); try expectEqual(a.distance(b), 1); try expectEqual(a.distance(c), 5); } // Vec4 { const a = Vec4.zero(); const b = Vec4.left(); const c = Vec4.new(0, 5, 0, 0); try expectEqual(a.distance(b), 1); try expectEqual(a.distance(c), 5); } } test "zalgebra.Vectors.normalize" { // Vec2 { const a = Vec2.new(1.5, 2.6); const a_normalized = Vec2.new(0.499722480, 0.866185605); try expectEqual(a.norm(), a_normalized); } // Vec3 { const a = Vec3.new(1.5, 2.6, 3.7); const a_normalized = Vec3.new(0.314831584, 0.545708060, 0.776584625); try expectEqual(a.norm(), a_normalized); } // Vec4 { const a = Vec4.new(1.5, 2.6, 3.7, 4.0); const a_normalized = Vec4.new(0.241121411, 0.417943745, 0.594766139, 0.642990410); try expectEqual(a.norm(), a_normalized); } } test "zalgebra.Vectors.scale" { // Vec2 { const a = Vec2.new(1, 2); const a_scaled = Vec2.new(5, 10); try expectEqual(a.scale(5), a_scaled); } // Vec3 { const a = Vec3.new(1, 2, 3); const a_scaled = Vec3.new(5, 10, 15); try expectEqual(a.scale(5), a_scaled); } // Vec4 { const a = Vec4.new(1, 2, 3, 4); const a_scaled = Vec4.new(5, 10, 15, 20); try expectEqual(a.scale(5), a_scaled); } } test "zalgebra.Vectors.dot" { // Vec2 { const a = Vec2.new(1.5, 2.6); const b = Vec2.new(2.5, 3.45); try expectEqual(a.dot(b), 12.7200002); } // Vec3 { const a = Vec3.new(1.5, 2.6, 3.7); const b = Vec3.new(2.5, 3.45, 1.0); try expectEqual(a.dot(b), 16.42); } // Vec4 { const a = Vec4.new(1.5, 2.6, 3.7, 5); const b = Vec4.new(2.5, 3.45, 1.0, 1); try expectEqual(a.dot(b), 21.4200000); } } test "zalgebra.Vectors.lerp" { // Vec2 { const a = Vec2.new(-10, 0); const b = Vec2.set(10); try expectEqual(Vec2.lerp(a, b, 0.5), Vec2.new(0, 5)); } // Vec3 { const a = Vec3.new(-10, 0, -10); const b = Vec3.set(10); try expectEqual(Vec3.lerp(a, b, 0.5), Vec3.new(0, 5, 0)); } // Vec4 { const a = Vec4.new(-10, 0, -10, -10); const b = Vec4.set(10); try expectEqual(Vec4.lerp(a, b, 0.5), Vec4.new(0, 5, 0, 0)); } } test "zalgebra.Vectors.min" { // Vec2 { const a = Vec2.new(10, -2); const b = Vec2.new(-10, 5); const minimum = Vec2.new(-10, -2); try expectEqual(Vec2.min(a, b), minimum); } // Vec3 { const a = Vec3.new(10, -2, 0); const b = Vec3.new(-10, 5, 0); const minimum = Vec3.new(-10, -2, 0); try expectEqual(Vec3.min(a, b), minimum); } // Vec4 { const a = Vec4.new(10, -2, 0, 1); const b = Vec4.new(-10, 5, 0, 1.01); const minimum = Vec4.new(-10, -2, 0, 1); try expectEqual(Vec4.min(a, b), minimum); } } test "zalgebra.Vectors.max" { // Vec2 { const a = Vec2.new(10, -2); const b = Vec2.new(-10, 5); const maximum = Vec2.new(10, 5); try expectEqual(Vec2.max(a, b), maximum); } // Vec3 { const a = Vec3.new(10, -2, 0); const b = Vec3.new(-10, 5, 0); const maximum = Vec3.new(10, 5, 0); try expectEqual(Vec3.max(a, b), maximum); } // Vec4 { const a = Vec4.new(10, -2, 0, 1); const b = Vec4.new(-10, 5, 0, 1.01); const maximum = Vec4.new(10, 5, 0, 1.01); try expectEqual(Vec4.max(a, b), maximum); } } test "zalgebra.Vectors.fromSlice" { // Vec2 { const slice = [_]f32{ 2, 4 }; try expectEqual(Vec2.fromSlice(&slice), Vec2.new(2, 4)); } // Vec3 { const slice = [_]f32{ 2, 4, 3 }; try expectEqual(Vec3.fromSlice(&slice), Vec3.new(2, 4, 3)); } // Vec4 { const slice = [_]f32{ 2, 4, 3, 6 }; try expectEqual(Vec4.fromSlice(&slice), Vec4.new(2, 4, 3, 6)); } } test "zalgebra.Vectors.cast" { // Vec2 { const a = Vec2_i32.new(3, 6); const a_usize = Vec2_usize.new(3, 6); try expectEqual(a.cast(usize), a_usize); const b = Vec2.new(3.5, 6.5); const b_f64 = Vec2_f64.new(3.5, 6.5); try expectEqual(b.cast(f64), b_f64); const c = Vec2_i32.new(3, 6); const c_f32 = Vec2.new(3, 6); try expectEqual(c.cast(f32), c_f32); const d = Vec2.new(3, 6); const d_i32 = Vec2_i32.new(3, 6); try expectEqual(d.cast(i32), d_i32); } // Vec3 { const a = Vec3_i32.new(3, 6, 2); const a_usize = Vec3_usize.new(3, 6, 2); try expectEqual(a.cast(usize), a_usize); const b = Vec3.new(3.5, 6.5, 2); const b_f64 = Vec3_f64.new(3.5, 6.5, 2); try expectEqual(b.cast(f64), b_f64); const c = Vec3_i32.new(3, 6, 2); const c_f32 = Vec3.new(3, 6, 2); try expectEqual(c.cast(f32), c_f32); const d = Vec3.new(3, 6, 2); const d_i32 = Vec3_i32.new(3, 6, 2); try expectEqual(d.cast(i32), d_i32); } // Vec4 { const a = Vec4_i32.new(3, 6, 2, 0); const a_usize = Vec4_usize.new(3, 6, 2, 0); try expectEqual(a.cast(usize), a_usize); const b = Vec4.new(3.5, 6.5, 2, 0); const b_f64 = Vec4_f64.new(3.5, 6.5, 2, 0); try expectEqual(b.cast(f64), b_f64); const c = Vec4_i32.new(3, 6, 2, 0); const c_f32 = Vec4.new(3, 6, 2, 0); try expectEqual(c.cast(f32), c_f32); const d = Vec4.new(3, 6, 2, 0); const d_i32 = Vec4_i32.new(3, 6, 2, 0); try expectEqual(d.cast(i32), d_i32); } } test "zalgebra.Vectors.cross" { // Only for Vec3 const a = Vec3.new(1.5, 2.6, 3.7); const b = Vec3.new(2.5, 3.45, 1.0); const c = Vec3.new(1.5, 2.6, 3.7); const result_1 = Vec3.cross(a, c); const result_2 = Vec3.cross(a, b); try expectEqual(result_1, Vec3.zero()); try expectEqual(result_2, Vec3.new(-10.1650009, 7.75, -1.32499980)); }
src/generic_vector.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const windows = std.os.windows; const WNDPROC = fn (windows.HWND, windows.UINT, windows.WPARAM, windows.LPARAM) callconv(windows.WINAPI) windows.LRESULT; extern "user32" fn MessageBoxW( hWnd: ?HWND, lpText: LPCWSTR, lpCaption: LPCWSTR, uType: UINT, ) callconv(WINAPI) c_int; extern "user32" fn AdjustWindowRectEx(lpRect: *RECT, dwStyle: windows.DWORD, bMenu: windows.BOOL, dwExStyle: windows.DWORD) callconv(windows.WINAPI) windows.BOOL; extern "user32" fn DefWindowProcW(windows.HWND, windows.UINT, windows.WPARAM, windows.LPARAM) callconv(windows.WINAPI) windows.LRESULT; extern "kernel32" fn OutputDebugStringW(lpOutputString: windows.LPCWSTR) callconv(windows.WINAPI) void; extern "user32" fn DestroyWindow(hWnd: windows.HWND) callconv(windows.WINAPI) windows.BOOL; extern "user32" fn GetClientRect(hWnd: windows.HWND, lpRect: *RECT) callconv(windows.WINAPI) windows.BOOL; extern "user32" fn ValidateRect(hWnd: HWND, lpRect: *const RECT) callconv(WINAPI) BOOL; extern "user32" fn BeginPaint(hWnd: HWND, lpPaint: *PAINTSTRUCT) callconv(WINAPI) HDC; extern "user32" fn EndPaint(hWnd: HWND, lpPaint: *PAINTSTRUCT) callconv(WINAPI) BOOL; extern "gdi32" fn StretchDIBits( hdc: HDC, xDest: c_int, yDest: c_int, DestWidth: c_int, DestHeight: c_int, xSrc: c_int, ySrc: c_int, SrcWidth: c_int, SrcHeight: c_int, lpBits: *const c_void, lpbmi: *const BITMAPINFO, iUsage: UINT, rop: DWORD, ) callconv(WINAPI) c_int; pub const Pixel = extern union { bits: u32, array: [4]u8, comp: struct { b: u8, g: u8, r: u8, a: u8, }, }; usingnamespace windows; const BITMAPINFOHEADER = extern struct { biSize: DWORD = @sizeOf(@This()), biWidth: LONG, biHeight: LONG, biPlanes: WORD = 1, biBitCount: WORD = 32, biCompression: DWORD = 0, biSizeImage: DWORD = 0, biXPelsPerMeter: LONG = 0, biYPelsPerMeter: LONG = 0, biClrUsed: DWORD = 0, biClrImportant: DWORD = 0, }; const RGBQUAD = extern struct { rgbBlue: BYTE, rgbGreen: BYTE, rgbRed: BYTE, rgbReserved: BYTE, }; const BITMAPINFO = extern struct { bmiHeader: BITMAPINFOHEADER, bmiColors: [1]RGBQUAD, }; extern "user32" fn GetMessageW( lpmsg: *MSG, hwnd: ?HWND, wMsgFilterMin: UINT, wMsgFilterMax: UINT, ) callconv(WINAPI) BOOL; const PAINTSTRUCT = extern struct { hdc: HDC, fErase: BOOL, rcPaint: RECT, fRestore: BOOL, fIncUpdate: BOOL, rgbReserved: [32]BYTE, }; extern "user32" fn DispatchMessageW(lpMsg: *const MSG) callconv(WINAPI) LRESULT; const WNDCLASSEXW = extern struct { cbSize: UINT = @sizeOf(@This()), style: UINT, lpfnWndProc: WNDPROC, cbClsExtra: c_int, cbWndExtra: c_int, hInstance: HINSTANCE, hIcon: ?HICON, hCursor: ?HCURSOR, hbrBackground: ?HBRUSH, lpszMenuName: ?LPCWSTR, lpszClassName: LPCWSTR, hIconSm: ?HICON, }; const CW_USEDEFAULT = @bitCast(i32, @as(u32, 0x80000000)); extern "user32" fn PostMessageW( hWnd: HWND, Msg: UINT, wParam: WPARAM, lParam: LPARAM, ) callconv(WINAPI) BOOL; const MSG = user32.MSG; const CS_OWNDC = 0x0020; extern "user32" fn RegisterClassExW(arg1: *const WNDCLASSEXW) callconv(WINAPI) ATOM; extern "user32" fn UnregisterClassW(lpClassName: LPCWSTR, hInstance: HINSTANCE) callconv(WINAPI) BOOL; extern "user32" fn CreateWindowExW( dwExStyle: DWORD, lpClassName: LPCWSTR, lpWindowName: LPCWSTR, dwStyle: DWORD, X: i32, Y: i32, nWidth: i32, nHeight: i32, hWindParent: ?HWND, hMenu: ?HMENU, hInstance: HINSTANCE, lpParam: ?LPVOID, ) callconv(WINAPI) ?HWND; extern "user32" fn SetWindowLongPtrW(hWnd: HWND, nIndex: c_int, dwNewLong: LONG_PTR) callconv(WINAPI) LONG_PTR; extern "user32" fn GetWindowLongPtrW(hWnd: HWND, nIndex: c_int) callconv(WINAPI) LONG_PTR; const WS_OVERLAPPED = 0; const WS_CAPTION = 0x00C00000; const WS_SYSMENU = 0x00080000; const WS_THICKFRAME = 0x00040000; const WS_VISIBLE = 0x10000000; const WindowCreatePipe = struct { out_win: ?*Instance.Window = null, in_name: []const u8, in_width: i32, in_height: i32, in_x: ?i32, in_y: ?i32, in_flags: WindowCreateFlags, reset_event: std.Thread.ResetEvent, }; const WindowCreateFlags = struct { resizable: bool, }; pub const Bitmap = struct { pixels: []Pixel, width: usize, height: usize, stride: usize, pixel_rows: usize, x_offset: usize, y_offset: usize, direction: Direction, const Direction = enum { TopDown, BottomUp }; pub fn create(allocator: *Allocator, width: usize, height: usize, direction: Direction) !@This() { const pixels = try allocator.alloc(Pixel, width * height); return @This(){ .pixels = pixels, .width = width, .height = height, .pixel_rows = height, .stride = width, .direction = direction, .x_offset = 0, .y_offset = 0, }; } pub fn subBitmap(this: *@This(), x: usize, y: usize, width: usize, height: usize) @This() { var bmp = this.*; bmp.x_offset += x; bmp.y_offset += y; bmp.width = width; bmp.height = height; return bmp; } const Row = struct { row: usize, pixels: []Pixel }; pub fn getPixel(this: *@This(), x: usize, y: usize) *Pixel { return &this.pixels[x + this.x_offset + (y + this.y_offset) * this.stride]; } const RowIterator = struct { current: usize = 0, pixels: []Pixel, height: usize, width: usize, stride: usize, pixel_rows: usize, x_offset: usize, y_offset: usize, pub fn next(self: *@This()) ?Row { if (self.current == self.height) { return null; } else { const whole_bitmap_row_start_index = (self.current + self.y_offset) * self.stride; const sub_bitmap_row_start_index = whole_bitmap_row_start_index + self.x_offset; const sub_bitmap_row_end_index = sub_bitmap_row_start_index + self.width; const row = .{ .row = self.current, .pixels = self.pixels[sub_bitmap_row_start_index..sub_bitmap_row_end_index], }; self.current += 1; return row; } } }; pub fn rowIterator(self: *@This()) RowIterator { return .{ .pixels = self.pixels, .height = self.height, .stride = self.stride, .pixel_rows = self.pixel_rows, .width = self.width, .x_offset = self.x_offset, .y_offset = self.y_offset, }; } pub fn release(self: *@This(), allocator: *Allocator) void { allocator.free(self.pixels); self.* = undefined; } }; fn windowProc(win: HWND, msg: UINT, wparam: WPARAM, lparam: LPARAM) callconv(WINAPI) LRESULT { const fail_result = 1; return switch (msg) { user32.WM_CLOSE => { const window = @intToPtr(*Instance.Window, @bitCast(usize, GetWindowLongPtrW(win, 0))); window.addEvent(.{ .CloseRequest = {} }) catch return 1; return 0; }, user32.WM_CREATE => { const createstruct = @intToPtr(*CREATESTRUCTW, @bitCast(usize, lparam)); const wcs = @ptrCast(*WindowCreationInfo, @alignCast( @alignOf(WindowCreationInfo), createstruct.lpCreateParams, )); _ = SetWindowLongPtrW(win, 0, @bitCast(LONG_PTR, @ptrToInt(wcs.window))); var client_rect = @as(RECT, undefined); _ = GetClientRect(win, &client_rect); wcs.window.* = .{ .allocator = wcs.allocator, .hwnd = win, .event_queue = std.atomic.Queue(Instance.Window.Event).init(), ._size = .{ .width = @intCast(u32, client_rect.right - client_rect.left), .height = @intCast(u32, client_rect.bottom - client_rect.top), }, .hdc = user32.GetDC(win) orelse return fail_result, }; return 0; }, user32.WM_SIZE => { const window = @intToPtr(*Instance.Window, @bitCast(usize, GetWindowLongPtrW(win, 0))); const size = lparam; var client_rect = @as(RECT, undefined); _ = GetClientRect(win, &client_rect); const width = @intCast(u32, client_rect.right - client_rect.left); const height = @intCast(u32, client_rect.bottom - client_rect.top); const dim = window._size.get(); if (width != dim.width or height != dim.height) { window.addEvent(.{ .WindowResize = .{ .width = width, .height = height, .old_width = dim.width, .old_height = dim.height, }, }) catch return fail_result; window._size.set(width, height); } return 0; }, user32.WM_PAINT => { const window = @intToPtr(*Instance.Window, @bitCast(usize, GetWindowLongPtrW(win, 0))); var ps = @as(PAINTSTRUCT, undefined); _ = BeginPaint(win, &ps); _ = ValidateRect(win, &ps.rcPaint); window.addEvent(.{ .RedrawRequest = .{ .x = ps.rcPaint.left, .y = ps.rcPaint.top, .width = @intCast(u32, ps.rcPaint.right - ps.rcPaint.left), .height = @intCast(u32, ps.rcPaint.bottom - ps.rcPaint.top), }, }) catch unreachable; _ = EndPaint(win, &ps); return 0; }, else => DefWindowProcW(win, msg, wparam, lparam), }; } fn messageWindowProc(win: HWND, msg: UINT, wparam: WPARAM, lparam: LPARAM) callconv(WINAPI) LRESULT { return switch (msg) { else => DefWindowProcW(win, msg, wparam, lparam), }; } const MessageThreadInputInfo = struct { message_window_ready: *std.Thread.ResetEvent, message_window: *?HWND, allocator: *Allocator, instance_name: []const u8, }; const windows_private_message_start = 0x400; const message_loop_terminate = windows_private_message_start + 0; const message_loop_create_window = windows_private_message_start + 1; const message_loop_show_window = windows_private_message_start + 2; const CREATESTRUCTW = extern struct { lpCreateParams: LPVOID, hInstance: HINSTANCE, hMenu: HMENU, hwndParent: HWND, cy: c_int, cx: c_int, y: c_int, x: c_int, style: LONG, lpszName: LPCWSTR, lpszClass: LPCWSTR, dwExStyle: DWORD, }; const WindowCreationInfo = struct { allocator: *Allocator, window: *Instance.Window, }; fn messageLoop( allocator: *Allocator, message_wnd: HWND, reg_win_class_name: [:0]const u16, hinstance: HINSTANCE, ) !void { var message = @as(MSG, undefined); while (GetMessageW(&message, null, 0, 0) > 0) { switch (message.message) { message_loop_terminate => return, // WE DONE message_loop_show_window => { _ = user32.ShowWindow(message.hWnd.?, @bitCast(i32, @intCast(u32, message.wParam))); }, message_loop_create_window => { // Unwrap the pipe we got sent in the lparam of the message const window_create_pipe = @intToPtr(*WindowCreatePipe, @bitCast(usize, message.lParam)); defer window_create_pipe.reset_event.set(); const name = std.unicode.utf8ToUtf16LeWithNull(allocator, window_create_pipe.in_name) catch continue; defer allocator.free(name); const window = allocator.create(Instance.Window) catch continue; var window_rect = RECT{ .left = 0, .right = window_create_pipe.in_width, .top = 0, .bottom = window_create_pipe.in_height }; const base_style = @as(DWORD, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU); const window_style = base_style | (if (window_create_pipe.in_flags.resizable) @as(DWORD, WS_THICKFRAME) else 0); _ = AdjustWindowRectEx(&window_rect, window_style, 0, 0); var wcs = WindowCreationInfo{ .allocator = allocator, .window = window }; if (CreateWindowExW( 0, reg_win_class_name, name, window_style, window_create_pipe.in_x orelse CW_USEDEFAULT, window_create_pipe.in_y orelse CW_USEDEFAULT, window_rect.right - window_rect.left, window_rect.bottom - window_rect.top, null, null, hinstance, &wcs, )) |_| { window_create_pipe.out_win = window; } }, else => { _ = user32.TranslateMessage(&message); _ = DispatchMessageW(&message); }, } } return error.EarlyExit; } fn messageThread(input_info: MessageThreadInputInfo) !void { const allocator = input_info.allocator; const canon_name = std.unicode.utf8ToUtf16LeWithNull(allocator, input_info.instance_name) catch |err| { input_info.message_window_ready.set(); return err; }; defer allocator.free(canon_name); const fake_name = std.mem.concat(allocator, u8, &[_][]const u8{ input_info.instance_name, "messagewindow" }) catch |err| { input_info.message_window_ready.set(); return err; }; defer allocator.free(fake_name); const message_windowclass_name = std.unicode.utf8ToUtf16LeWithNull(allocator, fake_name) catch |err| { input_info.message_window_ready.set(); return err; }; defer allocator.free(message_windowclass_name); const hinstance = @ptrCast(HINSTANCE, kernel32.GetModuleHandleW(null)); const wndclass = WNDCLASSEXW{ .style = CS_OWNDC, .lpfnWndProc = windowProc, .cbClsExtra = 0, .cbWndExtra = @sizeOf(*Instance.Window), .hInstance = hinstance, .hIcon = null, .hbrBackground = null, .hCursor = null, .lpszMenuName = null, .lpszClassName = canon_name, .hIconSm = null, }; const message_wndclass = WNDCLASSEXW{ .style = 0, .lpfnWndProc = messageWindowProc, .cbClsExtra = 0, .cbWndExtra = 0, .hInstance = hinstance, .hIcon = null, .hbrBackground = null, .hCursor = null, .lpszMenuName = null, .lpszClassName = message_windowclass_name, .hIconSm = null, }; if (RegisterClassExW(&wndclass) == 0) { input_info.message_window_ready.set(); std.log.err("{}", .{kernel32.GetLastError()}); return error.OsError; } defer _ = UnregisterClassW(wndclass.lpszClassName, wndclass.hInstance); if (RegisterClassExW(&message_wndclass) == 0) { input_info.message_window_ready.set(); std.log.err("{}", .{kernel32.GetLastError()}); return error.OsError; } defer _ = UnregisterClassW(message_wndclass.lpszClassName, wndclass.hInstance); const message_window_name = [_:0]u16{'a'}; if (CreateWindowExW( 0, message_windowclass_name, message_window_name[0..], 0, 0, 0, 0, 0, null, null, hinstance, null, )) |message_window| { _ = user32.ShowWindow(message_window, user32.SW_HIDE); _ = user32.ShowWindow(message_window, user32.SW_HIDE); defer _ = DestroyWindow(message_window); @atomicStore(?HWND, input_info.message_window, message_window, .SeqCst); input_info.message_window_ready.set(); try messageLoop(allocator, message_window, canon_name, hinstance); } else { input_info.message_window_ready.set(); return error.FailedToCreateInstance; } } pub const Instance = struct { instance_name: []u8, allocator: *std.mem.Allocator, message_thread: *std.Thread, message_window: HWND, pub fn init(allocator: *std.mem.Allocator, their_instance_name: []const u8) !@This() { // We don't want to take ownership but we need this const instance_name = try allocator.dupe(u8, their_instance_name); errdefer allocator.free(instance_name); var message_window_opt = @as(?HWND, null); var message_thread_ready: std.Thread.ResetEvent = @as(std.Thread.ResetEvent, undefined); try message_thread_ready.init(); defer message_thread_ready.deinit(); // Spawn a thread that will spin on the windows message queue // and make windows for us const message_thread = try std.Thread.spawn( MessageThreadInputInfo{ .message_window_ready = &message_thread_ready, .message_window = &message_window_opt, .instance_name = instance_name, .allocator = allocator, }, messageThread, ); errdefer message_thread.wait(); message_thread_ready.wait(); if (message_window_opt) |message_window| { return @This(){ .instance_name = instance_name, .allocator = allocator, .message_thread = message_thread, .message_window = message_window, }; } else { return error.InstanceCreationFailed; } } const Window = struct { allocator: *Allocator, hwnd: HWND, _size: _Size, hdc: HDC, // TODO: Verify the atomics in here. I'm pretty sure I'm right but I'm not 100% event_queue: EventQueue, waiter_queue: ?*Node = null, const Dim = struct { width: u32, height: u32 }; const _Size = struct { mutex: std.Thread.Mutex = .{}, width: u32, height: u32, fn get(self: *@This()) Dim { const lock = self.mutex.acquire(); defer lock.release(); return .{ .width = self.width, .height = self.height }; } fn set(self: *@This(), width: u32, height: u32) void { const lock = self.mutex.acquire(); defer lock.release(); self.width = width; self.height = height; } }; const Node = struct { reset_event: std.Thread.StaticResetEvent = .{}, next: ?*Node, }; const EventQueue = std.atomic.Queue(Event); pub fn close(self: *@This()) void { _ = DestroyWindow(self.hwnd); const allocator = self.allocator; allocator.destroy(self); } const Event = union(enum) { CloseRequest: void, RedrawRequest: struct { x: i32, y: i32, width: u32, height: u32 }, WindowResize: struct { width: u32, height: u32, old_width: u32, old_height: u32, } }; fn addEvent(self: *@This(), event: Event) !void { const node = try self.allocator.create(Instance.Window.EventQueue.Node); node.* = .{ .data = event }; self.event_queue.put(node); while (@atomicLoad(?*Node, &self.waiter_queue, .Monotonic)) |waiter_node| { if (@cmpxchgWeak(?*Node, &self.waiter_queue, waiter_node, waiter_node.next, .Monotonic, .Monotonic)) |_| {} else { waiter_node.reset_event.set(); return; } } } pub fn getSize(self: *@This()) Dim { return self._size.get(); } pub fn getEvent(self: *@This()) Event { if (self.pollEvent()) |event| { return event; } else { while (true) { var node = Node{ .next = @atomicLoad(?*Node, &self.waiter_queue, .Monotonic) }; if (self.pollEvent()) |event| { return event; } else { if (@cmpxchgWeak(?*Node, &self.waiter_queue, node.next, &node, .Monotonic, .Monotonic)) |_| {} else { node.reset_event.wait(); } } } } } pub fn pollEvent(self: *@This()) ?Event { if (self.event_queue.get()) |event| { defer self.allocator.destroy(event); _ = self.event_queue.remove(event); return event.data; } else { return null; } } pub fn show(self: *@This()) void { _ = PostMessageW(self.hwnd, message_loop_show_window, user32.SW_SHOW, 0); } pub fn hide(self: *@This()) void { _ = PostMessageW(self.hwnd, message_loop_show_window, user32.SW_HIDE, 0); } pub fn blit( self: *@This(), bitmap: Bitmap, dest_x: u32, dest_y: u32, ) error{BlitError}!void { const bitmapinfo = BITMAPINFOHEADER{ .biWidth = @intCast(i32, bitmap.stride), .biHeight = @intCast(i32, bitmap.height) * switch (bitmap.direction) { .TopDown => @as(i32, -1), .BottomUp => @as(i32, 1), }, }; // TODO: we don't actually want a stretch? What the fuck // else do we call if (StretchDIBits( self.hdc, @intCast(c_int, dest_x), @intCast(c_int, dest_y), @intCast(c_int, bitmap.width), @intCast(c_int, bitmap.height), @intCast(c_int, bitmap.x_offset), @intCast(c_int, bitmap.y_offset), @intCast(c_int, bitmap.width), @intCast(c_int, bitmap.height), bitmap.pixels.ptr, @ptrCast(*const BITMAPINFO, &bitmapinfo), 0, 0x00CC0020, ) == 0 and bitmap.height != 0) { return error.BlitError; } } }; pub fn createWindow( self: *@This(), title: []const u8, width: i32, height: i32, x: ?i32, y: ?i32, create_flags: WindowCreateFlags, ) !*Window { const allocator = self.allocator; var window_create_pipe = WindowCreatePipe{ .in_name = title, .in_width = width, .in_height = height, .in_x = x, .in_y = y, .in_flags = create_flags, .reset_event = @as(std.Thread.ResetEvent, undefined), }; try window_create_pipe.reset_event.init(); _ = PostMessageW(self.message_window, message_loop_create_window, 0, @bitCast(LPARAM, @ptrToInt(&window_create_pipe))); window_create_pipe.reset_event.wait(); if (window_create_pipe.out_win) |window| { return window; } else { return error.CouldNotCreateWindow; } } pub fn deinit(self: *@This()) void { _ = PostMessageW(self.message_window, message_loop_terminate, 0, 0); self.message_thread.wait(); self.allocator.free(self.instance_name); } }; const OutputDebugStringError = error{InvalidUtf8}; fn flushBuf(buf: []u16, buf_chars: usize) void { buf[buf_chars] = 0; const slice = buf[0..buf_chars :0]; OutputDebugStringW(slice.ptr); } fn outputDebugString(_: void, str: []const u8) OutputDebugStringError!usize { var buf: [4096]u16 = undefined; var buf_chars = @as(usize, 0); var view = try std.unicode.Utf8View.init(str); var iter = view.iterator(); while (iter.nextCodepoint()) |codepoint| { if (codepoint < 0x10000) { const short = @intCast(u16, codepoint); if (buf_chars + 2 == buf.len) { flushBuf(buf[0..], buf_chars); buf_chars = 0; } buf[buf_chars] = short; buf_chars += 1; } else { if (buf_chars + 3 == buf.len) { flushBuf(buf[0..], buf_chars); buf_chars = 0; } const high = @intCast(u16, (codepoint - 0x10000) >> 10) + 0xD800; const low = @intCast(u16, codepoint & 0x3FF) + 0xDC00; buf[buf_chars] = std.mem.nativeToLittle(u16, high); buf[buf_chars + 1] = std.mem.nativeToLittle(u16, low); buf_chars += 2; } } flushBuf(buf[0..], buf_chars); return str.len; } pub fn log( comptime message_level: std.log.Level, comptime scope: @Type(.EnumLiteral), comptime format: []const u8, args: anytype, ) void { const level_txt = switch (message_level) { .emerg => "emergency", .alert => "alert", .crit => "critical", .err => "error", .warn => "warning", .notice => "notice", .info => "info", .debug => "debug", }; const prefix2 = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): "; const held = std.debug.getStderrMutex().acquire(); defer held.release(); const use_windows_log = std.builtin.os.tag == .windows and std.builtin.subsystem != null and std.builtin.subsystem.? == .Windows; var writer = if (use_windows_log) std.io.Writer(void, OutputDebugStringError, outputDebugString){ .context = {} } else std.io.getStdErr().writer(); _ = writer.print(level_txt ++ prefix2 ++ format ++ "\n", args) catch {}; } const MB_ICONEXCLAMATION = 0x00000030; pub fn fatalErrorMessage(allocator: *Allocator, error_str: []const u8, title: []const u8) void { const error_str_u16 = std.unicode.utf8ToUtf16LeWithNull(allocator, error_str) catch |_| return; defer allocator.free(error_str_u16); const title_u16 = std.unicode.utf8ToUtf16LeWithNull(allocator, title) catch |_| return; defer allocator.free(title_u16); _ = MessageBoxW(null, error_str_u16, title_u16, MB_ICONEXCLAMATION); }
src/platform/windows.zig
const std = @import("std"); const debug = std.debug; const math = std.math; const mem = std.mem; const TypeId = @import("builtin").TypeId; pub fn main() void { debug.warn("state {}, rules {}\n", input_initial_state.len, input_rules.len); debug.warn("state {}, rules {}\n", test_initial_state.len, test_rules.len); } fn Generation(comptime T: type) type { return struct { const Self = @This(); gen_num: usize, first_plant: isize, last_plant: isize, pots: []const T, fn simNextGeneration(allocator: *std.mem.Allocator, current: Self, rules: u32) Self { var next_pots = std.ArrayList(T).init(allocator); defer next_pots.deinit(); comptime const pot_int_highest_bit = @truncate(math.Log2Int(T), @typeInfo(T).Int.bits - 1); comptime debug.assert(pot_int_highest_bit == @typeInfo(T).Int.bits - 1); var pot_context: u5 = 0; var next_pots_pot_int: T = 0; var next_pot_bit = pot_int_highest_bit; for (current.pots) |pot_int, i| { if (i == 0) { // Check the 3 leading pots // 00000 // ^ // assign corresponding bit from rules { const new_pot_state = @boolToInt((rules & (u32(1) << pot_context)) != 0); debug.warn("Rule result {b}\n", new_pot_state); next_pots_pot_int |= T(new_pot_state) << next_pot_bit; debug.warn("{x}\n", next_pots_pot_int); if (new_pot_state == 1) { next_pot_bit -= 1; } if (next_pot_bit == 0) { _ = next_pots.append(next_pots_pot_int); next_pots_pot_int = 0; next_pot_bit = pot_int_highest_bit; } } // 0000X // ^ { var shifted: u5 = 0; var overflowHappened = @shlWithOverflow(u5, pot_context, 1, &shifted); debug.warn("Overflow? {}\n", overflowHappened); pot_context = shifted; debug.warn("Shifted {b}\n", pot_context); const new_bit: u1 = @boolToInt((pot_int & (T(1) << pot_int_highest_bit)) != 0); pot_context |= new_bit; debug.warn("With new bit {b}\n", pot_context); // assign corresponding bit from rules const new_pot_state = @boolToInt((rules & (u32(1) << pot_context)) != 0); debug.warn("Rule result {b}\n", new_pot_state); next_pots_pot_int |= T(new_pot_state) << next_pot_bit; debug.warn("{x}\n", next_pots_pot_int); if (new_pot_state == 1) { next_pot_bit -= 1; } if (next_pot_bit == 0) { _ = next_pots.append(next_pots_pot_int); next_pots_pot_int = 0; next_pot_bit = pot_int_highest_bit; } } // 000XX // ^ { var shifted: u5 = 0; var overflowHappened = @shlWithOverflow(u5, pot_context, 1, &shifted); debug.warn("Overflow? {}\n", overflowHappened); pot_context = shifted; debug.warn("Shifted {b}\n", pot_context); const new_bit: u1 = @boolToInt((pot_int & (T(1) << pot_int_highest_bit - 1)) != 0); pot_context |= new_bit; debug.warn("With new bit {b}\n", pot_context); // assign corresponding bit from rules const new_pot_state = @boolToInt((rules & (u32(1) << pot_context)) != 0); debug.warn("Rule result {b}\n", new_pot_state); next_pots_pot_int |= T(new_pot_state) << next_pot_bit; debug.warn("{x}\n", next_pots_pot_int); if (new_pot_state == 1) { next_pot_bit -= 1; } if (next_pot_bit == 0) { _ = next_pots.append(next_pots_pot_int); next_pots_pot_int = 0; next_pot_bit = pot_int_highest_bit; } } } var pot_bit = pot_int_highest_bit - 2; while (pot_bit >= 0) : ({ pot_bit -= 1; next_pot_bit -= 1; }) { var shifted: u5 = 0; var overflowHappened = @shlWithOverflow(u5, pot_context, 1, &shifted); debug.warn("Overflow? {}\n", overflowHappened); pot_context = shifted; debug.warn("Shifted {b}\n", pot_context); const new_bit: u1 = @boolToInt((pot_int & (T(1) << pot_bit)) != 0); pot_context |= new_bit; debug.warn("With new bit {b}\n", pot_context); // assign corresponding bit from rules const new_pot_state = @boolToInt((rules & (u32(1) << pot_context)) != 0); debug.warn("Rule result {b}\n", new_pot_state); next_pots_pot_int |= T(new_pot_state) << next_pot_bit; debug.warn("{x}\n", next_pots_pot_int); if (next_pot_bit == 0) { _ = next_pots.append(next_pots_pot_int); next_pots_pot_int = 0; next_pot_bit = pot_int_highest_bit; } if (pot_bit == 0) { break; } } _ = next_pots.append(next_pots_pot_int); } // TODO: check the 3 following pots!! const result = Self { .gen_num = current.gen_num + 1, .first_plant = current.first_plant, .last_plant = current.last_plant, .pots = next_pots.toSlice(), }; return result; } }; } test "sim next gen" { const TestPotInt = u128; const TestGeneration = Generation(TestPotInt); var allocator = debug.global_allocator; const rules = rulesToInt(u32, test_rules); var g = TestGeneration { .gen_num = 0, .first_plant = 0, .last_plant = 24, .pots = potsToIntArray(TestPotInt, test_initial_state), }; var expected_first_plant: isize = undefined; var expected_last_plant: isize = undefined; var expected_pots: []const TestPotInt = potsToIntArray(TestPotInt, "........................."); while (g.gen_num <= 20) { debug.warn("{}\n", g.gen_num); // TODO: replace this with an array of expected `Generation`s switch (g.gen_num) { 0 => { expected_first_plant = 0; expected_last_plant = 24; expected_pots = potsToIntArray(TestPotInt, "#..#.#..##......###...###"); }, 1 => { expected_first_plant = 0; expected_last_plant = 24; // TODO: Why is the assertion on this passing!? expected_pots = potsToIntArray(TestPotInt, "#...#....#.....#..#..#..#"); }, 2 => { expected_first_plant = 0; expected_last_plant = 25; expected_pots = potsToIntArray(TestPotInt, "##..##...##....#..#..#..##"); }, 3 => { expected_first_plant = -1; expected_last_plant = 25; expected_pots = potsToIntArray(TestPotInt, "#.#...#..#.#....#..#..#...#"); }, 4 => { expected_first_plant = 0; expected_last_plant = 26; expected_pots = potsToIntArray(TestPotInt, "#.#..#...#.#...#..#..##..##"); }, 5 => { expected_first_plant = 1; expected_last_plant = 26; expected_pots = potsToIntArray(TestPotInt, "#...##...#.#..#..#...#...#"); }, 6 => { expected_first_plant = 1; expected_last_plant = 27; expected_pots = potsToIntArray(TestPotInt, "##.#.#....#...#..##..##..##"); }, 7 => { expected_first_plant = 0; expected_last_plant = 27; expected_pots = potsToIntArray(TestPotInt, "#..###.#...##..#...#...#...#"); }, 8 => { expected_first_plant = 0; expected_last_plant = 28; expected_pots = potsToIntArray(TestPotInt, "#....##.#.#.#..##..##..##..##"); }, 9 => { expected_first_plant = 0; expected_last_plant = 28; expected_pots = potsToIntArray(TestPotInt, "##..#..#####....#...#...#...#"); }, 10 => { expected_first_plant = -1; expected_last_plant = 29; expected_pots = potsToIntArray(TestPotInt, "#.#..#...#.##....##..##..##..##"); }, 11 => { expected_first_plant = 0; expected_last_plant = 29; expected_pots = potsToIntArray(TestPotInt, "#...##...#.#...#.#...#...#...#"); }, 12 => { expected_first_plant = 0; expected_last_plant = 30; expected_pots = potsToIntArray(TestPotInt, "##.#.#....#.#...#.#..##..##..##"); }, 13 => { expected_first_plant = -1; expected_last_plant = 30; expected_pots = potsToIntArray(TestPotInt, "#..###.#....#.#...#....#...#...#"); }, 14 => { expected_first_plant = -1; expected_last_plant = 31; expected_pots = potsToIntArray(TestPotInt, "#....##.#....#.#..##...##..##..##"); }, 15 => { expected_first_plant = -1; expected_last_plant = 31; expected_pots = potsToIntArray(TestPotInt, "##..#..#.#....#....#..#.#...#...#"); }, 16 => { expected_first_plant = -2; expected_last_plant = 32; expected_pots = potsToIntArray(TestPotInt, "#.#..#...#.#...##...#...#.#..##..##"); }, 17 => { expected_first_plant = -1; expected_last_plant = 32; expected_pots = potsToIntArray(TestPotInt, "#...##...#.#.#.#...##...#....#...#"); }, 18 => { expected_first_plant = -1; expected_last_plant = 33; expected_pots = potsToIntArray(TestPotInt, "##.#.#....#####.#.#.#...##...##..##"); }, 19 => { expected_first_plant = -2; expected_last_plant = 33; expected_pots = potsToIntArray(TestPotInt, "#..###.#..#.#.#######.#.#.#..#.#...#"); }, 20 => { expected_first_plant = -2; expected_last_plant = 34; expected_pots = potsToIntArray(TestPotInt, "#....##....#####...#######....#.#..##"); }, else => unreachable, } debug.warn("Gen {}\n", g.gen_num); debug.warn("{} == {}\n", expected_pots[0], g.pots[0]); //debug.assert(expected_first_plant == g.first_plant); //debug.assert(expected_last_plant == g.last_plant); debug.assert(g.pots.len == 1); debug.assert(expected_pots.len == 1); debug.assert(expected_pots[0] == g.pots[0]); debug.assert(mem.eql(TestPotInt, expected_pots, g.pots)); g = TestGeneration.simNextGeneration(allocator, g, rules); } } fn rulesToInt(comptime T: type, rules: []const []const u8) T { comptime { debug.assert(@typeId(T) == TypeId.Int); debug.assert(!@typeInfo(T).Int.is_signed); } debug.assert(rules.len <= @typeInfo(T).Int.bits); var num: T = 0; for (rules) |r| { var it = mem.split(r, " =>"); const pattern = potsToInt(u8, it.next().?); const result = it.next().?; debug.assert(it.next() == null); const bit_value = switch (result[0]) { '.' => T(0), '#' => T(1), else => unreachable, }; comptime const ShiftInt = math.Log2Int(T); num |= bit_value << @intCast(ShiftInt, pattern); } return num; } test "rules to int" { debug.assert(rulesToInt(u32, test_rules) == 0x7CA09D18); } fn potsToIntArray(comptime T: type, comptime pots: []const u8) []const T { comptime { debug.assert(!@typeInfo(T).Int.is_signed); } comptime const int_bits = @typeInfo(T).Int.bits; // round up to account for remainder pots comptime const result_array_len: usize = (pots.len + int_bits - 1) / int_bits; var result = []T{0} ** result_array_len; for (result) |*elem, i| { const pot_slice_index = i * int_bits; var pot_slice: []const u8 = undefined; if (i == result.len - 1) { // we need right-padding var padded_pots = "." ** int_bits; for (pots[pot_slice_index..]) |p, p_i| { padded_pots[p_i] = p; } pot_slice = padded_pots; } else { const next_slice_index = pot_slice_index + int_bits; pot_slice = pots[pot_slice_index..next_slice_index]; } elem.* = potsToInt(T, pot_slice); } return result; } test "pots to int array" { { const potArray = potsToIntArray(u8, test_initial_state); debug.assert(potArray.len == 4); debug.assert(potArray[0] == 0x94); // #..#.#.. debug.assert(potArray[1] == 0xC0); // ##...... debug.assert(potArray[2] == 0xE3); // ###...## debug.assert(potArray[3] == 0x80); // #....... } { const potArray = potsToIntArray(u32, test_initial_state); debug.assert(potArray.len == 1); debug.assert(potArray[0] == 0x94C0E380); } } fn potsToInt(comptime T: type, pots: []const u8) T { comptime { debug.assert(@typeId(T) == TypeId.Int); debug.assert(!@typeInfo(T).Int.is_signed); } comptime const int_bits = @typeInfo(T).Int.bits; debug.assert(pots.len <= int_bits); var num: T = 0; var i: u8 = 0; for (pots) |p| { if (p == '#') { comptime const ShiftInt = math.Log2Int(T); num |= T(1) << @intCast(ShiftInt, pots.len - 1 - i); } i += 1; } return num; } test "pots to int" { debug.assert(potsToInt(u8, ".....") == 0); debug.assert(potsToInt(u8, "....#") == 1); debug.assert(potsToInt(u8, "...##") == 3); debug.assert(potsToInt(u8, "..###") == 7); debug.assert(potsToInt(u8, ".####") == 15); debug.assert(potsToInt(u8, "#####") == 31); debug.assert(potsToInt(u8, "####.") == 30); debug.assert(potsToInt(u8, "###..") == 28); debug.assert(potsToInt(u8, "##...") == 24); debug.assert(potsToInt(u8, "#....") == 16); debug.assert(potsToInt(u8, "#") == 1); debug.assert(potsToInt(u5, "#####") == 31); debug.assert(potsToInt(u128, ".#.#.") == 10); debug.assert(potsToInt(u128, "#.#.#") == 21); debug.assert(potsToInt(u32, test_initial_state) == 0x12981C7); debug.assert(potsToInt(u128, input_initial_state) == 0xC9A1A56AFCD5E918842DC9C44); } const test_initial_state = "#..#.#..##......###...###"; const test_rules = []const []const u8 { "...## => #", "..#.. => #", ".#... => #", ".#.#. => #", ".#.## => #", ".##.. => #", ".#### => #", "#.#.# => #", "#.### => #", "##.#. => #", "##.## => #", "###.. => #", "###.# => #", "####. => #", }; const input_initial_state = "##..#..##.#....##.#..#.#.##.#.#.######..##.#.#.####.#..#...##...#....#....#.##.###..#..###...#...#.."; // Hey, look at that: // - there are exactly 32 rules // - the patterns, if interpreted as bits, correspond to u8 0 through 31 // - the results, by themselves, could fit in a single u32 // That's... interesting... const input_rules = []const []const u8 { "#..#. => .", ".#..# => #", "..#.# => .", "..... => .", ".#... => #", "#..## => #", "..##. => #", "#.##. => #", "#.#.# => .", "###.# => #", ".#### => .", "..### => .", ".###. => .", "#.#.. => #", "###.. => .", "##.#. => .", "##..# => .", "##.## => .", "#.### => .", "...## => #", "##... => #", "####. => .", ".#.## => .", "#...# => #", ".#.#. => #", "....# => .", ".##.. => .", "...#. => .", "..#.. => .", "#.... => .", ".##.# => #", "##### => #", };
2018/day_12.zig
const std = @import("std"); const fs = std.fs; // {{{ helpers fn read_from_file(allocator: std.mem.Allocator, filename: []const u8, nlines: u32) ![]u32 { var file = try fs.cwd().openFile(filename, .{ .read = true }); defer file.close(); var reader = std.io.bufferedReader(file.reader()); var in_stream = reader.reader(); var measurements = try allocator.alloc(u32, nlines); var buffer: [32]u8 = undefined; var i: u32 = 0; while (try in_stream.readUntilDelimiterOrEof(&buffer, '\n')) |line| { measurements[i] = try std.fmt.parseInt(u32, line, 10); i += 1; if (i >= nlines) { break; } } if (i < nlines) { std.debug.print("Read too few lines?", .{}); } return measurements; } // }}} // {{{ part one fn count_measurement_increases(measurements: []u32) u32 { var counter: u32 = 0; var i: u32 = 0; while (i < measurements.len - 1) { counter += @boolToInt(measurements[i] < measurements[i + 1]); i += 1; } return counter; } // }}} // {{{ part two fn count_measurement_windowed_increases(measurements: []u32, window: u32) u32 { var counter: u32 = 0; var i: u32 = 0; var previous_window: u32 = 0; var current_window: u32 = 0; // get first window while (i < window) { previous_window += measurements[i]; i += 1; } // go through the array and update the previous / current windows and check while (i < measurements.len) { current_window = (previous_window - measurements[i - window]) + measurements[i]; counter += @boolToInt(previous_window < current_window); previous_window = current_window; i += 1; } return counter; } // }}} pub fn main() void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var alloc = gpa.allocator(); defer _ = gpa.deinit(); var measurements = read_from_file(alloc, "input.txt", 2000) catch { std.debug.print("Couldn't read file.", .{}); return; }; defer alloc.free(measurements); std.debug.print("Your puzzle answer was {d} ({d}).\n", .{count_measurement_increases(measurements), 1477}); std.debug.print("Your puzzle answer was {d} ({d}).\n", .{count_measurement_windowed_increases(measurements, 3), 1523}); }
day1/main.zig
const std = @import("../std.zig"); const debug = std.debug; const mem = std.mem; const random = std.crypto.random; const testing = std.testing; const Endian = std.builtin.Endian; const Order = std.math.Order; /// Compares two arrays in constant time (for a given length) and returns whether they are equal. /// This function was designed to compare short cryptographic secrets (MACs, signatures). /// For all other applications, use mem.eql() instead. pub fn timingSafeEql(comptime T: type, a: T, b: T) bool { switch (@typeInfo(T)) { .Array => |info| { const C = info.child; if (@typeInfo(C) != .Int) { @compileError("Elements to be compared must be integers"); } var acc = @as(C, 0); for (a) |x, i| { acc |= x ^ b[i]; } const s = @typeInfo(C).Int.bits; const Cu = std.meta.Int(.unsigned, s); const Cext = std.meta.Int(.unsigned, s + 1); return @bitCast(bool, @truncate(u1, (@as(Cext, @bitCast(Cu, acc)) -% 1) >> s)); }, .Vector => |info| { const C = info.child; if (@typeInfo(C) != .Int) { @compileError("Elements to be compared must be integers"); } const acc = @reduce(.Or, a ^ b); const s = @typeInfo(C).Int.bits; const Cu = std.meta.Int(.unsigned, s); const Cext = std.meta.Int(.unsigned, s + 1); return @bitCast(bool, @truncate(u1, (@as(Cext, @bitCast(Cu, acc)) -% 1) >> s)); }, else => { @compileError("Only arrays and vectors can be compared"); }, } } /// Compare two integers serialized as arrays of the same size, in constant time. /// Returns .lt if a<b, .gt if a>b and .eq if a=b pub fn timingSafeCompare(comptime T: type, a: []const T, b: []const T, endian: Endian) Order { debug.assert(a.len == b.len); const bits = switch (@typeInfo(T)) { .Int => |cinfo| if (cinfo.signedness != .unsigned) @compileError("Elements to be compared must be unsigned") else cinfo.bits, else => @compileError("Elements to be compared must be integers"), }; const Cext = std.meta.Int(.unsigned, bits + 1); var gt: T = 0; var eq: T = 1; if (endian == .Little) { var i = a.len; while (i != 0) { i -= 1; const x1 = a[i]; const x2 = b[i]; gt |= @truncate(T, (@as(Cext, x2) -% @as(Cext, x1)) >> bits) & eq; eq &= @truncate(T, (@as(Cext, (x2 ^ x1)) -% 1) >> bits); } } else { for (a) |x1, i| { const x2 = b[i]; gt |= @truncate(T, (@as(Cext, x2) -% @as(Cext, x1)) >> bits) & eq; eq &= @truncate(T, (@as(Cext, (x2 ^ x1)) -% 1) >> bits); } } if (gt != 0) { return Order.gt; } else if (eq != 0) { return Order.eq; } return Order.lt; } /// Add two integers serialized as arrays of the same size, in constant time. /// The result is stored into `result`, and `true` is returned if an overflow occurred. pub fn timingSafeAdd(comptime T: type, a: []const T, b: []const T, result: []T, endian: Endian) bool { const len = a.len; debug.assert(len == b.len and len == result.len); var carry: u1 = 0; if (endian == .Little) { var i: usize = 0; while (i < len) : (i += 1) { const tmp = @boolToInt(@addWithOverflow(u8, a[i], b[i], &result[i])); carry = tmp | @boolToInt(@addWithOverflow(u8, result[i], carry, &result[i])); } } else { var i: usize = len; while (i != 0) { i -= 1; const tmp = @boolToInt(@addWithOverflow(u8, a[i], b[i], &result[i])); carry = tmp | @boolToInt(@addWithOverflow(u8, result[i], carry, &result[i])); } } return @bitCast(bool, carry); } /// Subtract two integers serialized as arrays of the same size, in constant time. /// The result is stored into `result`, and `true` is returned if an underflow occurred. pub fn timingSafeSub(comptime T: type, a: []const T, b: []const T, result: []T, endian: Endian) bool { const len = a.len; debug.assert(len == b.len and len == result.len); var borrow: u1 = 0; if (endian == .Little) { var i: usize = 0; while (i < len) : (i += 1) { const tmp = @boolToInt(@subWithOverflow(u8, a[i], b[i], &result[i])); borrow = tmp | @boolToInt(@subWithOverflow(u8, result[i], borrow, &result[i])); } } else { var i: usize = len; while (i != 0) { i -= 1; const tmp = @boolToInt(@subWithOverflow(u8, a[i], b[i], &result[i])); borrow = tmp | @boolToInt(@subWithOverflow(u8, result[i], borrow, &result[i])); } } return @bitCast(bool, borrow); } /// Sets a slice to zeroes. /// Prevents the store from being optimized out. pub fn secureZero(comptime T: type, s: []T) void { // NOTE: We do not use a volatile slice cast here since LLVM cannot // see that it can be replaced by a memset. const ptr = @ptrCast([*]volatile u8, s.ptr); const length = s.len * @sizeOf(T); @memset(ptr, 0, length); } test "crypto.utils.timingSafeEql" { var a: [100]u8 = undefined; var b: [100]u8 = undefined; random.bytes(a[0..]); random.bytes(b[0..]); try testing.expect(!timingSafeEql([100]u8, a, b)); mem.copy(u8, a[0..], b[0..]); try testing.expect(timingSafeEql([100]u8, a, b)); } test "crypto.utils.timingSafeEql (vectors)" { var a: [100]u8 = undefined; var b: [100]u8 = undefined; random.bytes(a[0..]); random.bytes(b[0..]); const v1: @Vector(100, u8) = a; const v2: @Vector(100, u8) = b; try testing.expect(!timingSafeEql(@Vector(100, u8), v1, v2)); const v3: @Vector(100, u8) = a; try testing.expect(timingSafeEql(@Vector(100, u8), v1, v3)); } test "crypto.utils.timingSafeCompare" { var a = [_]u8{10} ** 32; var b = [_]u8{10} ** 32; try testing.expectEqual(timingSafeCompare(u8, &a, &b, .Big), .eq); try testing.expectEqual(timingSafeCompare(u8, &a, &b, .Little), .eq); a[31] = 1; try testing.expectEqual(timingSafeCompare(u8, &a, &b, .Big), .lt); try testing.expectEqual(timingSafeCompare(u8, &a, &b, .Little), .lt); a[0] = 20; try testing.expectEqual(timingSafeCompare(u8, &a, &b, .Big), .gt); try testing.expectEqual(timingSafeCompare(u8, &a, &b, .Little), .lt); } test "crypto.utils.timingSafe{Add,Sub}" { const len = 32; var a: [len]u8 = undefined; var b: [len]u8 = undefined; var c: [len]u8 = undefined; const zero = [_]u8{0} ** len; var iterations: usize = 100; while (iterations != 0) : (iterations -= 1) { random.bytes(&a); random.bytes(&b); const endian = if (iterations % 2 == 0) Endian.Big else Endian.Little; _ = timingSafeSub(u8, &a, &b, &c, endian); // a-b _ = timingSafeAdd(u8, &c, &b, &c, endian); // (a-b)+b try testing.expectEqualSlices(u8, &c, &a); const borrow = timingSafeSub(u8, &c, &a, &c, endian); // ((a-b)+b)-a try testing.expectEqualSlices(u8, &c, &zero); try testing.expectEqual(borrow, false); } } test "crypto.utils.secureZero" { var a = [_]u8{0xfe} ** 8; var b = [_]u8{0xfe} ** 8; mem.set(u8, a[0..], 0); secureZero(u8, b[0..]); try testing.expectEqualSlices(u8, a[0..], b[0..]); }
lib/std/crypto/utils.zig
pub const wide_eastasian = [_][2]u21{ [2]u21{ 0x1100, 0x115f, }, // Hangul Choseong Kiyeok ..Hangul Choseong Filler [2]u21{ 0x231a, 0x231b, }, // Watch ..Hourglass [2]u21{ 0x2329, 0x232a, }, // Left-pointing Angle Brac..Right-pointing Angle Bra [2]u21{ 0x23e9, 0x23ec, }, // Black Right-pointing Dou..Black Down-pointing Doub [2]u21{ 0x23f0, 0x23f0, }, // Alarm Clock ..Alarm Clock [2]u21{ 0x23f3, 0x23f3, }, // Hourglass With Flowing S..Hourglass With Flowing S [2]u21{ 0x25fd, 0x25fe, }, // White Medium Small Squar..Black Medium Small Squar [2]u21{ 0x2614, 0x2615, }, // Umbrella With Rain Drops..Hot Beverage [2]u21{ 0x2648, 0x2653, }, // Aries ..Pisces [2]u21{ 0x267f, 0x267f, }, // Wheelchair Symbol ..Wheelchair Symbol [2]u21{ 0x2693, 0x2693, }, // Anchor ..Anchor [2]u21{ 0x26a1, 0x26a1, }, // High Voltage Sign ..High Voltage Sign [2]u21{ 0x26aa, 0x26ab, }, // Medium White Circle ..Medium Black Circle [2]u21{ 0x26bd, 0x26be, }, // Soccer Ball ..Baseball [2]u21{ 0x26c4, 0x26c5, }, // Snowman Without Snow ..Sun Behind Cloud [2]u21{ 0x26ce, 0x26ce, }, // Ophiuchus ..Ophiuchus [2]u21{ 0x26d4, 0x26d4, }, // No Entry ..No Entry [2]u21{ 0x26ea, 0x26ea, }, // Church ..Church [2]u21{ 0x26f2, 0x26f3, }, // Fountain ..Flag In Hole [2]u21{ 0x26f5, 0x26f5, }, // Sailboat ..Sailboat [2]u21{ 0x26fa, 0x26fa, }, // Tent ..Tent [2]u21{ 0x26fd, 0x26fd, }, // Fuel Pump ..Fuel Pump [2]u21{ 0x2705, 0x2705, }, // White Heavy Check Mark ..White Heavy Check Mark [2]u21{ 0x270a, 0x270b, }, // Raised Fist ..Raised Hand [2]u21{ 0x2728, 0x2728, }, // Sparkles ..Sparkles [2]u21{ 0x274c, 0x274c, }, // Cross Mark ..Cross Mark [2]u21{ 0x274e, 0x274e, }, // Negative Squared Cross M..Negative Squared Cross M [2]u21{ 0x2753, 0x2755, }, // Black Question Mark Orna..White Exclamation Mark O [2]u21{ 0x2757, 0x2757, }, // Heavy Exclamation Mark S..Heavy Exclamation Mark S [2]u21{ 0x2795, 0x2797, }, // Heavy Plus Sign ..Heavy Division Sign [2]u21{ 0x27b0, 0x27b0, }, // Curly Loop ..Curly Loop [2]u21{ 0x27bf, 0x27bf, }, // Double Curly Loop ..Double Curly Loop [2]u21{ 0x2b1b, 0x2b1c, }, // Black Large Square ..White Large Square [2]u21{ 0x2b50, 0x2b50, }, // White Medium Star ..White Medium Star [2]u21{ 0x2b55, 0x2b55, }, // Heavy Large Circle ..Heavy Large Circle [2]u21{ 0x2e80, 0x2e99, }, // Cjk Radical Repeat ..Cjk Radical Rap [2]u21{ 0x2e9b, 0x2ef3, }, // Cjk Radical Choke ..Cjk Radical C-simplified [2]u21{ 0x2f00, 0x2fd5, }, // Kangxi Radical One ..Kangxi Radical Flute [2]u21{ 0x2ff0, 0x2ffb, }, // Ideographic Description ..Ideographic Description [2]u21{ 0x3000, 0x303e, }, // Ideographic Space ..Ideographic Variation In [2]u21{ 0x3041, 0x3096, }, // Hiragana Letter Small A ..Hiragana Letter Small Ke [2]u21{ 0x3099, 0x30ff, }, // Combining Katakana-hirag..Katakana Digraph Koto [2]u21{ 0x3105, 0x312f, }, // Bopomofo Letter B ..Bopomofo Letter Nn [2]u21{ 0x3131, 0x318e, }, // Hangul Letter Kiyeok ..Hangul Letter Araeae [2]u21{ 0x3190, 0x31e3, }, // Ideographic Annotation L..Cjk Stroke Q [2]u21{ 0x31f0, 0x321e, }, // Katakana Letter Small Ku..Parenthesized Korean Cha [2]u21{ 0x3220, 0x3247, }, // Parenthesized Ideograph ..Circled Ideograph Koto [2]u21{ 0x3250, 0x4dbf, }, // Partnership Sign .. [2]u21{ 0x4e00, 0xa48c, }, // Cjk Unified Ideograph-4e..Yi Syllable Yyr [2]u21{ 0xa490, 0xa4c6, }, // Yi Radical Qot ..Yi Radical Ke [2]u21{ 0xa960, 0xa97c, }, // Hangul Choseong Tikeut-m..Hangul Choseong Ssangyeo [2]u21{ 0xac00, 0xd7a3, }, // Hangul Syllable Ga ..Hangul Syllable Hih [2]u21{ 0xf900, 0xfaff, }, // Cjk Compatibility Ideogr.. [2]u21{ 0xfe10, 0xfe19, }, // Presentation Form For Ve..Presentation Form For Ve [2]u21{ 0xfe30, 0xfe52, }, // Presentation Form For Ve..Small Full Stop [2]u21{ 0xfe54, 0xfe66, }, // Small Semicolon ..Small Equals Sign [2]u21{ 0xfe68, 0xfe6b, }, // Small Reverse Solidus ..Small Commercial At [2]u21{ 0xff01, 0xff60, }, // Fullwidth Exclamation Ma..Fullwidth Right White Pa [2]u21{ 0xffe0, 0xffe6, }, // Fullwidth Cent Sign ..Fullwidth Won Sign [2]u21{ 0x16fe0, 0x16fe4, }, // Tangut Iteration Mark .. [2]u21{ 0x16ff0, 0x16ff1, }, // [2]u21{ nil } .. [2]u21{ 0x17000, 0x187f7, }, // [2]u21{ nil } .. [2]u21{ 0x18800, 0x18cd5, }, // Tangut Component-001 .. [2]u21{ 0x18d00, 0x18d08, }, // [2]u21{ nil } .. [2]u21{ 0x1b000, 0x1b11e, }, // Katakana Letter Archaic ..Hentaigana Letter N-mu-m [2]u21{ 0x1b150, 0x1b152, }, // [2]u21{ nil } .. [2]u21{ 0x1b164, 0x1b167, }, // [2]u21{ nil } .. [2]u21{ 0x1b170, 0x1b2fb, }, // Nushu Character-1b170 ..Nushu Character-1b2fb [2]u21{ 0x1f004, 0x1f004, }, // Mahjong Tile Red Dragon ..Mahjong Tile Red Dragon [2]u21{ 0x1f0cf, 0x1f0cf, }, // Playing Card Black Joker..Playing Card Black Joker [2]u21{ 0x1f18e, 0x1f18e, }, // Negative Squared Ab ..Negative Squared Ab [2]u21{ 0x1f191, 0x1f19a, }, // Squared Cl ..Squared Vs [2]u21{ 0x1f200, 0x1f202, }, // Square Hiragana Hoka ..Squared Katakana Sa [2]u21{ 0x1f210, 0x1f23b, }, // Squared Cjk Unified Ideo..Squared Cjk Unified Ideo [2]u21{ 0x1f240, 0x1f248, }, // Tortoise Shell Bracketed..Tortoise Shell Bracketed [2]u21{ 0x1f250, 0x1f251, }, // Circled Ideograph Advant..Circled Ideograph Accept [2]u21{ 0x1f260, 0x1f265, }, // Rounded Symbol For Fu ..Rounded Symbol For Cai [2]u21{ 0x1f300, 0x1f320, }, // Cyclone ..Shooting Star [2]u21{ 0x1f32d, 0x1f335, }, // Hot Dog ..Cactus [2]u21{ 0x1f337, 0x1f37c, }, // Tulip ..Baby Bottle [2]u21{ 0x1f37e, 0x1f393, }, // Bottle With Popping Cork..Graduation Cap [2]u21{ 0x1f3a0, 0x1f3ca, }, // Carousel Horse ..Swimmer [2]u21{ 0x1f3cf, 0x1f3d3, }, // Cricket Bat And Ball ..Table Tennis Paddle And [2]u21{ 0x1f3e0, 0x1f3f0, }, // House Building ..European Castle [2]u21{ 0x1f3f4, 0x1f3f4, }, // Waving Black Flag ..Waving Black Flag [2]u21{ 0x1f3f8, 0x1f43e, }, // Badminton Racquet And Sh..Paw Prints [2]u21{ 0x1f440, 0x1f440, }, // Eyes ..Eyes [2]u21{ 0x1f442, 0x1f4fc, }, // Ear ..Videocassette [2]u21{ 0x1f4ff, 0x1f53d, }, // Prayer Beads ..Down-pointing Small Red [2]u21{ 0x1f54b, 0x1f54e, }, // Kaaba ..Menorah With Nine Branch [2]u21{ 0x1f550, 0x1f567, }, // Clock Face One Oclock ..Clock Face Twelve-thirty [2]u21{ 0x1f57a, 0x1f57a, }, // Man Dancing ..Man Dancing [2]u21{ 0x1f595, 0x1f596, }, // Reversed Hand With Middl..Raised Hand With Part Be [2]u21{ 0x1f5a4, 0x1f5a4, }, // Black Heart ..Black Heart [2]u21{ 0x1f5fb, 0x1f64f, }, // Mount Fuji ..Person With Folded Hands [2]u21{ 0x1f680, 0x1f6c5, }, // Rocket ..Left Luggage [2]u21{ 0x1f6cc, 0x1f6cc, }, // Sleeping Accommodation ..Sleeping Accommodation [2]u21{ 0x1f6d0, 0x1f6d2, }, // Place Of Worship ..Shopping Trolley [2]u21{ 0x1f6d5, 0x1f6d7, }, // [2]u21{ nil } .. [2]u21{ 0x1f6eb, 0x1f6ec, }, // Airplane Departure ..Airplane Arriving [2]u21{ 0x1f6f4, 0x1f6fc, }, // Scooter .. [2]u21{ 0x1f7e0, 0x1f7eb, }, // [2]u21{ nil } .. [2]u21{ 0x1f90c, 0x1f93a, }, // [2]u21{ nil } ..Fencer [2]u21{ 0x1f93c, 0x1f945, }, // Wrestlers ..Goal Net [2]u21{ 0x1f947, 0x1f978, }, // First Place Medal .. [2]u21{ 0x1f97a, 0x1f9cb, }, // Face With Pleading Eyes .. [2]u21{ 0x1f9cd, 0x1f9ff, }, // [2]u21{ nil } ..Nazar Amulet [2]u21{ 0x1fa70, 0x1fa74, }, // [2]u21{ nil } .. [2]u21{ 0x1fa78, 0x1fa7a, }, // [2]u21{ nil } .. [2]u21{ 0x1fa80, 0x1fa86, }, // [2]u21{ nil } .. [2]u21{ 0x1fa90, 0x1faa8, }, // [2]u21{ nil } .. [2]u21{ 0x1fab0, 0x1fab6, }, // [2]u21{ nil } .. [2]u21{ 0x1fac0, 0x1fac2, }, // [2]u21{ nil } .. [2]u21{ 0x1fad0, 0x1fad6, }, // [2]u21{ nil } .. [2]u21{ 0x20000, 0x2fffd, }, // Cjk Unified Ideograph-20.. [2]u21{ 0x30000, 0x3fffd, }, // [2]u21{ nil } .. };
src/table_wide.zig
const std = @import("std"); const ParseIntError = std.fmt.ParseIntError; const Vec = struct { x: isize, y: isize }; const Dir = struct { c: u8, a: isize }; const dirs = [4]Dir{ Dir{ .c = 'N', .a = 0 }, Dir{ .c = 'E', .a = 90 }, Dir{ .c = 'S', .a = 180 }, Dir{ .c = 'W', .a = 270 }, }; fn turn(dir: *Dir, angle: isize) void { const i = @divExact(@mod(dir.a + angle, 360), 90); dir.* = dirs[@intCast(usize, i)]; } fn advance(dir: u8, v: *Vec, n: isize) void { switch (dir) { 'N' => { v.y += n; }, 'S' => { v.y -= n; }, 'E' => { v.x += n; }, 'W' => { v.x -= n; }, else => {}, } } fn parse(line: []u8, v: *Vec, dir: *Dir) !void { const n = try std.fmt.parseInt(isize, line[1..], 10); switch (line[0]) { 'N', 'E', 'S', 'W' => { advance(line[0], v, n); }, 'L' => { turn(dir, -n); }, 'R' => { turn(dir, n); }, 'F' => { advance(dir.c, v, n); }, else => {}, } } const unit = [4]isize{ 1, 0, -1, 0 }; fn cos(angle: isize) isize { return unit[@intCast(usize, @divExact(angle, 90))]; } fn sin(angle: isize) isize { return unit[@intCast(usize, @divExact(@mod(angle - 90, 360), 90))]; } fn rotate(v: *Vec, a: isize, s: isize) void { const x = v.x * cos(a) + s * v.y * sin(a); const y = v.y * cos(a) - s * v.x * sin(a); v.x = x; v.y = y; } fn parseWaypoint(line: []u8, v: *Vec, w: *Vec) !void { const n = try std.fmt.parseInt(isize, line[1..], 10); switch (line[0]) { 'N', 'E', 'S', 'W' => { advance(line[0], w, n); }, 'L' => { rotate(w, n, -1); }, 'R' => { rotate(w, n, 1); }, 'F' => { v.x += n * w.x; v.y += n * w.y; }, else => {}, } } fn abs(x: isize) isize { return if (x < 0) -x else x; } pub fn main() anyerror!void { var a = Vec{ .x = 0, .y = 0 }; var dir = Dir{ .c = 'E', .a = 90 }; var b = Vec{ .x = 0, .y = 0 }; var w = Vec{ .x = 10, .y = 1 }; // Read and parse puzzle input from stdin var stdin = std.io.getStdIn().reader(); var in = std.io.bufferedReader(stdin).reader(); var buf: [256]u8 = undefined; while (try in.readUntilDelimiterOrEof(&buf, '\n')) |line| { try parse(line, &a, &dir); try parseWaypoint(line, &b, &w); } std.debug.print("A) {d} + {d} = {d}\n", .{ abs(a.x), abs(a.y), abs(a.x) + abs(a.y), }); std.debug.print("B) {d} + {d} = {d}\n", .{ abs(b.x), abs(b.y), abs(b.x) + abs(b.y), }); }
2020/zig/src/12.zig
const Request = @This(); const std = @import("std"); const uri = @import("uri.zig"); /// Parsed URL from the client's request. uri: uri.Uri, /// Parses a request, validates it and then returns a `Request` instance pub fn parse(reader: anytype, buffer: []u8) Parser(@TypeOf(reader)).Error!Request { var parser = Parser(@TypeOf(reader)).init(reader, buffer); return parser.parseAndValidate(); } /// All error cases which can be hit when validating /// a Gemini request. pub const ParseError = error{ /// Request is invalid, the first line does not end with \r\n. MissingCRLF, /// Request is missing mandatory URI. MissingUri, /// The URI has a maximum length of 1024 bytes, including its scheme. UriTooLong, /// When the provided buffer is smaller than 1026 bytes. BufferTooSmall, /// Connection was closed by the client. EndOfStream, } || uri.ParseError; /// Constructs a generic `Parser` for a given `ReaderType`. fn Parser(comptime ReaderType: type) type { return struct { const Self = @This(); reader: ReaderType, buffer: []u8, index: usize, const Error = ReaderType.Error || ParseError; /// Initializes a new `Parser` with a reader of type `ReaderType` fn init(reader: ReaderType, buffer: []u8) Self { return .{ .reader = reader, .buffer = buffer, .index = 0 }; } /// Parses the request and validates it fn parseAndValidate(self: *Self) Error!Request { if (self.buffer.len < 1026) return error.BufferTooSmall; const read = try self.reader.read(self.buffer); if (read == 0) return error.EndOfStream; if (read == 2) return error.MissingUri; // URI's have a maximum length of 1024 bytes including its scheme if (read > 1026) { return error.UriTooLong; } // verify CRLF if (!std.mem.eql(u8, self.buffer[read - 2 .. read], "\r\n")) { return error.MissingCRLF; } return Request{ .uri = try uri.parse(self.buffer[0 .. read - 2]) }; } }; } test "Happy flow" { const valid = "gemini://example.com/hello-world\r\n"; var buf: [1026]u8 = undefined; _ = try parse(std.io.fixedBufferStream(valid).reader(), &buf); } test "Unhappy flow" { const error_cases = .{ .{ "gemini://example.com", error.MissingCRLF }, .{ &[_]u8{0} ** 1027, error.UriTooLong }, .{ "\r\n", error.MissingUri }, .{ "", error.EndOfStream }, }; inline for (error_cases) |case| { var buf: [1028]u8 = undefined; try std.testing.expectError( case[1], parse(std.io.fixedBufferStream(case[0]).reader(), &buf), ); } var buf: [1]u8 = undefined; try std.testing.expectError( error.BufferTooSmall, parse(std.io.fixedBufferStream("test").reader(), &buf), ); }
src/Request.zig
const std = @import("std"); const parseFloat = std.fmt.parseFloat; const parseInt = std.fmt.parseInt; pub const MaterialData = struct { materials: std.StringHashMap(Material), fn deinit(self: *@This()) void { self.materials.deinit(); } }; // NOTE: I'm not sure which material statements are optional. For now, I'm assuming all of them are. pub const Material = struct { ambient_color: ?[3]f32 = null, diffuse_color: ?[3]f32 = null, specular_color: ?[3]f32 = null, specular_highlight: ?f32 = null, emissive_coefficient: ?[3]f32 = null, optical_density: ?f32 = null, dissolve: ?f32 = null, illumination: ?u8 = null, bump_map_path: ?[]const u8 = null, diffuse_map_path: ?[]const u8 = null, specular_map_path: ?[]const u8 = null, }; const Keyword = enum { comment, new_material, ambient_color, diffuse_color, specular_color, specular_highlight, emissive_coefficient, optical_density, dissolve, illumination, bump_map_path, diffuse_map_path, specular_map_path, }; pub fn parse(allocator: std.mem.Allocator, data: []const u8) !MaterialData { var materials = std.StringHashMap(Material).init(allocator); var lines = std.mem.tokenize(u8, data, "\n"); var current_material = Material{}; var name: ?[]const u8 = null; while (lines.next()) |line| { var words = std.mem.tokenize(u8, line, " "); const keyword = try parseKeyword(words.next().?); switch (keyword) { .comment => {}, .new_material => { if (name) |n| { try materials.put(n, current_material); current_material = Material{}; } name = words.next().?; }, .ambient_color => { current_material.ambient_color = try parseVec3(&words); }, .diffuse_color => { current_material.diffuse_color = try parseVec3(&words); }, .specular_color => { current_material.specular_color = try parseVec3(&words); }, .specular_highlight => { current_material.specular_highlight = try parseFloat(f32, words.next().?); }, .emissive_coefficient => { current_material.emissive_coefficient = try parseVec3(&words); }, .optical_density => { current_material.optical_density = try parseFloat(f32, words.next().?); }, .dissolve => { current_material.dissolve = try parseFloat(f32, words.next().?); }, .illumination => { current_material.illumination = try parseInt(u8, words.next().?, 10); }, .bump_map_path => { current_material.bump_map_path = words.next().?; }, .diffuse_map_path => { current_material.diffuse_map_path = words.next().?; }, .specular_map_path => { current_material.specular_map_path = words.next().?; }, } } try materials.put(name.?, current_material); return MaterialData{ .materials = materials }; } fn parseVec3(iter: *std.mem.TokenIterator(u8)) ![3]f32 { const x = try parseFloat(f32, iter.next().?); const y = try parseFloat(f32, iter.next().?); const z = try parseFloat(f32, iter.next().?); return [_]f32{ x, y, z }; } fn parseKeyword(s: []const u8) !Keyword { if (std.mem.eql(u8, s, "#")) { return .comment; } else if (std.mem.eql(u8, s, "newmtl")) { return .new_material; } else if (std.mem.eql(u8, s, "Ka")) { return .ambient_color; } else if (std.mem.eql(u8, s, "Kd")) { return .diffuse_color; } else if (std.mem.eql(u8, s, "Ks")) { return .specular_color; } else if (std.mem.eql(u8, s, "Ns")) { return .specular_highlight; } else if (std.mem.eql(u8, s, "Ke")) { return .emissive_coefficient; } else if (std.mem.eql(u8, s, "Ni")) { return .optical_density; } else if (std.mem.eql(u8, s, "d")) { return .dissolve; } else if (std.mem.eql(u8, s, "illum")) { return .illumination; } else if (std.mem.eql(u8, s, "map_Bump")) { return .bump_map_path; } else if (std.mem.eql(u8, s, "map_Kd")) { return .diffuse_map_path; } else if (std.mem.eql(u8, s, "map_Ns")) { return .specular_map_path; } else { std.log.warn("Unknown keyword: {s}", .{s}); return error.UnknownKeyword; } } const test_allocator = std.testing.allocator; const expectEqual = std.testing.expectEqual; const expectEqualSlices = std.testing.expectEqualSlices; const expectEqualStrings = std.testing.expectEqualStrings; test "single material" { const data = @embedFile("../single.mtl"); var result = try parse(test_allocator, data); defer result.deinit(); const material = result.materials.get("Material").?; try expectEqualSlices(f32, &material.ambient_color.?, &.{ 1.0, 1.0, 1.0 }); try expectEqualSlices(f32, &material.diffuse_color.?, &.{ 0.9, 0.9, 0.9 }); try expectEqualSlices(f32, &material.specular_color.?, &.{ 0.8, 0.8, 0.8 }); try expectEqualSlices(f32, &material.emissive_coefficient.?, &.{ 0.7, 0.7, 0.7 }); try expectEqual(material.specular_highlight.?, 225.0); try expectEqual(material.optical_density.?, 1.45); try expectEqual(material.dissolve.?, 1.0); try expectEqual(material.illumination.?, 2); try expectEqualStrings(material.bump_map_path.?, "/path/to/bump.png"); try expectEqualStrings(material.diffuse_map_path.?, "/path/to/diffuse.png"); try expectEqualStrings(material.specular_map_path.?, "/path/to/specular.png"); }
src/mtl.zig
const std = @import("std"); const util = @import("util.zig"); const uv_util = @import("uv_util.zig"); const c = @import("uv_c.zig").c; pub const log = util.log; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const alloc = &gpa.allocator; const DEFAULT_PORT = 3000; const DEFAULT_BACKLOG = 128; pub fn main() !void { uv_util.init(alloc); defer _ = gpa.deinit(); const loop = c.uv_default_loop(); var addr: c.sockaddr_in = undefined; var server: c.uv_tcp_t = undefined; _ = c.uv_tcp_init(loop, &server); server.data = @ptrCast(?*c_void, loop); _ = c.uv_ip4_addr("0.0.0.0", DEFAULT_PORT, &addr); _ = c.uv_tcp_bind(&server, @ptrCast(?*const c.sockaddr, &addr), 0); const r = c.uv_listen(@ptrCast(?*c.uv_stream_t, &server), DEFAULT_BACKLOG, on_new_connection); if (r != 0) { std.log.err("Listen error {}", .{c.uv_strerror(r)}); return error.listen_error; } _ = c.uv_run(loop, util.castCEnum(c.uv_run, 1, c.UV_RUN_DEFAULT)); std.log.info("Closing...", .{}); } export fn on_new_connection(server: ?*c.uv_stream_t, status: i32) void { if (status < 0) { std.log.err("New connection error {}", .{c.uv_strerror(status)}); return; } var client = alloc.create(c.uv_tcp_t) catch { std.log.err("Error allocating client", .{}); return; }; errdefer alloc.destroy(client); const loop = util.cast_from_cptr(*c.uv_loop_t, server.?.data); _ = c.uv_tcp_init(loop, client); if (c.uv_accept(server, @ptrCast(?*c.uv_stream_t, client)) == 0) { _ = c.uv_read_start(@ptrCast(?*c.uv_stream_t, client), uv_util.alloc_buffer, echo_read); } else { _ = c.uv_close(@ptrCast(?*c.uv_handle_t, client), null); } } export fn echo_read(client: ?*c.uv_stream_t, nread: isize, buf: ?*const c.uv_buf_t) void { std.debug.assert(client != null); std.debug.assert(buf != null); if (nread < 0) { if (nread == c.UV_EOF) { _ = c.uv_close(@ptrCast(?*c.uv_handle_t, client), null); } } else if (nread > 0) { var req = alloc.create(uv_util.WriteReq) catch unreachable; const buf_data = alloc.dupe(u8, buf.?.base[0..@intCast(usize, nread)]) catch unreachable; std.log.info("< {s}", .{buf_data}); req.buf = c.uv_buf_init(buf_data.ptr, @intCast(u32, buf_data.len)); _ = c.uv_write(&req.req, client, &req.buf, 1, uv_util.on_write); } if (buf.?.base != null) { alloc.free(buf.?.base[0..buf.?.len]); } }
src/uv_examples/uvserver.zig
const c = @cImport({ @cInclude("cfl.h"); @cInclude("cfl_image.h"); }); const widget = @import("widget.zig"); const enums = @import("enums.zig"); const std = @import("std"); const Scheme = enum { Base, Gtk, Plastic, Gleam, }; // fltk initizialization of optional functionalities pub fn init() !void { c.Fl_init_all(); // inits all styles, if needed c.Fl_register_images(); // register image types supported by fltk, if needed const ret = c.Fl_lock(); // enable multithreading, if needed if (ret != 0) unreachable; } pub fn run() !void { const ret = c.Fl_run(); if (ret != 0) unreachable; } pub fn setScheme(scheme: Scheme) void { var temp = switch (scheme) { .Base => "base", .Gtk => "gtk+", .Plastic => "plastic", .Gleam => "gleam", }; c.Fl_set_scheme(temp); } pub fn event() enums.Event { return @intToEnum(enums.Event, c.Fl_event()); } pub fn eventX() i32 { return c.Fl_event_x(); } pub fn eventY() i32 { return c.Fl_event_y(); } pub fn background(r: u8, g: u8, b: u8) void { c.Fl_background(r, g, b); } pub fn background2(r: u8, g: u8, b: u8) void { c.Fl_background2(r, g, b); } pub fn foreground(r: u8, g: u8, b: u8) void { c.Fl_foreground(r, g, b); } pub const WidgetTracker = struct { inner: ?*c.Fl_Widget_Tracker, pub fn new(w: widget.Widget) WidgetTracker { const ptr = c.Fl_Widget_Tracker_new(@ptrCast(?*c.Fl_Widget, w.inner)); if (ptr == null) unreachable; return WidgetTracker{ .inner = ptr, }; } pub fn deleted() bool { return c.Fl_Widget_Tracker_deleted() != 0; } pub fn delete(self: WidgetTracker) void { c.Fl_Widget_Tracker_delete(self.inner); } }; pub fn wait() bool { return c.Fl_wait() != 0; } pub fn send(comptime T: type, t: T) void { c.Fl_awake_msg(@intToPtr(?*c_void, @bitCast(usize, t))); } pub fn recv(comptime T: type) ?T { var temp = c.Fl_thread_msg(); if (temp) |ptr| { const v = @ptrToInt(ptr); return @intToEnum(T, v); } return null; } pub fn rgb_color(r: u8, g: u8, b: u8) u32 { return c.Fl_get_rgb_color(r, g, b); } test "" { @import("std").testing.refAllDecls(@This()); }
src/app.zig
const std = @import("std"); pub const BuildOptions = struct { shape_use_32bit_indices: bool = false, }; pub const BuildOptionsStep = struct { options: BuildOptions, step: *std.build.OptionsStep, pub fn init(b: *std.build.Builder, options: BuildOptions) BuildOptionsStep { const bos = .{ .options = options, .step = b.addOptions(), }; bos.step.addOption(bool, "shape_use_32bit_indices", bos.options.shape_use_32bit_indices); return bos; } pub fn getPkg(bos: BuildOptionsStep) std.build.Pkg { return bos.step.getPackage("zmesh_options"); } fn addTo(bos: BuildOptionsStep, target_step: *std.build.LibExeObjStep) void { target_step.addOptions("zmesh_options", bos.step); } }; pub fn getPkg(dependencies: []const std.build.Pkg) std.build.Pkg { return .{ .name = "zmesh", .source = .{ .path = thisDir() ++ "/src/main.zig" }, .dependencies = dependencies, }; } pub fn build(b: *std.build.Builder) void { const build_mode = b.standardReleaseOptions(); const target = b.standardTargetOptions(.{}); const tests = buildTests(b, build_mode, target); const test_step = b.step("test", "Run zmesh tests"); test_step.dependOn(&tests.step); } pub fn buildTests( b: *std.build.Builder, build_mode: std.builtin.Mode, target: std.zig.CrossTarget, ) *std.build.LibExeObjStep { const tests = b.addTest(thisDir() ++ "/src/main.zig"); tests.setBuildMode(build_mode); tests.setTarget(target); link(tests, BuildOptionsStep.init(b, .{})); return tests; } fn buildLibrary(exe: *std.build.LibExeObjStep, bos: BuildOptionsStep) *std.build.LibExeObjStep { const lib = exe.builder.addStaticLibrary("zmesh", thisDir() ++ "/src/main.zig"); bos.addTo(lib); lib.setBuildMode(exe.build_mode); lib.setTarget(exe.target); lib.linkSystemLibrary("c"); lib.linkSystemLibrary("c++"); const par_shapes_t = if (bos.options.shape_use_32bit_indices) "-DPAR_SHAPES_T=uint32_t" else ""; lib.addIncludeDir(thisDir() ++ "/libs/par_shapes"); lib.addCSourceFile( thisDir() ++ "/libs/par_shapes/par_shapes.c", &.{ "-std=c99", "-fno-sanitize=undefined", par_shapes_t }, ); lib.addCSourceFile(thisDir() ++ "/libs/meshoptimizer/clusterizer.cpp", &.{""}); lib.addCSourceFile(thisDir() ++ "/libs/meshoptimizer/indexgenerator.cpp", &.{""}); lib.addCSourceFile(thisDir() ++ "/libs/meshoptimizer/vcacheoptimizer.cpp", &.{""}); lib.addCSourceFile(thisDir() ++ "/libs/meshoptimizer/vcacheanalyzer.cpp", &.{""}); lib.addCSourceFile(thisDir() ++ "/libs/meshoptimizer/vfetchoptimizer.cpp", &.{""}); lib.addCSourceFile(thisDir() ++ "/libs/meshoptimizer/vfetchanalyzer.cpp", &.{""}); lib.addCSourceFile(thisDir() ++ "/libs/meshoptimizer/overdrawoptimizer.cpp", &.{""}); lib.addCSourceFile(thisDir() ++ "/libs/meshoptimizer/overdrawanalyzer.cpp", &.{""}); lib.addCSourceFile(thisDir() ++ "/libs/meshoptimizer/allocator.cpp", &.{""}); lib.addIncludeDir(thisDir() ++ "/libs/cgltf"); lib.addCSourceFile(thisDir() ++ "/libs/cgltf/cgltf.c", &.{"-std=c99"}); return lib; } pub fn link(exe: *std.build.LibExeObjStep, bos: BuildOptionsStep) void { bos.addTo(exe); const lib = buildLibrary(exe, bos); exe.linkLibrary(lib); exe.addIncludeDir(thisDir() ++ "/libs/cgltf"); } fn thisDir() []const u8 { comptime { return std.fs.path.dirname(@src().file) orelse "."; } }
libs/zmesh/build.zig
const std = @import("std"); const builtin = @import("builtin"); const hzzp = @import("hzzp"); const wz = @import("wz"); const Heartbeat = @import("Client/Heartbeat.zig"); const https = @import("https.zig"); const discord = @import("discord.zig"); const json = @import("json.zig"); const util = @import("util.zig"); const log = std.log.scoped(.zCord); const default_agent = "zCord/0.0.1"; const Client = @This(); allocator: *std.mem.Allocator, auth_token: []const u8, user_agent: []const u8, intents: discord.Gateway.Intents, presence: discord.Gateway.Presence, connect_info: ?ConnectInfo, ssl_tunnel: ?*https.Tunnel, wz: WzClient, wz_buffer: [0x1000]u8, write_mutex: std.Thread.Mutex, heartbeat: Heartbeat, const WzClient = wz.base.client.BaseClient(https.Tunnel.Client.Reader, https.Tunnel.Client.Writer); pub const JsonElement = json.Stream(WzClient.PayloadReader).Element; pub const ConnectInfo = struct { heartbeat_interval_ms: u64, seq: u32, user_id: discord.Snowflake(.user), session_id: std.BoundedArray(u8, 0x100), }; pub fn create(args: struct { allocator: *std.mem.Allocator, auth_token: []const u8, user_agent: []const u8 = default_agent, intents: discord.Gateway.Intents = .{}, presence: discord.Gateway.Presence = .{}, heartbeat: Heartbeat.Strategy = Heartbeat.Strategy.default, }) !*Client { const result = try args.allocator.create(Client); errdefer args.allocator.destroy(result); result.allocator = args.allocator; result.auth_token = args.auth_token; result.user_agent = args.user_agent; result.intents = args.intents; result.presence = args.presence; result.connect_info = null; result.ssl_tunnel = null; result.write_mutex = .{}; result.heartbeat = try Heartbeat.init(result, args.heartbeat); errdefer result.heartbeat.deinit(); return result; } pub fn destroy(self: *Client) void { if (self.ssl_tunnel) |ssl_tunnel| { ssl_tunnel.destroy(); } self.heartbeat.deinit(); self.allocator.destroy(self); } fn fetchGatewayHost(self: *Client, buffer: []u8) ![]const u8 { var req = try self.sendRequest(self.allocator, .GET, "/api/v8/gateway/bot", null); defer req.deinit(); switch (req.response_code.?) { .success_ok => {}, .client_unauthorized => return error.AuthenticationFailed, else => { log.warn("Unknown response code: {}", .{req.response_code.?}); return error.UnknownGatewayResponse; }, } try req.completeHeaders(); var stream = json.stream(req.client.reader()); const root = try stream.root(); const match = (try root.objectMatchOne("url")) orelse return error.UnknownGatewayResponse; const url = try match.value.stringBuffer(buffer); if (std.mem.startsWith(u8, url, "wss://")) { return url["wss://".len..]; } else { log.warn("Unknown url: {s}", .{url}); return error.UnknownGatewayResponse; } } fn connect(self: *Client) !ConnectInfo { std.debug.assert(self.ssl_tunnel == null); var buf: [0x100]u8 = undefined; const host = try self.fetchGatewayHost(&buf); self.ssl_tunnel = try https.Tunnel.create(.{ .allocator = self.allocator, .host = host, }); errdefer self.disconnect(); const reader = self.ssl_tunnel.?.client.reader(); const writer = self.ssl_tunnel.?.client.writer(); const Reader = @TypeOf(reader); const Writer = @TypeOf(writer); const seed = @truncate(u64, @bitCast(u128, std.time.nanoTimestamp())); var prng = std.rand.DefaultPrng.init(seed); // Handshake // DefaultHandshakeClient on 0.0.6 // HandshakeClient on master // // At the end I needed to change DefaultHandshakeClient src at the end // This is solved on master branch var handshake = wz.base.client.DefaultHandshakeClient(Reader, Writer).init(&self.wz_buffer, reader, writer, prng); try handshake.writeStatusLine("/?v=6&encoding=json"); try handshake.writeHeaderValue("Host", host); try handshake.finishHeaders(); if (!try handshake.wait()) { return error.HandshakeError; } self.wz = wz.base.client.create( &self.wz_buffer, self.ssl_tunnel.?.client.reader(), self.ssl_tunnel.?.client.writer(), ); if (try self.wz.next()) |event| { std.debug.assert(event == .header); } var result: ConnectInfo = undefined; var flush_error: WzClient.ReadNextError!void = {}; { std.log.info("here2", .{}); var stream = json.stream(self.wz.reader()); defer self.wz.flushReader() catch |err| { flush_error = err; }; errdefer |err| log.info("{}", .{stream.debugInfo()}); const root = try stream.root(); const paths = try json.path.match(root, struct { @"op": u8, @"d.heartbeat_interval": u32, }); if (paths.@"op" != @enumToInt(discord.Gateway.Opcode.hello)) { return error.MalformedHelloResponse; } result.heartbeat_interval_ms = paths.@"d.heartbeat_interval"; } try flush_error; if (result.heartbeat_interval_ms == 0) { return error.MalformedHelloResponse; } if (self.connect_info) |old_info| { try self.sendCommand(.{ .@"resume" = .{ .token = self.auth_token, .seq = old_info.seq, .session_id = old_info.session_id.constSlice(), } }); result.seq = old_info.seq; result.user_id = old_info.user_id; result.session_id = old_info.session_id; return result; } try self.sendCommand(.{ .identify = .{ .compress = false, .intents = self.intents, .token = self.auth_token, .properties = .{ .@"$os" = @tagName(builtin.target.os.tag), .@"$browser" = self.user_agent, .@"$device" = self.user_agent, }, .presence = self.presence, } }); if (try self.wz.next()) |event| { if (event.header.opcode == .close) { try self.processCloseEvent(); } } { var stream = json.stream(self.wz.reader()); defer self.wz.flushReader() catch |err| { flush_error = err; }; errdefer |err| log.info("{}", .{stream.debugInfo()}); const root = try stream.root(); const paths = try json.path.match(root, struct { @"t": std.BoundedArray(u8, 0x100), @"s": ?u32, @"op": u8, @"d.session_id": std.BoundedArray(u8, 0x100), @"d.user.id": discord.Snowflake(.user), @"d.user.username": std.BoundedArray(u8, 0x100), @"d.user.discriminator": std.BoundedArray(u8, 0x100), }); if (!std.mem.eql(u8, paths.@"t".constSlice(), "READY")) { return error.MalformedIdentify; } if (paths.@"op" != @enumToInt(discord.Gateway.Opcode.dispatch)) { return error.MalformedIdentify; } if (paths.@"s") |seq| { result.seq = seq; } result.user_id = paths.@"d.user.id"; result.session_id = paths.@"d.session_id"; log.info("Connected -- {s}#{s}", .{ paths.@"d.user.username".constSlice(), paths.@"d.user.discriminator".constSlice(), }); } try flush_error; return result; } fn disconnect(self: *Client) void { if (self.ssl_tunnel) |ssl_tunnel| { ssl_tunnel.destroy(); self.ssl_tunnel = null; } } pub fn ws(self: *Client, context: anytype, comptime handler: type) !void { var reconnect_wait: u64 = 1; while (true) { self.connect_info = self.connect() catch |err| switch (err) { error.AuthenticationFailed, error.DisallowedIntents, error.CertificateVerificationFailed, => |e| return e, else => { log.info("Connect error: {s}", .{@errorName(err)}); std.time.sleep(reconnect_wait * std.time.ns_per_s); reconnect_wait = std.math.min(reconnect_wait * 2, 30); continue; }, }; defer self.disconnect(); if (@hasDecl(handler, "handleConnect")) { handler.handleConnect(context, self.connect_info.?); } reconnect_wait = 1; self.heartbeat.send(.start); defer self.heartbeat.send(.stop); self.listen(context, handler) catch |err| switch (err) { error.ConnectionReset => continue, error.InvalidSession => { self.connect_info = null; continue; }, else => |e| { // TODO: convert this to inline switch once available if (!util.errSetContains(WzClient.ReadNextError, e)) { return e; } }, }; } } fn processCloseEvent(self: *Client) !void { const event = (try self.wz.next()).?; const code_num = std.mem.readIntBig(u16, event.chunk.data[0..2]); const code = @intToEnum(discord.Gateway.CloseEventCode, code_num); switch (code) { _ => { log.info("Websocket close frame - {d}: unknown code. Reconnecting...", .{code_num}); return error.ConnectionReset; }, .NormalClosure, .GoingAway, .ProtocolError, .NoStatusReceived, .AbnormalClosure, .PolicyViolation, .InternalError, .ServiceRestart, .TryAgainLater, .BadGateway, .UnknownError, .SessionTimedOut, => { log.info("Websocket close frame - {d}: {s}. Reconnecting...", .{ @enumToInt(code), @tagName(code) }); return error.ConnectionReset; }, // Most likely user error .UnsupportedData => return error.UnsupportedData, .InvalidFramePayloadData => return error.InvalidFramePayloadData, .MessageTooBig => return error.MessageTooBig, .AuthenticationFailed => return error.AuthenticationFailed, .AlreadyAuthenticated => return error.AlreadyAuthenticated, .DecodeError => return error.DecodeError, .UnknownOpcode => return error.UnknownOpcode, .RateLimited => return error.WoahNelly, .DisallowedIntents => return error.DisallowedIntents, // We don't support these yet .InvalidSeq => unreachable, .InvalidShard => unreachable, .ShardingRequired => unreachable, .InvalidApiVersion => unreachable, // This library fucked up .MissingExtension => unreachable, .TlsHandshake => unreachable, .NotAuthenticated => unreachable, .InvalidIntents => unreachable, } } fn listen(self: *Client, context: anytype, comptime handler: type) !void { while (try self.wz.next()) |event| { switch (event.header.opcode) { .text => { self.processChunks(self.wz.reader(), context, handler) catch |err| switch (err) { error.ConnectionReset, error.InvalidSession => |e| return e, else => { log.warn("Process chunks failed: {s}", .{err}); }, }; try self.wz.flushReader(); }, .ping, .pong => {}, .close => try self.processCloseEvent(), .binary => return error.WtfBinary, else => return error.WtfWtf, } } log.info("Websocket close frame - {{}}: no reason provided. Reconnecting...", .{}); return error.ConnectionReset; } fn processChunks(self: *Client, reader: anytype, context: anytype, comptime handler: type) !void { var stream = json.stream(reader); errdefer |err| { if (util.errSetContains(@TypeOf(stream).ParseError, err)) { log.warn("{}", .{stream.debugInfo()}); } } var name_buf: [32]u8 = undefined; var name: ?[]u8 = null; var op: ?discord.Gateway.Opcode = null; const root = try stream.root(); while (try root.objectMatch(enum { t, s, op, d })) |match| switch (match.key) { .t => { name = try match.value.optionalStringBuffer(&name_buf); }, .s => { if (try match.value.optionalNumber(u32)) |seq| { self.connect_info.?.seq = seq; } }, .op => { op = try std.meta.intToEnum(discord.Gateway.Opcode, try match.value.number(u8)); }, .d => { switch (op orelse return error.DataBeforeOp) { .dispatch => { log.info("<< {d} -- {s}", .{ self.connect_info.?.seq, name }); try handler.handleDispatch( context, name orelse return error.DispatchWithoutName, match.value, ); }, .heartbeat_ack => self.heartbeat.send(.ack), .reconnect => { log.info("Discord reconnect. Reconnecting...", .{}); return error.ConnectionReset; }, .invalid_session => { log.info("Discord invalid session. Reconnecting...", .{}); const resumable = match.value.boolean() catch false; if (resumable) { return error.ConnectionReset; } else { return error.InvalidSession; } }, else => { log.info("Unhandled {} -- {s}", .{ op, name }); match.value.debugDump(std.io.getStdErr().writer()) catch {}; }, } _ = try match.value.finalizeToken(); }, }; } pub fn sendCommand(self: *Client, command: discord.Gateway.Command) !void { if (self.ssl_tunnel == null) return error.NotConnected; var buf: [0x1000]u8 = undefined; const msg = try std.fmt.bufPrint(&buf, "{s}", .{json.format(command)}); self.write_mutex.lock(); defer self.write_mutex.unlock(); try self.wz.writeHeader(.{ .opcode = .text, .length = msg.len }); try self.wz.writeChunk(msg); } pub fn sendRequest(self: *Client, allocator: *std.mem.Allocator, method: https.Request.Method, path: []const u8, body: anytype) !https.Request { var req = try https.Request.init(.{ .allocator = allocator, .host = "discord.com", .method = method, .path = path, .user_agent = self.user_agent, }); errdefer req.deinit(); try req.client.writeHeaderValue("Accept", "application/json"); try req.client.writeHeaderValue("Content-Type", "application/json"); try req.client.writeHeaderValue("Authorization", self.auth_token); switch (@typeInfo(@TypeOf(body))) { .Null => _ = try req.sendEmptyBody(), .Optional => { if (body == null) { _ = try req.sendEmptyBody(); } else { _ = try req.sendPrint("{}", .{json.format(body)}); } }, else => _ = try req.sendPrint("{}", .{json.format(body)}), } return req; } test { std.testing.refAllDecls(@This()); }
src/Client.zig
const Board = @This(); const std = @import("std"); const assert = std.debug.assert; const attacks = @import("../bitboards/attacks.zig"); const bitboard = @import("../utils/bitboard.zig"); const console = @import("../utils/console.zig"); const masks = @import("../bitboards/masks.zig"); const Color = @import("enums.zig").Color; const Rank = @import("enums.zig").Rank; const File = @import("enums.zig").File; const Square = @import("enums.zig").Square; const Piece = @import("Piece.zig"); const Move = @import("Move.zig"); const MoveList = @import("MoveList.zig"); // Data members start piece_bitboards: [6]u64 = undefined, color_bitboards: [2]u64 = undefined, enpassant_square: Square = undefined, castling_rights_bitset: u4 = undefined, side_to_move: Color = undefined, // Data members end // zig fmt: off const castling_spoilers = [_]u4{ 13, 15, 15, 15, 12, 15, 15, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 7, 15, 15, 15, 3, 15, 15, 11 }; // zig fmt: on pub fn makeMove(self: *Board, move: Move) void { const from = move.from_square; const to = move.to_square; const move_type = self.moveTypeOf(move); const side_to_move = self.side_to_move; const opposite_side = side_to_move.reverse(); self.side_to_move = opposite_side; self.enpassant_square = .None; self.castling_rights_bitset &= castling_spoilers[@enumToInt(from)] & castling_spoilers[@enumToInt(to)]; switch (move_type) { .Normal => self.movePiece(Piece{ .type = self.pieceTypeOn(from), .color = side_to_move }, from, to), .Capture => { self.removePiece(Piece{ .type = self.pieceTypeOn(to), .color = opposite_side }, to); self.movePiece(Piece{ .type = self.pieceTypeOn(from), .color = side_to_move }, from, to); }, .DoublePush => { self.movePiece(Piece{ .type = .Pawn, .color = side_to_move }, from, to); self.enpassant_square = if (side_to_move == .White) @intToEnum(Square, @enumToInt(from) + 8) else @intToEnum(Square, (@enumToInt(from) - 8)); }, .Enpassant => { const captured_piece_square = if (side_to_move == Color.White) @intToEnum(Square, @enumToInt(to) - 8) else @intToEnum(Square, (@enumToInt(to) + 8)); self.movePiece(Piece{ .type = .Pawn, .color = side_to_move }, from, to); self.removePiece(Piece{ .type = .Pawn, .color = opposite_side }, captured_piece_square); }, .Castling => { self.movePiece(Piece{ .type = .King, .color = side_to_move }, from, to); switch (to) { .C1 => self.movePiece(Piece{ .type = .Rook, .color = side_to_move }, .A1, .D1), .G1 => self.movePiece(Piece{ .type = .Rook, .color = side_to_move }, .H1, .F1), .C8 => self.movePiece(Piece{ .type = .Rook, .color = side_to_move }, .A8, .D8), .G8 => self.movePiece(Piece{ .type = .Rook, .color = side_to_move }, .H8, .F8), else => unreachable, } }, .CapturePromotion => { self.removePiece(Piece{ .type = self.pieceTypeOn(to), .color = opposite_side }, to); self.removePiece(Piece{ .type = .Pawn, .color = side_to_move }, from); self.putPiece(Piece{ .type = move.promotion_piece_type, .color = side_to_move }, to); }, .Promotion => { self.removePiece(Piece{ .type = .Pawn, .color = side_to_move }, from); self.putPiece(Piece{ .type = move.promotion_piece_type, .color = side_to_move }, to); }, .None => unreachable, } } pub fn pieceTypeOn(self: *Board, square: Square) Piece.Type { const square_bb = square.toBitboard(); for (Piece.Type.all) |piece_type| { if ((self.piece_bitboards[@enumToInt(piece_type)] & square_bb) != 0) { return piece_type; } } return .None; } pub fn pieceOn(self: *Board, square: Square) ?Piece { const square_bb = square.toBitboard(); var pt = Piece.Type.None; for (Piece.Type.all) |piece_type| { if ((self.piece_bitboards[@enumToInt(piece_type)] & square_bb) != 0) { pt = piece_type; break; } } if (pt == Piece.Type.None) { return null; } const color = if ((self.color_bitboards[@enumToInt(Color.White)] & square_bb) != 0) Color.White else Color.Black; return Piece{ .type = pt, .color = color }; } pub fn parse(fen: []const u8) Board { var board = Board{}; board.clear(); var fenIndex: u8 = 0; var fenSquareIndex: u8 = @enumToInt(Square.A8); while (fenIndex < 64) { if (fenIndex >= fen.len) { unreachable; // TODO: Handle error } const ch = fen[fenIndex]; fenIndex += 1; if (ch == ' ') { break; } else if (ch > '0' and ch < '9') { fenSquareIndex += (ch - '0'); } else if (ch == '/') { fenSquareIndex -= 16; } else { const piece = Piece.parse(ch); const square = @intToEnum(Square, fenSquareIndex); assert(square != .None); board.putPiece(piece, square); fenSquareIndex += 1; } } var ch = fen[fenIndex]; board.side_to_move = Color.parse(ch); fenIndex += 2; ch = fen[fenIndex]; while (ch != ' ') { if (ch == '-') { fenIndex += 1; break; } else { board.castling_rights_bitset |= switch (ch) { 'K' => @as(u4, 1), 'Q' => @as(u4, 2), 'k' => @as(u4, 4), 'q' => @as(u4, 8), else => unreachable, // TODO: Handle error }; } fenIndex += 1; ch = fen[fenIndex]; } fenIndex += 1; ch = fen[fenIndex]; if (ch != '-') { fenIndex += 1; board.enpassant_square = @intToEnum(Square, (ch - 'a') + ((fen[fenIndex] - '1') << 3)); } return board; } pub fn print(self: *Board) void { for (Square.all) |square| { if (square != Square.A1 and (@enumToInt(square) & 7) == 0) { console.println("", .{}); } const square_flipped = @intToEnum(Square, @enumToInt(square) ^ 56); const optional_piece = self.pieceOn(square_flipped); if (optional_piece) |piece| { console.printf("{} ", .{&[1]u8{piece.toChar()}}); } else { console.printf("- ", .{}); } } console.println("", .{}); } pub fn clear(self: *Board) void { for (Piece.Type.all) |piece_type| { self.piece_bitboards[@enumToInt(piece_type)] = 0; } for (Color.all) |color| { self.color_bitboards[@enumToInt(color)] = 0; } self.enpassant_square = .None; self.castling_rights_bitset = 0; self.side_to_move = .White; } pub fn occupancyBB(self: *Board) u64 { return self.color_bitboards[@enumToInt(Color.White)] | self.color_bitboards[@enumToInt(Color.Black)]; } pub fn sideIsInCheck(self: *Board, color: Color) bool { return self.checkersBBToColor(color) != 0; } pub fn checkersBBToColor(self: *Board, color: Color) u64 { const king_bb = self.piece_bitboards[@enumToInt(Piece.Type.King)]; const color_bb = self.color_bitboards[@enumToInt(color)]; const king_square = @intToEnum(Square, bitboard.bitscanForward(king_bb & color_bb)); return self.attackersBBToSquareByColor(king_square, color.reverse()); } pub fn attackersBBToSquareByColor(self: *Board, square: Square, color: Color) u64 { return self.attackersBBToSquare(square, self.occupancyBB()) & self.color_bitboards[@enumToInt(color)]; } pub fn attackersBBToSquare(self: *Board, square: Square, occupancy_bb: u64) u64 { const pawn_bb = self.piece_bitboards[@enumToInt(Piece.Type.Pawn)]; var attackers_bb = (attacks.pawnAttacks(square, Color.White) & pawn_bb & self.color_bitboards[@enumToInt(Color.Black)]) | (attacks.pawnAttacks(square, Color.Black) & pawn_bb & self.color_bitboards[@enumToInt(Color.White)]); for ([_]Piece.Type{ .Knight, .Bishop, .Rook, .Queen, .King }) |piece_type| { attackers_bb |= attacks.nonPawnAttacks(piece_type, square, occupancy_bb) & self.piece_bitboards[@enumToInt(piece_type)]; } return attackers_bb; } pub fn pinnedBBToColor(self: *Board, color: Color) u64 { const king_bb = self.piece_bitboards[@enumToInt(Piece.Type.King)]; const color_bb = self.color_bitboards[@enumToInt(color)]; const other_color_bb = self.color_bitboards[@enumToInt(color.reverse())]; const king_square = @intToEnum(Square, bitboard.bitscanForward(king_bb & color_bb)); const occupancy_bb = self.occupancyBB(); var pinners_bb = ((self.piece_bitboards[@enumToInt(Piece.Type.Queen)] | self.piece_bitboards[@enumToInt(Piece.Type.Rook)]) & other_color_bb & attacks.rookAttacks(king_square, 0)) | ((self.piece_bitboards[@enumToInt(Piece.Type.Queen)] | self.piece_bitboards[@enumToInt(Piece.Type.Bishop)]) & other_color_bb & attacks.bishopAttacks(king_square, 0)); var pinned_bb: u64 = 0; while (pinners_bb != 0) { const square = bitboard.bitscanForward(pinners_bb); bitboard.popBitForward(&pinners_bb); var bb = masks.intervening_masks[square][@enumToInt(king_square)] & occupancy_bb; if (bitboard.popcount(bb) == 1) { pinned_bb ^= bb & color_bb; } } return pinned_bb; } pub fn generateLegalMoves(self: *Board, move_list_iterator: *MoveList.Iterator) usize { const move_list_start = move_list_iterator.iter; const start = @ptrToInt(move_list_start); if (self.sideIsInCheck(self.side_to_move)) { self.generateCheckEvasions(move_list_iterator); } else { self.generatePseudolegalMoves(move_list_iterator); } var end = @ptrToInt(move_list_iterator.iter); var size: usize = (end - start) / @sizeOf(Move); const king_bb = self.piece_bitboards[@enumToInt(Piece.Type.King)]; const color_bb = self.color_bitboards[@enumToInt(self.side_to_move)]; const king_square = @intToEnum(Square, bitboard.bitscanForward(king_bb & color_bb)); const pinned_bb = self.pinnedBBToColor(self.side_to_move); var move_index: usize = 0; while (move_index < size) { const move = move_list_start[move_index]; if (((pinned_bb & move.from_square.toBitboard()) != 0 or move.from_square == king_square or (move.to_square == self.enpassant_square and self.pieceTypeOn(move.from_square) == .Pawn)) and !self.isLegalGeneratedMove(move, pinned_bb)) { move_list_start[move_index] = move_list_start[size - 1]; size -= 1; } else { move_index += 1; } } return size; } fn isLegalGeneratedMove(self: *Board, move: Move, pinned_bb: u64) bool { const king_bb = self.piece_bitboards[@enumToInt(Piece.Type.King)]; const side_to_move = self.side_to_move; const color_bb = self.color_bitboards[@enumToInt(side_to_move)]; const other_color_bb = self.color_bitboards[@enumToInt(side_to_move.reverse())]; const king_square = @intToEnum(Square, bitboard.bitscanForward(king_bb & color_bb)); const from_square = move.from_square; const to_square = move.to_square; if (self.pieceTypeOn(from_square) == .Pawn and to_square == self.enpassant_square) { const enpassant_bb = self.enpassant_square.toBitboard(); const post_enpassant_occupancy_bb = (self.occupancyBB() ^ from_square.toBitboard() ^ (if (side_to_move == .White) enpassant_bb >> 8 else enpassant_bb << 8)) | enpassant_bb; return (attacks.bishopAttacks(king_square, post_enpassant_occupancy_bb) & (self.piece_bitboards[@enumToInt(Piece.Type.Queen)] | self.piece_bitboards[@enumToInt(Piece.Type.Bishop)]) & other_color_bb) == 0 and (attacks.rookAttacks(king_square, post_enpassant_occupancy_bb) & (self.piece_bitboards[@enumToInt(Piece.Type.Queen)] | self.piece_bitboards[@enumToInt(Piece.Type.Rook)]) & other_color_bb) == 0; } else if (from_square == king_square) { return (to_square.toBitboard() & attacks.kingAttacks(king_square)) == 0 or (self.attackersBBToSquare(to_square, self.occupancyBB()) & other_color_bb) == 0; } else { return (pinned_bb & from_square.toBitboard()) == 0 or (to_square.toBitboard() & masks.xray_masks[@enumToInt(king_square)][@enumToInt(from_square)]) != 0; } } fn generateCheckEvasions(self: *Board, move_list_iterator: *MoveList.Iterator) void { const side_to_move = self.side_to_move; assert(self.sideIsInCheck(side_to_move)); const king_bb = self.piece_bitboards[@enumToInt(Piece.Type.King)]; const color_bb = self.color_bitboards[@enumToInt(side_to_move)]; const color_king_bb = king_bb & color_bb; const king_square = @intToEnum(Square, bitboard.bitscanForward(color_king_bb)); const checkers_bb = self.checkersBBToColor(side_to_move); const sans_king_occupancy_bb = self.occupancyBB() ^ king_square.toBitboard(); var evasions_bb = attacks.kingAttacks(king_square) & ~color_bb; const other_color_bb = self.color_bitboards[@enumToInt(side_to_move.reverse())]; while (evasions_bb != 0) { const square = @intToEnum(Square, bitboard.bitscanForward(evasions_bb)); bitboard.popBitForward(&evasions_bb); if ((self.attackersBBToSquare(square, sans_king_occupancy_bb) & other_color_bb) == 0) { move_list_iterator.addMove(Move{ .from_square = king_square, .to_square = square, }); } } if ((checkers_bb & (checkers_bb - 1)) != 0) { return; } const pawns_bb = self.piece_bitboards[@enumToInt(Piece.Type.Pawn)] & color_bb; const enpassant_square = self.enpassant_square; if (side_to_move == .White) { if (enpassant_square != .None and ((enpassant_square.toBitboard() >> 8) & checkers_bb) != 0) { var enpassant_candidates_bb = attacks.pawnAttacks(enpassant_square, Color.Black) & pawns_bb; while (enpassant_candidates_bb != 0) { const from_square = @intToEnum(Square, bitboard.bitscanForward(enpassant_candidates_bb)); bitboard.popBitForward(&enpassant_candidates_bb); move_list_iterator.addMove(Move{ .from_square = from_square, .to_square = enpassant_square, }); } } } else { if (enpassant_square != .None and ((enpassant_square.toBitboard() << 8) & checkers_bb) != 0) { var enpassant_candidates_bb = attacks.pawnAttacks(enpassant_square, Color.White) & pawns_bb; while (enpassant_candidates_bb != 0) { const from_square = @intToEnum(Square, bitboard.bitscanForward(enpassant_candidates_bb)); bitboard.popBitForward(&enpassant_candidates_bb); move_list_iterator.addMove(Move{ .from_square = from_square, .to_square = enpassant_square, }); } } } const checker_square = @intToEnum(Square, bitboard.bitscanForward(checkers_bb)); const occupancy_bb = self.occupancyBB(); var attackers_bb = self.attackersBBToSquare(checker_square, occupancy_bb) & color_bb & ~color_king_bb; const rank_7_pawns = pawns_bb & (if (side_to_move == .White) masks.rank_masks[@enumToInt(Rank.Seven)] else masks.rank_masks[@enumToInt(Rank.Two)]); var pawn_promotion_attackers_bb = attackers_bb & rank_7_pawns; attackers_bb &= ~rank_7_pawns; while (pawn_promotion_attackers_bb != 0) { const from_square = @intToEnum(Square, bitboard.bitscanForward(pawn_promotion_attackers_bb)); bitboard.popBitForward(&pawn_promotion_attackers_bb); for ([_]Piece.Type{ .Queen, .Knight, .Bishop, .Rook }) |piece_type| { move_list_iterator.addMove(Move{ .from_square = from_square, .to_square = checker_square, .promotion_piece_type = piece_type, }); } } while (attackers_bb != 0) { const from_square = @intToEnum(Square, bitboard.bitscanForward(attackers_bb)); bitboard.popBitForward(&attackers_bb); move_list_iterator.addMove(Move{ .from_square = from_square, .to_square = checker_square, }); } if ((checkers_bb & attacks.kingAttacks(king_square)) != 0) { return; } var checker_intercept_bb = masks.intervening_masks[@enumToInt(king_square)][@enumToInt(checker_square)]; if (checker_intercept_bb == 0) { return; } if (side_to_move == .White) { const shifted_intercept_bb = checker_intercept_bb >> 8; var single_push_pawn_blockers_bb = pawns_bb & shifted_intercept_bb; var double_push_pawn_blockers_bb = ((shifted_intercept_bb & ~occupancy_bb) >> 8) & pawns_bb & masks.rank_masks[@enumToInt(Rank.Two)]; while (double_push_pawn_blockers_bb != 0) { const from_square = @intToEnum(Square, bitboard.bitscanForward(double_push_pawn_blockers_bb)); bitboard.popBitForward(&double_push_pawn_blockers_bb); move_list_iterator.addMove(Move{ .from_square = from_square, .to_square = @intToEnum(Square, @enumToInt(from_square) + 16), }); } while (single_push_pawn_blockers_bb != 0) { const from_square = @intToEnum(Square, bitboard.bitscanForward(single_push_pawn_blockers_bb)); bitboard.popBitForward(&single_push_pawn_blockers_bb); const to_square = @intToEnum(Square, @enumToInt(from_square) + 8); if ((to_square.toBitboard() & masks.rank_masks[@enumToInt(Rank.Seven)]) != 0) { for ([_]Piece.Type{ .Queen, .Knight, .Bishop, .Rook }) |piece_type| { move_list_iterator.addMove(Move{ .from_square = from_square, .to_square = to_square, .promotion_piece_type = piece_type, }); } } else { move_list_iterator.addMove(Move{ .from_square = from_square, .to_square = to_square, }); } } } else { const shifted_intercept_bb = checker_intercept_bb << 8; var single_push_pawn_blockers_bb = pawns_bb & shifted_intercept_bb; var double_push_pawn_blockers_bb = ((shifted_intercept_bb & ~occupancy_bb) << 8) & pawns_bb & masks.rank_masks[@enumToInt(Rank.Seven)]; while (double_push_pawn_blockers_bb != 0) { const from_square = @intToEnum(Square, bitboard.bitscanForward(double_push_pawn_blockers_bb)); bitboard.popBitForward(&double_push_pawn_blockers_bb); move_list_iterator.addMove(Move{ .from_square = from_square, .to_square = @intToEnum(Square, @enumToInt(from_square) - 16), }); } while (single_push_pawn_blockers_bb != 0) { const from_square = @intToEnum(Square, bitboard.bitscanForward(single_push_pawn_blockers_bb)); bitboard.popBitForward(&single_push_pawn_blockers_bb); const to_square = @intToEnum(Square, @enumToInt(from_square) - 8); if ((to_square.toBitboard() & masks.rank_masks[@enumToInt(Rank.Two)]) != 0) { for ([_]Piece.Type{ .Queen, .Knight, .Bishop, .Rook }) |piece_type| { move_list_iterator.addMove(Move{ .from_square = from_square, .to_square = to_square, .promotion_piece_type = piece_type, }); } } else { move_list_iterator.addMove(Move{ .from_square = from_square, .to_square = to_square, }); } } } const excluded_piece_types_mask = ~(king_bb | pawns_bb); while (checker_intercept_bb != 0) { const to_square = @intToEnum(Square, bitboard.bitscanForward(checker_intercept_bb)); bitboard.popBitForward(&checker_intercept_bb); var blockers_bb = self.attackersBBToSquare(to_square, occupancy_bb) & color_bb & excluded_piece_types_mask; while (blockers_bb != 0) { const from_square = @intToEnum(Square, bitboard.bitscanForward(blockers_bb)); bitboard.popBitForward(&blockers_bb); move_list_iterator.addMove(Move{ .from_square = from_square, .to_square = to_square, }); } } } fn generatePseudolegalMoves(self: *Board, move_list_iterator: *MoveList.Iterator) void { self.generateNonPawnMoves(move_list_iterator); self.generatePawnMoves(move_list_iterator); } fn generateNonPawnMoves(self: *Board, move_list_iterator: *MoveList.Iterator) void { const side_to_move_occupancy_bb = self.color_bitboards[@enumToInt(self.side_to_move)]; const other_side_occupancy_bb = self.color_bitboards[@enumToInt(self.side_to_move.reverse())]; const occupancy_bb = side_to_move_occupancy_bb | other_side_occupancy_bb; for ([_]Piece.Type{ .Knight, .Bishop, .Rook, .Queen, .King }) |piece_type| { var piece_type_bb = self.piece_bitboards[@enumToInt(piece_type)] & self.color_bitboards[@enumToInt(self.side_to_move)]; while (piece_type_bb != 0) { const from_square = @intToEnum(Square, bitboard.bitscanForward(piece_type_bb)); bitboard.popBitForward(&piece_type_bb); var attacks_bb = attacks.nonPawnAttacks(piece_type, from_square, occupancy_bb) & (~side_to_move_occupancy_bb | other_side_occupancy_bb); while (attacks_bb != 0) { const to_square = @intToEnum(Square, bitboard.bitscanForward(attacks_bb)); bitboard.popBitForward(&attacks_bb); move_list_iterator.*.addMove(Move{ .from_square = from_square, .to_square = to_square, }); } } } self.generateCastlingMoves(move_list_iterator); } fn generateCastlingMoves(self: *Board, move_list_iterator: *MoveList.Iterator) void { const castling_possibilities = [2][2]u4{ [2]u4{ 1, 2 }, [2]u4{ 4, 8 }, }; const castling_mask = [2][2]u64{ [2]u64{ Square.F1.toBitboard() | Square.G1.toBitboard(), Square.D1.toBitboard() | Square.C1.toBitboard() | Square.B1.toBitboard(), }, [2]u64{ Square.F8.toBitboard() | Square.G8.toBitboard(), Square.D8.toBitboard() | Square.C8.toBitboard() | Square.B8.toBitboard(), }, }; const castling_intermediate_squares = [2][2][2]Square{ [2][2]Square{ [2]Square{ Square.F1, Square.G1 }, [2]Square{ Square.D1, Square.C1 }, }, [2][2]Square{ [2]Square{ Square.F8, Square.G8 }, [2]Square{ Square.D8, Square.C8 }, }, }; const castling_king_squares = [2][2][2]Square{ [2][2]Square{ [2]Square{ Square.E1, Square.G1 }, [2]Square{ Square.E1, Square.C1 }, }, [2][2]Square{ [2]Square{ Square.E8, Square.G8 }, [2]Square{ Square.E8, Square.C8 }, }, }; const castling_rights = self.castling_rights_bitset; const side_to_move = @enumToInt(self.side_to_move); const occupancy_bb = self.occupancyBB(); if ((castling_possibilities[side_to_move][0] & castling_rights) != 0 and ((castling_mask[side_to_move][0] & occupancy_bb) == 0) and (self.checkersBBToColor(@intToEnum(Color, side_to_move)) == 0) and (self.attackersBBToSquareByColor(castling_intermediate_squares[side_to_move][0][0], @intToEnum(Color, side_to_move ^ 1)) == 0) and (self.attackersBBToSquareByColor(castling_intermediate_squares[side_to_move][0][1], @intToEnum(Color, side_to_move ^ 1)) == 0)) { move_list_iterator.addMove(Move{ .from_square = castling_king_squares[side_to_move][0][0], .to_square = castling_king_squares[side_to_move][0][1], }); } if ((castling_possibilities[side_to_move][1] & castling_rights) != 0 and ((castling_mask[side_to_move][1] & occupancy_bb) == 0) and (self.checkersBBToColor(@intToEnum(Color, side_to_move)) == 0) and (self.attackersBBToSquareByColor(castling_intermediate_squares[side_to_move][1][0], @intToEnum(Color, side_to_move ^ 1)) == 0) and (self.attackersBBToSquareByColor(castling_intermediate_squares[side_to_move][1][1], @intToEnum(Color, side_to_move ^ 1)) == 0)) { move_list_iterator.addMove(Move{ .from_square = castling_king_squares[side_to_move][1][0], .to_square = castling_king_squares[side_to_move][1][1], }); } } fn generatePawnMoves(self: *Board, move_list_iterator: *MoveList.Iterator) void { const white_bb = self.color_bitboards[@enumToInt(Color.White)]; const black_bb = self.color_bitboards[@enumToInt(Color.Black)]; const occupancy_bb = white_bb | black_bb; if (self.side_to_move == Color.White) { const pawn_bb = self.piece_bitboards[@enumToInt(Piece.Type.Pawn)] & white_bb; var single_push_bb = (pawn_bb << 8) & ~occupancy_bb; var double_push_bb = ((single_push_bb & masks.rank_masks[@enumToInt(Rank.Three)]) << 8) & ~occupancy_bb; var nw_capture_bb = ((pawn_bb << 7) & black_bb) & ~masks.file_masks[@enumToInt(File.H)]; var ne_capture_bb = ((pawn_bb << 9) & black_bb) & ~masks.file_masks[@enumToInt(File.A)]; const rank_8_mask = masks.rank_masks[@enumToInt(Rank.Eight)]; const sans_rank_8_mask = ~rank_8_mask; var push_promotions_bb = single_push_bb & rank_8_mask; var nw_capture_promotions_bb = nw_capture_bb & rank_8_mask; var ne_capture_promotions_bb = ne_capture_bb & rank_8_mask; single_push_bb &= sans_rank_8_mask; nw_capture_bb &= sans_rank_8_mask; ne_capture_bb &= sans_rank_8_mask; const enpassant_square = self.enpassant_square; if (enpassant_square != .None) { var enpassant_candidates_bb = attacks.pawnAttacks(enpassant_square, Color.Black) & pawn_bb; while (enpassant_candidates_bb != 0) { const from_square = @intToEnum(Square, bitboard.bitscanForward(enpassant_candidates_bb)); bitboard.popBitForward(&enpassant_candidates_bb); move_list_iterator.*.addMove(Move{ .from_square = from_square, .to_square = enpassant_square, }); } } while (single_push_bb != 0) { const to_square = @intToEnum(Square, bitboard.bitscanForward(single_push_bb)); bitboard.popBitForward(&single_push_bb); move_list_iterator.*.addMove(Move{ .from_square = @intToEnum(Square, @enumToInt(to_square) - 8), .to_square = to_square, }); } while (double_push_bb != 0) { const to_square = @intToEnum(Square, bitboard.bitscanForward(double_push_bb)); bitboard.popBitForward(&double_push_bb); move_list_iterator.*.addMove(Move{ .from_square = @intToEnum(Square, @enumToInt(to_square) - 16), .to_square = to_square, }); } while (nw_capture_bb != 0) { const to_square = @intToEnum(Square, bitboard.bitscanForward(nw_capture_bb)); bitboard.popBitForward(&nw_capture_bb); move_list_iterator.*.addMove(Move{ .from_square = @intToEnum(Square, @enumToInt(to_square) - 7), .to_square = to_square, }); } while (ne_capture_bb != 0) { const to_square = @intToEnum(Square, bitboard.bitscanForward(ne_capture_bb)); bitboard.popBitForward(&ne_capture_bb); move_list_iterator.*.addMove(Move{ .from_square = @intToEnum(Square, @enumToInt(to_square) - 9), .to_square = to_square, }); } while (push_promotions_bb != 0) { const to_square = @intToEnum(Square, bitboard.bitscanForward(push_promotions_bb)); bitboard.popBitForward(&push_promotions_bb); for ([_]Piece.Type{ .Queen, .Knight, .Bishop, .Rook }) |piece_type| { move_list_iterator.*.addMove(Move{ .from_square = @intToEnum(Square, @enumToInt(to_square) - 8), .to_square = to_square, .promotion_piece_type = piece_type, }); } } while (nw_capture_promotions_bb != 0) { const to_square = @intToEnum(Square, bitboard.bitscanForward(nw_capture_promotions_bb)); bitboard.popBitForward(&nw_capture_promotions_bb); for ([_]Piece.Type{ .Queen, .Knight, .Bishop, .Rook }) |piece_type| { move_list_iterator.*.addMove(Move{ .from_square = @intToEnum(Square, @enumToInt(to_square) - 7), .to_square = to_square, .promotion_piece_type = piece_type, }); } } while (ne_capture_promotions_bb != 0) { const to_square = @intToEnum(Square, bitboard.bitscanForward(ne_capture_promotions_bb)); bitboard.popBitForward(&ne_capture_promotions_bb); for ([_]Piece.Type{ .Queen, .Knight, .Bishop, .Rook }) |piece_type| { move_list_iterator.*.addMove(Move{ .from_square = @intToEnum(Square, @enumToInt(to_square) - 9), .to_square = to_square, .promotion_piece_type = piece_type, }); } } } else { const pawn_bb = self.piece_bitboards[@enumToInt(Piece.Type.Pawn)] & black_bb; var single_push_bb = (pawn_bb >> 8) & ~occupancy_bb; var double_push_bb = ((single_push_bb & masks.rank_masks[@enumToInt(Rank.Six)]) >> 8) & ~occupancy_bb; var se_capture_bb = ((pawn_bb >> 7) & white_bb) & ~masks.file_masks[@enumToInt(File.A)]; var sw_capture_bb = ((pawn_bb >> 9) & white_bb) & ~masks.file_masks[@enumToInt(File.H)]; const rank_1_mask = masks.rank_masks[@enumToInt(Rank.One)]; const sans_rank_1_mask = ~rank_1_mask; var push_promotions_bb = single_push_bb & rank_1_mask; var se_capture_promotions_bb = se_capture_bb & rank_1_mask; var sw_capture_promotions_bb = sw_capture_bb & rank_1_mask; single_push_bb &= sans_rank_1_mask; se_capture_bb &= sans_rank_1_mask; sw_capture_bb &= sans_rank_1_mask; const enpassant_square = self.enpassant_square; if (enpassant_square != .None) { var enpassant_candidates_bb = attacks.pawnAttacks(enpassant_square, Color.White) & pawn_bb; while (enpassant_candidates_bb != 0) { const from_square = @intToEnum(Square, bitboard.bitscanForward(enpassant_candidates_bb)); bitboard.popBitForward(&enpassant_candidates_bb); move_list_iterator.*.addMove(Move{ .from_square = from_square, .to_square = enpassant_square, }); } } while (single_push_bb != 0) { const to_square = @intToEnum(Square, bitboard.bitscanForward(single_push_bb)); bitboard.popBitForward(&single_push_bb); move_list_iterator.*.addMove(Move{ .from_square = @intToEnum(Square, @enumToInt(to_square) + 8), .to_square = to_square, }); } while (double_push_bb != 0) { const to_square = @intToEnum(Square, bitboard.bitscanForward(double_push_bb)); bitboard.popBitForward(&double_push_bb); move_list_iterator.*.addMove(Move{ .from_square = @intToEnum(Square, @enumToInt(to_square) + 16), .to_square = to_square, }); } while (se_capture_bb != 0) { const to_square = @intToEnum(Square, bitboard.bitscanForward(se_capture_bb)); bitboard.popBitForward(&se_capture_bb); move_list_iterator.*.addMove(Move{ .from_square = @intToEnum(Square, @enumToInt(to_square) + 7), .to_square = to_square, }); } while (sw_capture_bb != 0) { const to_square = @intToEnum(Square, bitboard.bitscanForward(sw_capture_bb)); bitboard.popBitForward(&sw_capture_bb); move_list_iterator.*.addMove(Move{ .from_square = @intToEnum(Square, @enumToInt(to_square) + 9), .to_square = to_square, }); } while (push_promotions_bb != 0) { const to_square = @intToEnum(Square, bitboard.bitscanForward(push_promotions_bb)); bitboard.popBitForward(&push_promotions_bb); for ([_]Piece.Type{ .Queen, .Knight, .Bishop, .Rook }) |piece_type| { move_list_iterator.*.addMove(Move{ .from_square = @intToEnum(Square, @enumToInt(to_square) + 8), .to_square = to_square, .promotion_piece_type = piece_type, }); } } while (se_capture_promotions_bb != 0) { const to_square = @intToEnum(Square, bitboard.bitscanForward(se_capture_promotions_bb)); bitboard.popBitForward(&se_capture_promotions_bb); for ([_]Piece.Type{ .Queen, .Knight, .Bishop, .Rook }) |piece_type| { move_list_iterator.*.addMove(Move{ .from_square = @intToEnum(Square, @enumToInt(to_square) + 7), .to_square = to_square, .promotion_piece_type = piece_type, }); } } while (sw_capture_promotions_bb != 0) { const to_square = @intToEnum(Square, bitboard.bitscanForward(sw_capture_promotions_bb)); bitboard.popBitForward(&sw_capture_promotions_bb); for ([_]Piece.Type{ .Queen, .Knight, .Bishop, .Rook }) |piece_type| { move_list_iterator.*.addMove(Move{ .from_square = @intToEnum(Square, @enumToInt(to_square) + 9), .to_square = to_square, .promotion_piece_type = piece_type, }); } } } } fn moveTypeOf(self: *Board, move: Move) Move.Type { const to = move.to_square; const from = move.from_square; const moving_piece_type = self.pieceTypeOn(from); const captured_piece_type = self.pieceTypeOn(to); const promotion_piece_type = move.promotion_piece_type; if (promotion_piece_type != .None) { return if (captured_piece_type != .None) .CapturePromotion else .Promotion; } else if (captured_piece_type != .None) { return .Capture; } else if (moving_piece_type == Piece.Type.Pawn) { const square_diff = std.math.absCast(@as(i32, @enumToInt(to)) - @as(i32, @enumToInt(from))); if (square_diff == 16) { return .DoublePush; } else if (to == self.enpassant_square) { return .Enpassant; } else { return .Normal; } } else if (moving_piece_type == Piece.Type.King and std.math.absCast(@as(i32, @enumToInt(to)) - @as(i32, @enumToInt(from))) == 2) { return .Castling; } else { return .Normal; } } inline fn movePiece(self: *Board, piece: Piece, from: Square, to: Square) void { const from_to_bb = from.toBitboard() | to.toBitboard(); self.piece_bitboards[@enumToInt(piece.type)] ^= from_to_bb; self.color_bitboards[@enumToInt(piece.color)] ^= from_to_bb; } inline fn putPiece(self: *Board, piece: Piece, square: Square) void { const to_bb = square.toBitboard(); self.piece_bitboards[@enumToInt(piece.type)] ^= to_bb; self.color_bitboards[@enumToInt(piece.color)] ^= to_bb; } inline fn removePiece(self: *Board, piece: Piece, square: Square) void { const from_bb = square.toBitboard(); self.piece_bitboards[@enumToInt(piece.type)] ^= from_bb; self.color_bitboards[@enumToInt(piece.color)] ^= from_bb; }
src/types/Board.zig
const std = @import("std"); const input = @embedFile("data/input04"); usingnamespace @import("util.zig"); pub fn main() !void { var numValid1: usize = 0; var numValid2: usize = 0; var reader = std.mem.split(input, "\n\n"); while (reader.next()) |passport| { numValid1 += @boolToInt(isValidPassport(.one, passport)); numValid2 += @boolToInt(isValidPassport(.two, passport)); } print("[Part1] Number of valid passports: {}", .{numValid1}); print("[Part2] Number of valid passports: {}", .{numValid2}); } const Part = enum { one, two }; const RequiredField = enum { byr, iyr, eyr, hgt, hcl, ecl, pid }; fn isValidPassport(comptime part: Part, passport: []const u8) bool { const requiredFieldsMask = 0b0111_1111; var fieldsMask: u8 = 0; var fields = std.mem.tokenize(passport, " \n"); while (fields.next()) |field| { inline for (std.meta.fields(RequiredField)) |f| { const bit = 1 << f.value; if ((fieldsMask & bit) == 0 and std.mem.startsWith(u8, field, f.name ++ ":")) { if (part == .one or (part == .two and isValidField(@intToEnum(RequiredField, f.value), field[4..]))) { fieldsMask |= bit; } break; } } } return (fieldsMask & requiredFieldsMask) == requiredFieldsMask; } fn isValidField(field: RequiredField, value: []const u8) bool { return switch (field) { .byr => isValidYear(value, "1920", "2002"), .iyr => isValidYear(value, "2010", "2020"), .eyr => isValidYear(value, "2020", "2030"), .hgt => if (std.mem.endsWith(u8, value, "cm")) isNumberInRange(value[0..value.len-2], 3, "150", "193") else if (std.mem.endsWith(u8, value, "in")) isNumberInRange(value[0..value.len-2], 2, "59", "76") else false, .hcl => value.len == 7 and value[0] == '#' and all(u8, value[1..], std.ascii.isXDigit), .ecl => value.len == 3 and ( std.mem.eql(u8, value, "amb") or std.mem.eql(u8, value, "blu") or std.mem.eql(u8, value, "brn") or std.mem.eql(u8, value, "gry") or std.mem.eql(u8, value, "grn") or std.mem.eql(u8, value, "hzl") or std.mem.eql(u8, value, "oth") ), .pid => value.len == 9 and all(u8, value, std.ascii.isDigit), }; } fn isValidYear(yearStr: []const u8, comptime min: []const u8, comptime max: []const u8) bool { return isNumberInRange(yearStr, 4, min, max); } fn isNumberInRange(str: []const u8, comptime numDigits: usize, comptime min: []const u8, comptime max: []const u8) bool { return str.len == numDigits and std.mem.order(u8, str, min) != .lt and std.mem.order(u8, str, max) != .gt; } const expect = std.testing.expect; test "isNumberInRange" { expect(isNumberInRange("10", 2, "10", "15")); expect(isNumberInRange("15", 2, "10", "15")); expect(isNumberInRange("12", 2, "10", "15")); expect(!isNumberInRange("8", 2, "10", "15")); expect(!isNumberInRange("20", 2, "10", "15")); } test "validateField" { expect(isValidField(.byr, "2002")); expect(!isValidField(.byr, "2003")); expect(isValidField(.hgt, "60in")); expect(isValidField(.hgt, "190cm")); expect(!isValidField(.hgt, "190in")); expect(!isValidField(.hgt, "190")); expect(isValidField(.hcl, "#123abc")); expect(!isValidField(.hcl, "#123abz")); expect(!isValidField(.hcl, "123abc")); expect(isValidField(.ecl, "brn")); expect(!isValidField(.ecl, "wat")); expect(isValidField(.pid, "000000001")); expect(!isValidField(.pid, "0123456789")); } test "isValidPassport" { expect(!isValidPassport(.two, "eyr:1972 cid:100 hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926")); expect(!isValidPassport(.two, "iyr:2019 hcl:#602927 eyr:1967 hgt:170cm ecl:grn pid:012533040 byr:1946")); expect(!isValidPassport(.two, "hcl:dab227 iyr:2012 ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277")); expect(!isValidPassport(.two, "hgt:59cm ecl:zzz eyr:2038 hcl:74454a iyr:2023 pid:3556412378 byr:2007")); expect(isValidPassport(.two, "pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980 hcl:#623a2f")); expect(isValidPassport(.two, "eyr:2029 ecl:blu cid:129 byr:1989 iyr:2014 pid:896056539 hcl:#a97842 hgt:165cm")); expect(isValidPassport(.two, "hcl:#888785 hgt:164cm byr:2001 iyr:2015 cid:88 pid:545766238 ecl:hzl eyr:2022")); expect(isValidPassport(.two, "iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719")); }
src/day04.zig
const std = @import("std"); const tools = @import("tools"); const with_trace = true; const assert = std.debug.assert; fn trace(comptime fmt: []const u8, args: anytype) void { if (with_trace) std.debug.print(fmt, args); } fn reverseCircular(list: []u8, index: usize, len: usize) void { var i: u32 = 0; const mod = list.len; while (i < len / 2) : (i += 1) { const t = list[(index + i) % mod]; list[(index + i) % mod] = list[(index + ((len - 1) - i)) % mod]; list[(index + ((len - 1) - i)) % mod] = t; } } fn knotHash(str: []const u8) u128 { const mod = 256; var list = comptime blk: { var l: [mod]u8 = undefined; for (l) |*e, i| { e.* = @intCast(u8, i); } break :blk l; }; var skip: u32 = 0; var cursor: u32 = 0; var round: u32 = 0; while (round < 64) : (round += 1) { for (str) |l| { reverseCircular(&list, cursor, l); cursor = (cursor + l + skip) % mod; skip += 1; } for ([_]u8{ 17, 31, 73, 47, 23 }) |l| { reverseCircular(&list, cursor, l); cursor = (cursor + l + skip) % mod; skip += 1; } } var hash: u128 = 0; var accu: u8 = 0; for (list) |l, i| { accu ^= l; if ((i + 1) % 16 == 0) { hash |= @intCast(u128, accu) << @intCast(u7, ((i / 16) * 8)); accu = 0; } } return hash; } pub fn main() anyerror!void { const stdout = std.io.getStdOut().writer(); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); const prefix = "jzgqcdpd"; //@setEvalBranchQuota(500000); -> explose en comptime. //const onescount = comptime blk: { // var bitcount: u32 = 0; // var row: u32 = 0; // while (row < 128) : (row += 1) { // var buf: [12]u8 = undefined; // const str = std.fmt.bufPrint(&buf, prefix ++ "-{}", .{row}) catch unreachable; // const hash = knotHash(str); // bitcount += @popCount(u128, hash); // } // break :blk bitcount; //}; var disk: [128 * 128]u16 = undefined; var sectors: u16 = 0; { var row: u32 = 0; while (row < 128) : (row += 1) { var buf: [12]u8 = undefined; const str = std.fmt.bufPrint(&buf, prefix ++ "-{}", .{row}) catch unreachable; const hash = knotHash(str); var bit: u8 = 0; while (bit < 128) : (bit += 1) { const filled = (hash & (@as(u128, 1) << @intCast(u7, bit))) != 0; if (filled) { sectors += 1; disk[row * 128 + bit] = sectors; } else { disk[row * 128 + bit] = 0; } } } } var dirty = true; while (dirty) { dirty = false; var row: u32 = 0; while (row < 128) : (row += 1) { var col: u32 = 0; while (col < 128) : (col += 1) { const d00 = &disk[(row + 0) * 128 + (col + 0)]; if (row < 127) { const d10 = &disk[(row + 1) * 128 + (col + 0)]; if (d00.* != 0 and d10.* != 0 and d00.* != d10.*) { const min = if (d00.* < d10.*) d00.* else d10.*; d00.* = min; d10.* = min; dirty = true; } } if (col < 127) { const d01 = &disk[(row + 0) * 128 + (col + 1)]; if (d00.* != 0 and d01.* != 0 and d00.* != d01.*) { const min = if (d00.* < d01.*) d00.* else d01.*; d00.* = min; d01.* = min; dirty = true; } } } } } var regions = blk: { var used = [1]bool{false} ** (128 * 128); var total: u32 = 0; for (disk) |d| { if (d == 0) continue; if (used[d]) continue; total += 1; used[d] = true; } break :blk total; }; try stdout.print("sectors={} regions={}\n", .{ sectors, regions }); }
2017/day14.zig
const std = @import("std"); const mem = std.mem; const token = @import("./lang/token.zig"); const builtin = @import("builtin"); const Cmd = @import("./cli.zig").Cmd; const match = @import("./cli.zig").match; const process = std.process; const fs = std.fs; const ChildProcess = std.ChildProcess; pub const io_mode = .evented; const Parser = @import("./lang/parser.zig").Parser; pub fn main() anyerror!void { var a = std.heap.ArenaAllocator.init(std.heap.page_allocator); var alo = a.allocator(); var args = std.process.args(); var mcmd: Cmd = Cmd.help; _ = args.skip(); while (try args.next(alo)) |arg| { if (Cmd.isCmd(arg)) |cm| { std.debug.print("Cmd: {s}\n", .{arg}); mcmd = cm; } else if (std.mem.startsWith(u8, arg, "--")) { std.debug.print("Opt: {s}\n", .{arg[2..]}); } else if (std.mem.startsWith(u8, arg, "-")) { std.debug.print("Opt: {s}", .{arg[1..]}); } else { continue; } } try mcmd.exe(); // _ = try token.tokFile(alo, "../../res/test.is"); } //// Process system args to get command, subcommand(s) (if applicable), and args/flags/opts /// Provides the global command, subcommand, opts, and flags. pub fn processCmd(a: std.mem.Allocator) !void { const args = std.process.argsAlloc(a); defer std.process.argsFree(a, args); var cmd: ?Cmd = null; var arg_i: usize = 1; const arg = args[arg_i]; // ARG POSITION 1 corresponds to base command // Iterates through each possible pair/quad of command values and breaks if there's a match std.debug.print("\x1b[37;1m CMD \x1b[32;1m]#:{d}\x1b[0m is:\x1b[33;1m {s}\x1b[0m", .{ arg_i, cmd }); const main_cmd = cb: { if (match(arg, "list", "ls")) break :cb Cmd{ .list = null }; if (match(arg, "about", "A")) break :cb Cmd{ .about = null }; if (match(arg, "build", "B")) break :cb Cmd{ .base = null }; if (match(arg, "base", "b")) break :cb Cmd{ .build = null }; if (match(arg, "space", "S")) break :cb Cmd{ .id = null }; if (match(arg, "page", "p")) break :cb Cmd{ .build = null }; if (match(arg, "repl", "R")) break :cb Cmd{ .repl = null }; if (match(arg, "shell", "sh")) break :cb Cmd{ .shell = null }; if (match(arg, "init", "i")) break :cb Cmd{ .init = null }; if (match(arg, "id", "I")) break :cb Cmd{ .id = null }; if (match(arg, "guide", "G")) break :cb Cmd{ .build = null }; if (match(arg, "query", "q")) break :cb Cmd{ .build = null }; if (match(arg, "help", "h") or match(arg, "--help", "-h")) break :cb Cmd{ .build = null }; }; try main_cmd.exe(); } // var o: ?Linke([]String u8) = null; // defer opts.deinit(); // For command two, then get subcommands of chosen command and loop thru those // to find a match. In timee . // while (arg_i < args.len) : (arg_i += 2) { // // First we'll parse boolean valued flags // if (match(a, "--debug", "-d")) { // flags.prepend("verbose"); // } else if (match(arg, "--version", "-v")) { // flags.prepend("version"); // } else if (match(arg, "--private", "-p")) { // flags.prepend("private"); // } else if (match(arg, "--all-bases", "-A")) { // flags.prepend("all-bases"); // } else continue; // Next we'll look through the possible gloobal opt keys // if (match(a, "--base", "-b")) { try o.put("base", arg); } //Multiple values allowed // else if (match(arg,"--tag", "-t")) { try o.put("tag", arg); } // Same // else if (match(arg,"--page", "-p")) { try o.put("page", arg);} //Same // else if (match(arg,"--comments", "-c")) { try o.put("comment", arg);} // else if (match(arg,"--attr", "-a")) { try o.put("attr", arg); } // else if (match(arg,"--entity", "-e")) { try o.put("entity", arg); } // else continue; // arg_i += 1; // } // } // // } // // const args = try std.process.argsAlloc(a); // // // for (args) |arg| P // // inline while (args.next) |ar| match: { // if s(td.debug.print("\x1b[32;1mArg {s} ",) .{ar}); { // // if (matches(ar * "spaces", "S")) { // break :match Cmd{ .spaces = null }; // } else if (matches(ar, "config", "C")) { // break :match Cmd{ .config = null }; // } else if (matches(ar, "id", "I")) { // break :match Cmd{ .id = null }; // } else if (matches(ar, "pages", "p")) { // break :match Cmd{ .pages = null }; // } else if (matches(ar, "bases", "b")) {} else if (matches(ar, "spaces", "p")) {} else if (matches(ar, "shell", "sh")) {} else if (matches(ar, "help", "h")) {} else if (matches(ar, "init", "i")) {} else if (matches(ar, "new", "n")) {} else if (matches(ar, "compile", "C")) {} else if (matches(ar, "run", "r")) {} else if (matches(ar, "guides", "G")) {} else if (matches(ar, "build", "b")) { // @import("cli/help.zig").print_usage(); // } else { // return Cmd{ .help = .main }; // } // } // _ = try token.tokFile(a, "../../res/test.is"); // } // const gpa = std.heap.GeneralPurposeAllocator(.{}); // const gpalloc = gpa.allocator(std.heap.page_allocator); // log(.err, .main, "Helelo from space", .{}); // const cli = comptime try Cli.init(&gpalloc); // comptime try cli.exec(); // skip my own exe name // } // // const dir_path = try fs.path.join(a, &[_][]const u8{ cache_root, "clitest" }); // defer fs.cwd().deleteTree(dir_path) catch {}; // const TestFn = fn ([]const u8, []const u8) anyerror!void; // const test_fns = [_]TestFn{ // testZigInitLib, // testZigInitExe, // testGodboltApi, // testMissingOutputPath, // testZigFmt, // }; // for (test_fns) |testFn| { // try fs.cwd().deleteTree(dir_path); // try fs.cwd().makeDir(dir_path); // try testFn(zig_exe, dir_path); // } // } // pub fn main() !void { // log(.info, .main, "Initializing the application!", .{}); // // var a: std.mem.Allocator = undefined; // const arena = comptime std.heap.ArenaAllocator; // var aa = comptime *arena.init(std.heap.page_allocator); // var aall = comptime aa.allocator(); // defer arena.deinit(); // // var gpalloc = comptime arena.allocator(); // var cl = comptime Cli.init(aall); // // _ = comptime try cl.parse(); // _ = comptime try cl.exec(); // } // // pub fn log( // comptime level: std.log.Level, // comptime scope: @TypeOf(.EnumLiteral), // comptime format: []const u8, // args: anytype, // ) void { // logs.log(level, scope, format, args); // } // // test "basic test" { // try std.testing.expectEqual(10, 3 + 7); // } // pub fn async_ex() !void { // var a = std.heap.ArenaAllocator.init(std.heap.page_allocator).child_allocator; // var cpu: u64 = try std.Thread.getCpuCount(); // // var prom = try std.heap.page_allocator.alloc(@Frame(worker), cpu); // defer std.heap.page_allocator.free(prom); // // var compl_tkn: bool = false; // while (cpu > 0) : (cpu -= 1) { // prom[cpu - 1] = async worker(cpu, &compl_tkn); // } // std.debug.print("\x1b[33;1mWorking on some task\x1b[0m", .{}); // for (prom) |*fut| { // var res = await fut; // if (res != 0) std.debug.print("\x1b[33;1mThe answer is \x1b[0m{d}", .{res}); // } // } // // pub fn worker(seed: u64, compl_tkn: *bool) u64 { // std.event.Loop.startCpuBoundOperation(); // var prng = std.rand.DefaultPrng.init(seed); // const rand = prng.random(); // while (true) ev_loop: { // var att = rand.int(u64); // if (att & 0xffffff == 0) { // @atomicStore(bool, compl_tkn, true, std.builtin.AtomicOrder.Release); // std.debug.print("\x1b[33;1mI found the answer!\n\x1b[0m", .{}); // return att; // } // if (@atomicLoad(bool, compl_tkn, std.builtin.AtomicOrder.Acquire)) { // std.debug.print("\x1b[35;1mAnother worker solved it...\x1b[0m", .{}); // break :ev_loop; // } // } // return 0; // } // pub fn mainCmdInline(ar: []const u8) cmd { // return main_cmd:{ // if (matches(ar, "about", "A")) { break:main_cmd .about; } // else if (matches(ar, "build", "b")) { break:main_cmd .build; } // else if (matches(ar, "bases", "B")) { break:main_cmd .build;} // else if (matches(ar, "run", "r")) { break:main_cmd .run;} // else if (matches(ar, "shell", "sh")) { break:main_cmd .shell;} // else if (matches(ar, "repl", "R")) { break:main_cmd .repl;} // else if (matches(ar, "config", "C")) { break:main_cmd .config;} // else if (matches(ar, "guides", "G")) { break:main_cmd.guides;} // else if (matches(ar, "pages", "p")) { break:main_cmd .pages;} // else if (matches(ar, "spaces", "S")){ break:main_cmd .spaces;} // else if (matches(ar, "init", "i")){ break:main_cmd .page ; } // else if (matches(ar, "new", "n")) { break:main_cmd .new ; } // else if (matches(ar, "id", "I")) { break:main_cmd .id ; } // else if (matches(ar, "help", "h") or matches(ar, "--help", "-h")) { break:main_cmd.help ;} // }; // return cmd; // } //
src/main.zig
const std = @import("std"); const assert = std.debug.assert; const log_ = @import("Log.zig"); const errLog_ = log_.errLog; const dbgLog_ = log_.dbgLog; const TCPServer = @import("TCPServer.zig"); const c_allocator = std.heap.c_allocator; const page_allocator = std.heap.page_allocator; const ObjectPool = @import("ObjectPool.zig").ObjectPool; const openssl = @import("OpenSSL.zig").openssl; const tlsCustomBIO = @import("TLSCustomBIO.zig"); const CustomBIO = tlsCustomBIO.CustomBIO; const builtin = @import("builtin"); const LinkedBuffers = @import("LinkedBuffers.zig").LinkedBuffers; const config = @import("Config.zig").config; pub fn dbgLog(comptime s: []const u8, args: var) void { dbgLog_("TLS: " ++ s, args); } pub fn errLog(comptime s: []const u8, args: var) void { errLog_("TLS: " ++ s, args); } pub const BUFFER_SIZE = 16384; // 4096/8192/16384 pub threadlocal var linked_buffer_obj: LinkedBuffers(BUFFER_SIZE, 256) = undefined; pub fn writeBufferPoolSize() usize { return linked_buffer_obj.size(); } var ssl_context: *openssl.SSL_CTX = undefined; export fn doErrPrint(str: [*c]const u8, len: usize, d: ?*c_void) c_int { errLog("{}", .{str[0..len]}); return 1; } fn printErrors() void { if (builtin.mode == .Debug) { var data: [256]u8 = undefined; openssl.ERR_print_errors_cb(doErrPrint, null); } } pub fn init() !void { const method = openssl.TLS_server_method(); const ctx = openssl.SSL_CTX_new(method); if (ctx == null) { return error.OpenSSLError; } ssl_context = ctx.?; // _ = openssl.SSL_CTX_ctrl(ssl_context, openssl.SSL_CTRL_SET_MIN_PROTO_VERSION, openssl.TLS1_3_VERSION, null); _ = openssl.SSL_CTX_ctrl(ssl_context, openssl.SSL_CTRL_SET_MIN_PROTO_VERSION, openssl.TLS1_2_VERSION, null); _ = openssl.SSL_CTX_ctrl(ssl_context, openssl.SSL_CTRL_MODE, openssl.SSL_MODE_RELEASE_BUFFERS, null); if (openssl.SSL_CTX_use_certificate_file(ssl_context, config().certificate_file_path, openssl.SSL_FILETYPE_PEM) <= 0) { return error.OpenSSLError; } if (openssl.SSL_CTX_use_PrivateKey_file(ssl_context, config().certificate_key_file_path, openssl.SSL_FILETYPE_PEM) <= 0) { return error.OpenSSLError; } try tlsCustomBIO.init(); } pub fn threadLocalInit() void { // tlsCustomBIO.threadLocalInit(); linked_buffer_obj = LinkedBuffers(BUFFER_SIZE, 256).init(c_allocator, page_allocator); } // N.B. If a function returns an error then the TLS connection is closed (underlying TCP connection remains open) pub const TLSConnection = struct { // Undefined variables initialised in startConnection ssl: ?*openssl.SSL = null, ssl_accept_finished: bool = false, bio: CustomBIO = undefined, // Not persistent, new buffer acquired for each read read_buffer: ?LinkedBuffers(BUFFER_SIZE, 256).Buffer = null, data_read: u32 = 0, // Only ever has 1 buffer object // Data is unencrypted // Encrypted buffer is in the BIO object write_tmp_buffer: ?LinkedBuffers(BUFFER_SIZE, 256).Buffer = null, write_tmp_buffer_len: u32 = 0, fatal_error: bool = false, trying_to_flush: bool = false, // true -> not accepting new data until flushWrite() succeeds shutdown_in_progress: bool = false, // for retrying writes prev_write_command_fail: ?[]const u8 = null, pub fn startConnection(self: *TLSConnection) !void { const ssl_ = openssl.SSL_new(ssl_context); if (ssl_ == null) { return error.OpenSSLError; } self.ssl = ssl_.?; errdefer { openssl.SSL_free(self.ssl.?); self.ssl = null; } openssl.SSL_set_accept_state(self.ssl.?); try self.bio.init(); openssl.SSL_set_bio(self.ssl.?, self.bio.bio, self.bio.bio); dbgLog("OpenSSL init okay", .{}); } fn checkFatalError(self: *TLSConnection, e: c_int) bool { if (e == openssl.SSL_ERROR_SYSCALL or e == openssl.SSL_ERROR_SSL) { // These 2 errors are unrecoverable // If either of these errors occur then SSL_shutdown() must not be called self.fatal_error = true; return true; } return false; } // N.B. Best not to mix calls to bufferedWrite and sendData - the data will be out of order // flushStream is called every BUFFER_SIZE bytes // call flushStream when all data is written to send the last bit of data // Returns number of bytes written to the buffer // N.B. If the returned value < data_.len then the write /must/ be completed later. // OpenSSL expects the same parameters to OpenSSL_Write() pub fn bufferedWrite(self: *TLSConnection, conn: usize, data_: []const u8) !u32 { if (self.shutdown_in_progress) { try self.shutdown(conn); return 0; } if (self.trying_to_flush) { try self.flushWrite(conn); if (self.trying_to_flush) { return 0; } } var data = data_; if (self.write_tmp_buffer_len >= BUFFER_SIZE) { dbgLog("buffer is full", .{}); return 0; } dbgLog("bufferedWrite ptr {}, len {}", .{ data_.ptr, data_.len }); var written: u32 = 0; if (self.write_tmp_buffer_len > 0 and self.write_tmp_buffer_len + data.len >= BUFFER_SIZE) { // About to go over BUFFER_SIZE bytes // Write up to the end of the buffer const l = BUFFER_SIZE - self.write_tmp_buffer_len; try linked_buffer_obj.addData(&self.write_tmp_buffer, &self.write_tmp_buffer_len, data[0..l]); written += l; data = data[l..]; try self.flushWrite(conn); if (self.trying_to_flush) { // Data is still in buffer. Cannot write any more just yet. dbgLog("Waiting on TCP send.", .{}); return written; } } if (self.write_tmp_buffer_len == 0) { while (data.len >= BUFFER_SIZE) { dbgLog("Sending [BUFFER_SIZE={}] bytes of data.", .{BUFFER_SIZE}); if (!(try self.sendData(conn, data[0..BUFFER_SIZE]))) { dbgLog("Waiting on TCP send.", .{}); return written; } written += BUFFER_SIZE; data = data[BUFFER_SIZE..]; } } if (data.len > 0 and data.len < BUFFER_SIZE) { dbgLog("Storing {} bytes of data in TLS buffer", .{data.len}); try linked_buffer_obj.addData(&self.write_tmp_buffer, &self.write_tmp_buffer_len, data); written += @intCast(u32, data.len); } return written; } pub fn bufferedWriteG(self: *TLSConnection, conn: usize, data: []const u8) !void { const success = (try self.bufferedWrite(conn, data)) == data.len; assert(success); if (!success) { return error.BufferedWriteGError; } } // returns true if data is now being sent, false if need to wait for data to be received (data is not sent) // data slice does not need to remain valid. It is encrypted and stored. // failed writes must be retried // Do not call this. Use bufferedWrite() fn sendData(self: *TLSConnection, conn: usize, data: []const u8) !bool { if (self.ssl == null) { assert(false); return error.SSLConnFreed; } if (!self.bio.canSendData(@intCast(u32, data.len))) { dbgLog("Cannot send right now, waiting on BIO", .{}); return false; } dbgLog("send len={} ptr = {}\n", .{ data.len, data.ptr }); dbgLog("send: {}\n", .{data[0..std.math.min(450, data.len)]}); if (!(self.prev_write_command_fail == null or (self.prev_write_command_fail.?.ptr == data.ptr and self.prev_write_command_fail.?.len == data.len))) { assert(false); return error.InvalidWriteRetry; } assert(self.prev_write_command_fail == null or (self.prev_write_command_fail.?.ptr == data.ptr and self.prev_write_command_fail.?.len == data.len)); self.prev_write_command_fail = null; errdefer self.deinit(conn); openssl.ERR_clear_error(); const w = openssl.SSL_write(self.ssl.?, data.ptr, @intCast(c_int, data.len)); if (w != data.len) { const e = openssl.SSL_get_error(self.ssl.?, w); if (e == openssl.SSL_ERROR_WANT_READ or e == openssl.SSL_ERROR_WANT_WRITE) { dbgLog("SSL_Write SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE w={}, e={}", .{ w, e }); self.prev_write_command_fail = data; return false; } else { errLog("ssl write error = {}, return val was {}", .{ e, w }); printErrors(); _ = self.checkFatalError(e); return error.OpenSSLError; } } return true; } fn flushWrite_(self: *TLSConnection, conn: usize) !void { if (self.ssl == null) { assert(false); return error.SSLConnFreed; } errdefer self.deinit(conn); dbgLog("flushWrite. self.write_tmp_buffer_len={}", .{self.write_tmp_buffer_len}); if (self.write_tmp_buffer_len > 0) { assert(self.write_tmp_buffer.?.next == null); if (try self.sendData(conn, self.write_tmp_buffer.?.data[0..self.write_tmp_buffer_len])) { dbgLog("flushWrite data sent success", .{}); self.write_tmp_buffer_len = 0; linked_buffer_obj.freeBufferChain(&self.write_tmp_buffer.?); self.write_tmp_buffer = null; self.trying_to_flush = false; } else { self.trying_to_flush = true; } } else { self.trying_to_flush = false; } } pub fn flushWriteAndShutdown(self: *TLSConnection, conn: usize) !void { try self.flushWrite_(conn); if (!self.trying_to_flush) { try self.shutdown(conn); } } pub fn flushWrite(self: *TLSConnection, conn: usize) !void { try self.flushWrite_(conn); self.bio.flush(conn) catch {}; } // Called when a write on the TCP stream has completed successfully pub fn writeDone(self: *TLSConnection, conn: usize, data: []const u8) !void { if (self.ssl == null) { assert(false); } dbgLog("write done", .{}); self.bio.writeDone(conn, data); try self.flushWrite(conn); if (self.shutdown_in_progress) { try self.shutdown(conn); } } // data_in is the encrypted data (from TCPServer.zig) // Remember to call readReset() or buffer won't be emptied // Data is in self.read_buffer // Returns number of bytes read into self.read_buffer or 0 if handshake is being done // Returns error.ConnectionClosed if connection is closed. pub fn read(self: *TLSConnection, conn: usize, data_in: []const u8) !u32 { if (self.ssl == null) { assert(false); return error.SSLConnFreed; } if (self.shutdown_in_progress) { try self.shutdown(conn); return 0; } errdefer self.deinit(conn); self.bio.next_read_data = data_in; if (!self.ssl_accept_finished) { openssl.ERR_clear_error(); const accept_result = openssl.SSL_accept(self.ssl.?); if (accept_result == 0) { errLog("ssl accept error", .{}); return error.OpenSSLError; } self.ssl_accept_finished = accept_result == 1; if (!self.ssl_accept_finished) { // accept_result < 0 const e = openssl.SSL_get_error(self.ssl.?, accept_result); if (e != openssl.SSL_ERROR_WANT_READ and e != openssl.SSL_ERROR_WANT_WRITE) { errLog("ssl accept error = {}, return val was {}", .{ e, accept_result }); printErrors(); _ = self.checkFatalError(e); return error.OpenSSLError; } } } if (self.ssl_accept_finished and self.bio.next_read_data != null) { self.read_buffer = try linked_buffer_obj.newBufferChain(); var buffer = &self.read_buffer.?; while (true) { openssl.ERR_clear_error(); const dst = buffer.data[(self.data_read % BUFFER_SIZE)..]; const r = openssl.SSL_read(self.ssl.?, dst.ptr, @intCast(c_int, dst.len)); if (r <= 0) { const e = openssl.SSL_get_error(self.ssl.?, r); if (e == openssl.SSL_ERROR_ZERO_RETURN) { return error.ConnectionClosed; } if (e != openssl.SSL_ERROR_WANT_READ and e != openssl.SSL_ERROR_WANT_WRITE) { errLog("ssl read error = {}, return val was {}", .{ e, r }); printErrors(); _ = self.checkFatalError(e); return error.OpenSSLError; } else if (e == openssl.SSL_ERROR_WANT_READ) { dbgLog("SSL_read SSL_ERROR_WANT_READ", .{}); } else if (e == openssl.SSL_ERROR_WANT_WRITE) { dbgLog("SSL_read SSL_ERROR_WANT_WRITE", .{}); } break; } else { // No error self.data_read += @intCast(u32, r); if (self.bio.next_read_data == null) { // No more data break; } // More data to go if (self.data_read % BUFFER_SIZE == 0) { buffer = try linked_buffer_obj.addToChain(buffer); } } } try self.flushWrite(conn); assert(self.bio.next_read_data == null or self.bio.next_read_data.?.len == 0); return self.data_read; } try self.flushWrite(conn); assert(self.bio.next_read_data == null or self.bio.next_read_data.?.len == 0); return 0; } // Call when done with the data from read() pub fn resetRead(self: *TLSConnection) void { if (self.ssl == null) { assert(false); } if (self.read_buffer != null) { linked_buffer_obj.freeBufferChain(&self.read_buffer.?); self.read_buffer = null; self.data_read = 0; } } // Server-initiated shutdown pub fn shutdown(self: *TLSConnection, conn: usize) !void { if (self.ssl == null) { assert(false); } self.shutdown_in_progress = true; if (self.trying_to_flush) { try self.flushWrite(conn); if (self.trying_to_flush) { return; } } const r = openssl.SSL_shutdown(self.ssl.?); self.bio.flush(conn) catch {}; return error.TLSShutDown; } pub fn deinit(self: *TLSConnection, conn: usize) void { if (self.ssl != null) { self.resetRead(); if (self.write_tmp_buffer != null) { linked_buffer_obj.freeBufferChain(&self.write_tmp_buffer.?); self.write_tmp_buffer = null; } openssl.SSL_free(self.ssl.?); self.ssl = null; } } };
src/TLS.zig
const std = @import("std"); const sqlite = @import("sqlite"); const manage_main = @import("main.zig"); const libpcre = @import("libpcre"); const Context = manage_main.Context; const log = std.log.scoped(.als); const VERSION = "0.0.1"; const HELPTEXT = \\ als: list file tags \\ \\ usage: \\ als path \\ \\ options: \\ -h prints this help and exits \\ -V prints version and exits \\ \\ examples: \\ als path/to/file \\ shows tags about a single file \\ als path/to/directory \\ shows files and their respective tags inside a directory ; pub fn main() anyerror!void { const rc = sqlite.c.sqlite3_config(sqlite.c.SQLITE_CONFIG_LOG, manage_main.sqliteLog, @as(?*anyopaque, null)); if (rc != sqlite.c.SQLITE_OK) { std.log.err("failed to configure: {d} '{s}'", .{ rc, sqlite.c.sqlite3_errstr(rc), }); return error.ConfigFail; } var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); var allocator = gpa.allocator(); var args_it = std.process.args(); _ = args_it.skip(); const Args = struct { help: bool = false, version: bool = false, query: ?[]const u8 = null, }; var given_args = Args{}; while (args_it.next()) |arg| { if (std.mem.eql(u8, arg, "-h")) { given_args.help = true; } else if (std.mem.eql(u8, arg, "-V")) { given_args.version = true; } else { given_args.query = arg; } } if (given_args.help) { std.debug.print(HELPTEXT, .{}); return; } else if (given_args.version) { std.debug.print("ainclude {s}\n", .{VERSION}); return; } const query = given_args.query orelse "."; var ctx = Context{ .home_path = null, .args_it = undefined, .stdout = undefined, .db = null, .allocator = allocator, }; defer ctx.deinit(); try ctx.loadDatabase(.{}); var stdout = std.io.getStdOut().writer(); var maybe_dir = std.fs.cwd().openDir(query, .{ .iterate = true }) catch |err| switch (err) { error.FileNotFound => { log.err("path not found: {s}", .{query}); return err; }, error.NotDir => blk: { break :blk null; }, else => return err, }; if (maybe_dir) |dir| { var it = dir.iterate(); while (try it.next()) |entry| { // TODO get stat? switch (entry.kind) { .File => try stdout.print("-", .{}), .Directory => try stdout.print("d", .{}), else => try stdout.print("-", .{}), } try stdout.print(" {s}", .{entry.name}); if (entry.kind == .File) { var realpath_buf: [std.os.PATH_MAX]u8 = undefined; const full_path = try dir.realpath(entry.name, &realpath_buf); var maybe_inner_file = try ctx.fetchFileByPath(full_path); if (maybe_inner_file) |*file| { defer file.deinit(); try file.printTagsTo(allocator, stdout); } } try stdout.print("\n", .{}); } } else { var realpath_buf: [std.os.PATH_MAX]u8 = undefined; const full_path = try std.fs.cwd().realpath(query, &realpath_buf); const maybe_file = try ctx.fetchFileByPath(full_path); try stdout.print("- {s}", .{query}); if (maybe_file) |file| { defer file.deinit(); try file.printTagsTo(allocator, stdout); } try stdout.print("\n", .{}); } }
src/ls_main.zig
pub const PROP_ID_SECURE_MIN = @as(u32, 26608); pub const PROP_ID_SECURE_MAX = @as(u32, 26623); pub const MAPI_DIM = @as(u32, 1); pub const MAPI_P1 = @as(u32, 268435456); pub const MAPI_SUBMITTED = @as(u32, 2147483648); pub const MAPI_SHORTTERM = @as(u32, 128); pub const MAPI_NOTRECIP = @as(u32, 64); pub const MAPI_THISSESSION = @as(u32, 32); pub const MAPI_NOW = @as(u32, 16); pub const MAPI_NOTRESERVED = @as(u32, 8); pub const MAPI_COMPOUND = @as(u32, 128); pub const MV_FLAG = @as(u32, 4096); pub const PROP_ID_NULL = @as(u32, 0); pub const PROP_ID_INVALID = @as(u32, 65535); pub const MV_INSTANCE = @as(u32, 8192); pub const TABLE_CHANGED = @as(u32, 1); pub const TABLE_ERROR = @as(u32, 2); pub const TABLE_ROW_ADDED = @as(u32, 3); pub const TABLE_ROW_DELETED = @as(u32, 4); pub const TABLE_ROW_MODIFIED = @as(u32, 5); pub const TABLE_SORT_DONE = @as(u32, 6); pub const TABLE_RESTRICT_DONE = @as(u32, 7); pub const TABLE_SETCOL_DONE = @as(u32, 8); pub const TABLE_RELOAD = @as(u32, 9); pub const MAPI_ERROR_VERSION = @as(i32, 0); pub const MAPI_USE_DEFAULT = @as(u32, 64); pub const MNID_ID = @as(u32, 0); pub const MNID_STRING = @as(u32, 1); pub const WAB_LOCAL_CONTAINERS = @as(u32, 1048576); pub const WAB_PROFILE_CONTENTS = @as(u32, 2097152); pub const WAB_IGNORE_PROFILES = @as(u32, 8388608); pub const MAPI_ONE_OFF_NO_RICH_INFO = @as(u32, 1); pub const UI_SERVICE = @as(u32, 2); pub const SERVICE_UI_ALWAYS = @as(u32, 2); pub const SERVICE_UI_ALLOWED = @as(u32, 16); pub const UI_CURRENT_PROVIDER_FIRST = @as(u32, 4); pub const WABOBJECT_LDAPURL_RETURN_MAILUSER = @as(u32, 1); pub const WABOBJECT_ME_NEW = @as(u32, 1); pub const WABOBJECT_ME_NOCREATE = @as(u32, 2); pub const WAB_VCARD_FILE = @as(u32, 0); pub const WAB_VCARD_STREAM = @as(u32, 1); pub const WAB_USE_OE_SENDMAIL = @as(u32, 1); pub const WAB_ENABLE_PROFILES = @as(u32, 4194304); pub const WAB_DISPLAY_LDAPURL = @as(u32, 1); pub const WAB_CONTEXT_ADRLIST = @as(u32, 2); pub const WAB_DISPLAY_ISNTDS = @as(u32, 4); //-------------------------------------------------------------------------------- // Section: Types (115) //-------------------------------------------------------------------------------- pub const _WABACTIONITEM = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const ENTRYID = extern struct { abFlags: [4]u8, ab: [1]u8, }; pub const MAPIUID = extern struct { ab: [16]u8, }; pub const SPropTagArray = extern struct { cValues: u32, aulPropTag: [1]u32, }; pub const SBinary = extern struct { cb: u32, lpb: ?*u8, }; pub const SShortArray = extern struct { cValues: u32, lpi: ?*i16, }; pub const SGuidArray = extern struct { cValues: u32, lpguid: ?*Guid, }; pub const SRealArray = extern struct { cValues: u32, lpflt: ?*f32, }; pub const SLongArray = extern struct { cValues: u32, lpl: ?*i32, }; pub const SLargeIntegerArray = extern struct { cValues: u32, lpli: ?*LARGE_INTEGER, }; pub const SDateTimeArray = extern struct { cValues: u32, lpft: ?*FILETIME, }; pub const SAppTimeArray = extern struct { cValues: u32, lpat: ?*f64, }; pub const SCurrencyArray = extern struct { cValues: u32, lpcur: ?*CY, }; pub const SBinaryArray = extern struct { cValues: u32, lpbin: ?*SBinary, }; pub const SDoubleArray = extern struct { cValues: u32, lpdbl: ?*f64, }; pub const SWStringArray = extern struct { cValues: u32, lppszW: ?*?PWSTR, }; pub const SLPSTRArray = extern struct { cValues: u32, lppszA: ?*?PSTR, }; pub const _PV = extern union { i: i16, l: i32, ul: u32, flt: f32, dbl: f64, b: u16, cur: CY, at: f64, ft: FILETIME, lpszA: ?PSTR, bin: SBinary, lpszW: ?PWSTR, lpguid: ?*Guid, li: LARGE_INTEGER, MVi: SShortArray, MVl: SLongArray, MVflt: SRealArray, MVdbl: SDoubleArray, MVcur: SCurrencyArray, MVat: SAppTimeArray, MVft: SDateTimeArray, MVbin: SBinaryArray, MVszA: SLPSTRArray, MVszW: SWStringArray, MVguid: SGuidArray, MVli: SLargeIntegerArray, err: i32, x: i32, }; pub const SPropValue = extern struct { ulPropTag: u32, dwAlignPad: u32, Value: _PV, }; pub const SPropProblem = extern struct { ulIndex: u32, ulPropTag: u32, scode: i32, }; pub const SPropProblemArray = extern struct { cProblem: u32, aProblem: [1]SPropProblem, }; pub const FLATENTRY = extern struct { cb: u32, abEntry: [1]u8, }; pub const FLATENTRYLIST = extern struct { cEntries: u32, cbEntries: u32, abEntries: [1]u8, }; pub const MTSID = extern struct { cb: u32, ab: [1]u8, }; pub const FLATMTSIDLIST = extern struct { cMTSIDs: u32, cbMTSIDs: u32, abMTSIDs: [1]u8, }; pub const ADRENTRY = extern struct { ulReserved1: u32, cValues: u32, rgPropVals: ?*SPropValue, }; pub const ADRLIST = extern struct { cEntries: u32, aEntries: [1]ADRENTRY, }; pub const SRow = extern struct { ulAdrEntryPad: u32, cValues: u32, lpProps: ?*SPropValue, }; pub const SRowSet = extern struct { cRows: u32, aRow: [1]SRow, }; pub const LPALLOCATEBUFFER = fn( cbSize: u32, lppBuffer: ?*?*c_void, ) callconv(@import("std").os.windows.WINAPI) i32; pub const LPALLOCATEMORE = fn( cbSize: u32, lpObject: ?*c_void, lppBuffer: ?*?*c_void, ) callconv(@import("std").os.windows.WINAPI) i32; pub const LPFREEBUFFER = fn( lpBuffer: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) u32; pub const MAPIERROR = extern struct { ulVersion: u32, lpszError: ?*i8, lpszComponent: ?*i8, ulLowLevelError: u32, ulContext: u32, }; pub const ERROR_NOTIFICATION = extern struct { cbEntryID: u32, lpEntryID: ?*ENTRYID, scode: i32, ulFlags: u32, lpMAPIError: ?*MAPIERROR, }; pub const NEWMAIL_NOTIFICATION = extern struct { cbEntryID: u32, lpEntryID: ?*ENTRYID, cbParentID: u32, lpParentID: ?*ENTRYID, ulFlags: u32, lpszMessageClass: ?*i8, ulMessageFlags: u32, }; pub const OBJECT_NOTIFICATION = extern struct { cbEntryID: u32, lpEntryID: ?*ENTRYID, ulObjType: u32, cbParentID: u32, lpParentID: ?*ENTRYID, cbOldID: u32, lpOldID: ?*ENTRYID, cbOldParentID: u32, lpOldParentID: ?*ENTRYID, lpPropTagArray: ?*SPropTagArray, }; pub const TABLE_NOTIFICATION = extern struct { ulTableEvent: u32, hResult: HRESULT, propIndex: SPropValue, propPrior: SPropValue, row: SRow, ulPad: u32, }; pub const EXTENDED_NOTIFICATION = extern struct { ulEvent: u32, cb: u32, pbEventParameters: ?*u8, }; pub const STATUS_OBJECT_NOTIFICATION = extern struct { cbEntryID: u32, lpEntryID: ?*ENTRYID, cValues: u32, lpPropVals: ?*SPropValue, }; pub const NOTIFICATION = extern struct { ulEventType: u32, ulAlignPad: u32, info: extern union { err: ERROR_NOTIFICATION, newmail: NEWMAIL_NOTIFICATION, obj: OBJECT_NOTIFICATION, tab: TABLE_NOTIFICATION, ext: EXTENDED_NOTIFICATION, statobj: STATUS_OBJECT_NOTIFICATION, }, }; pub const IMAPIAdviseSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnNotify: fn( self: *const IMAPIAdviseSink, cNotif: u32, lpNotifications: ?*NOTIFICATION, ) callconv(@import("std").os.windows.WINAPI) u32, }; 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 IMAPIAdviseSink_OnNotify(self: *const T, cNotif: u32, lpNotifications: ?*NOTIFICATION) callconv(.Inline) u32 { return @ptrCast(*const IMAPIAdviseSink.VTable, self.vtable).OnNotify(@ptrCast(*const IMAPIAdviseSink, self), cNotif, lpNotifications); } };} pub usingnamespace MethodMixin(@This()); }; pub const LPNOTIFCALLBACK = fn( lpvContext: ?*c_void, cNotification: u32, lpNotifications: ?*NOTIFICATION, ) callconv(@import("std").os.windows.WINAPI) i32; pub const IMAPIProgress = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Progress: fn( self: *const IMAPIProgress, ulValue: u32, ulCount: u32, ulTotal: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFlags: fn( self: *const IMAPIProgress, lpulFlags: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMax: fn( self: *const IMAPIProgress, lpulMax: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMin: fn( self: *const IMAPIProgress, lpulMin: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetLimits: fn( self: *const IMAPIProgress, lpulMin: ?*u32, lpulMax: ?*u32, lpulFlags: ?*u32, ) 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 IMAPIProgress_Progress(self: *const T, ulValue: u32, ulCount: u32, ulTotal: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProgress.VTable, self.vtable).Progress(@ptrCast(*const IMAPIProgress, self), ulValue, ulCount, ulTotal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProgress_GetFlags(self: *const T, lpulFlags: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProgress.VTable, self.vtable).GetFlags(@ptrCast(*const IMAPIProgress, self), lpulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProgress_GetMax(self: *const T, lpulMax: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProgress.VTable, self.vtable).GetMax(@ptrCast(*const IMAPIProgress, self), lpulMax); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProgress_GetMin(self: *const T, lpulMin: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProgress.VTable, self.vtable).GetMin(@ptrCast(*const IMAPIProgress, self), lpulMin); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProgress_SetLimits(self: *const T, lpulMin: ?*u32, lpulMax: ?*u32, lpulFlags: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProgress.VTable, self.vtable).SetLimits(@ptrCast(*const IMAPIProgress, self), lpulMin, lpulMax, lpulFlags); } };} pub usingnamespace MethodMixin(@This()); }; pub const MAPINAMEID = extern struct { lpguid: ?*Guid, ulKind: u32, Kind: extern union { lID: i32, lpwstrName: ?PWSTR, }, }; pub const IMAPIProp = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetLastError: fn( self: *const IMAPIProp, hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SaveChanges: fn( self: *const IMAPIProp, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProps: fn( self: *const IMAPIProp, lpPropTagArray: ?*SPropTagArray, ulFlags: u32, lpcValues: ?*u32, lppPropArray: ?*?*SPropValue, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPropList: fn( self: *const IMAPIProp, ulFlags: u32, lppPropTagArray: ?*?*SPropTagArray, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenProperty: fn( self: *const IMAPIProp, ulPropTag: u32, lpiid: ?*Guid, ulInterfaceOptions: u32, ulFlags: u32, lppUnk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetProps: fn( self: *const IMAPIProp, cValues: u32, lpPropArray: ?*SPropValue, lppProblems: ?*?*SPropProblemArray, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteProps: fn( self: *const IMAPIProp, lpPropTagArray: ?*SPropTagArray, lppProblems: ?*?*SPropProblemArray, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyTo: fn( self: *const IMAPIProp, ciidExclude: u32, rgiidExclude: ?*Guid, lpExcludeProps: ?*SPropTagArray, ulUIParam: usize, lpProgress: ?*IMAPIProgress, lpInterface: ?*Guid, lpDestObj: ?*c_void, ulFlags: u32, lppProblems: ?*?*SPropProblemArray, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyProps: fn( self: *const IMAPIProp, lpIncludeProps: ?*SPropTagArray, ulUIParam: usize, lpProgress: ?*IMAPIProgress, lpInterface: ?*Guid, lpDestObj: ?*c_void, ulFlags: u32, lppProblems: ?*?*SPropProblemArray, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNamesFromIDs: fn( self: *const IMAPIProp, lppPropTags: ?*?*SPropTagArray, lpPropSetGuid: ?*Guid, ulFlags: u32, lpcPropNames: ?*u32, lpppPropNames: ?*?*?*MAPINAMEID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetIDsFromNames: fn( self: *const IMAPIProp, cPropNames: u32, lppPropNames: ?*?*MAPINAMEID, ulFlags: u32, lppPropTags: ?*?*SPropTagArray, ) 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 IMAPIProp_GetLastError(self: *const T, hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProp.VTable, self.vtable).GetLastError(@ptrCast(*const IMAPIProp, self), hResult, ulFlags, lppMAPIError); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProp_SaveChanges(self: *const T, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProp.VTable, self.vtable).SaveChanges(@ptrCast(*const IMAPIProp, self), ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProp_GetProps(self: *const T, lpPropTagArray: ?*SPropTagArray, ulFlags: u32, lpcValues: ?*u32, lppPropArray: ?*?*SPropValue) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProp.VTable, self.vtable).GetProps(@ptrCast(*const IMAPIProp, self), lpPropTagArray, ulFlags, lpcValues, lppPropArray); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProp_GetPropList(self: *const T, ulFlags: u32, lppPropTagArray: ?*?*SPropTagArray) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProp.VTable, self.vtable).GetPropList(@ptrCast(*const IMAPIProp, self), ulFlags, lppPropTagArray); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProp_OpenProperty(self: *const T, ulPropTag: u32, lpiid: ?*Guid, ulInterfaceOptions: u32, ulFlags: u32, lppUnk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProp.VTable, self.vtable).OpenProperty(@ptrCast(*const IMAPIProp, self), ulPropTag, lpiid, ulInterfaceOptions, ulFlags, lppUnk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProp_SetProps(self: *const T, cValues: u32, lpPropArray: ?*SPropValue, lppProblems: ?*?*SPropProblemArray) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProp.VTable, self.vtable).SetProps(@ptrCast(*const IMAPIProp, self), cValues, lpPropArray, lppProblems); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProp_DeleteProps(self: *const T, lpPropTagArray: ?*SPropTagArray, lppProblems: ?*?*SPropProblemArray) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProp.VTable, self.vtable).DeleteProps(@ptrCast(*const IMAPIProp, self), lpPropTagArray, lppProblems); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProp_CopyTo(self: *const T, ciidExclude: u32, rgiidExclude: ?*Guid, lpExcludeProps: ?*SPropTagArray, ulUIParam: usize, lpProgress: ?*IMAPIProgress, lpInterface: ?*Guid, lpDestObj: ?*c_void, ulFlags: u32, lppProblems: ?*?*SPropProblemArray) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProp.VTable, self.vtable).CopyTo(@ptrCast(*const IMAPIProp, self), ciidExclude, rgiidExclude, lpExcludeProps, ulUIParam, lpProgress, lpInterface, lpDestObj, ulFlags, lppProblems); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProp_CopyProps(self: *const T, lpIncludeProps: ?*SPropTagArray, ulUIParam: usize, lpProgress: ?*IMAPIProgress, lpInterface: ?*Guid, lpDestObj: ?*c_void, ulFlags: u32, lppProblems: ?*?*SPropProblemArray) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProp.VTable, self.vtable).CopyProps(@ptrCast(*const IMAPIProp, self), lpIncludeProps, ulUIParam, lpProgress, lpInterface, lpDestObj, ulFlags, lppProblems); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProp_GetNamesFromIDs(self: *const T, lppPropTags: ?*?*SPropTagArray, lpPropSetGuid: ?*Guid, ulFlags: u32, lpcPropNames: ?*u32, lpppPropNames: ?*?*?*MAPINAMEID) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProp.VTable, self.vtable).GetNamesFromIDs(@ptrCast(*const IMAPIProp, self), lppPropTags, lpPropSetGuid, ulFlags, lpcPropNames, lpppPropNames); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProp_GetIDsFromNames(self: *const T, cPropNames: u32, lppPropNames: ?*?*MAPINAMEID, ulFlags: u32, lppPropTags: ?*?*SPropTagArray) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProp.VTable, self.vtable).GetIDsFromNames(@ptrCast(*const IMAPIProp, self), cPropNames, lppPropNames, ulFlags, lppPropTags); } };} pub usingnamespace MethodMixin(@This()); }; pub const SSortOrder = extern struct { ulPropTag: u32, ulOrder: u32, }; pub const SSortOrderSet = extern struct { cSorts: u32, cCategories: u32, cExpanded: u32, aSort: [1]SSortOrder, }; pub const SAndRestriction = extern struct { cRes: u32, lpRes: ?*SRestriction, }; pub const SOrRestriction = extern struct { cRes: u32, lpRes: ?*SRestriction, }; pub const SNotRestriction = extern struct { ulReserved: u32, lpRes: ?*SRestriction, }; pub const SContentRestriction = extern struct { ulFuzzyLevel: u32, ulPropTag: u32, lpProp: ?*SPropValue, }; pub const SBitMaskRestriction = extern struct { relBMR: u32, ulPropTag: u32, ulMask: u32, }; pub const SPropertyRestriction = extern struct { relop: u32, ulPropTag: u32, lpProp: ?*SPropValue, }; pub const SComparePropsRestriction = extern struct { relop: u32, ulPropTag1: u32, ulPropTag2: u32, }; pub const SSizeRestriction = extern struct { relop: u32, ulPropTag: u32, cb: u32, }; pub const SExistRestriction = extern struct { ulReserved1: u32, ulPropTag: u32, ulReserved2: u32, }; pub const SSubRestriction = extern struct { ulSubObject: u32, lpRes: ?*SRestriction, }; pub const SCommentRestriction = extern struct { cValues: u32, lpRes: ?*SRestriction, lpProp: ?*SPropValue, }; pub const SRestriction = extern struct { rt: u32, res: extern union { resCompareProps: SComparePropsRestriction, resAnd: SAndRestriction, resOr: SOrRestriction, resNot: SNotRestriction, resContent: SContentRestriction, resProperty: SPropertyRestriction, resBitMask: SBitMaskRestriction, resSize: SSizeRestriction, resExist: SExistRestriction, resSub: SSubRestriction, resComment: SCommentRestriction, }, }; // TODO: this type is limited to platform 'windows5.0' pub const IMAPITable = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetLastError: fn( self: *const IMAPITable, hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Advise: fn( self: *const IMAPITable, ulEventMask: u32, lpAdviseSink: ?*IMAPIAdviseSink, lpulConnection: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Unadvise: fn( self: *const IMAPITable, ulConnection: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStatus: fn( self: *const IMAPITable, lpulTableStatus: ?*u32, lpulTableType: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetColumns: fn( self: *const IMAPITable, lpPropTagArray: ?*SPropTagArray, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryColumns: fn( self: *const IMAPITable, ulFlags: u32, lpPropTagArray: ?*?*SPropTagArray, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRowCount: fn( self: *const IMAPITable, ulFlags: u32, lpulCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SeekRow: fn( self: *const IMAPITable, bkOrigin: u32, lRowCount: i32, lplRowsSought: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SeekRowApprox: fn( self: *const IMAPITable, ulNumerator: u32, ulDenominator: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryPosition: fn( self: *const IMAPITable, lpulRow: ?*u32, lpulNumerator: ?*u32, lpulDenominator: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FindRow: fn( self: *const IMAPITable, lpRestriction: ?*SRestriction, bkOrigin: u32, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Restrict: fn( self: *const IMAPITable, lpRestriction: ?*SRestriction, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateBookmark: fn( self: *const IMAPITable, lpbkPosition: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FreeBookmark: fn( self: *const IMAPITable, bkPosition: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SortTable: fn( self: *const IMAPITable, lpSortCriteria: ?*SSortOrderSet, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QuerySortOrder: fn( self: *const IMAPITable, lppSortCriteria: ?*?*SSortOrderSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryRows: fn( self: *const IMAPITable, lRowCount: i32, ulFlags: u32, lppRows: ?*?*SRowSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Abort: fn( self: *const IMAPITable, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ExpandRow: fn( self: *const IMAPITable, cbInstanceKey: u32, pbInstanceKey: ?*u8, ulRowCount: u32, ulFlags: u32, lppRows: ?*?*SRowSet, lpulMoreRows: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CollapseRow: fn( self: *const IMAPITable, cbInstanceKey: u32, pbInstanceKey: ?*u8, ulFlags: u32, lpulRowCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WaitForCompletion: fn( self: *const IMAPITable, ulFlags: u32, ulTimeout: u32, lpulTableStatus: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCollapseState: fn( self: *const IMAPITable, ulFlags: u32, cbInstanceKey: u32, lpbInstanceKey: ?*u8, lpcbCollapseState: ?*u32, lppbCollapseState: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetCollapseState: fn( self: *const IMAPITable, ulFlags: u32, cbCollapseState: u32, pbCollapseState: ?*u8, lpbkLocation: ?*u32, ) 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 IMAPITable_GetLastError(self: *const T, hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).GetLastError(@ptrCast(*const IMAPITable, self), hResult, ulFlags, lppMAPIError); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_Advise(self: *const T, ulEventMask: u32, lpAdviseSink: ?*IMAPIAdviseSink, lpulConnection: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).Advise(@ptrCast(*const IMAPITable, self), ulEventMask, lpAdviseSink, lpulConnection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_Unadvise(self: *const T, ulConnection: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).Unadvise(@ptrCast(*const IMAPITable, self), ulConnection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_GetStatus(self: *const T, lpulTableStatus: ?*u32, lpulTableType: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).GetStatus(@ptrCast(*const IMAPITable, self), lpulTableStatus, lpulTableType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_SetColumns(self: *const T, lpPropTagArray: ?*SPropTagArray, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).SetColumns(@ptrCast(*const IMAPITable, self), lpPropTagArray, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_QueryColumns(self: *const T, ulFlags: u32, lpPropTagArray: ?*?*SPropTagArray) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).QueryColumns(@ptrCast(*const IMAPITable, self), ulFlags, lpPropTagArray); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_GetRowCount(self: *const T, ulFlags: u32, lpulCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).GetRowCount(@ptrCast(*const IMAPITable, self), ulFlags, lpulCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_SeekRow(self: *const T, bkOrigin: u32, lRowCount: i32, lplRowsSought: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).SeekRow(@ptrCast(*const IMAPITable, self), bkOrigin, lRowCount, lplRowsSought); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_SeekRowApprox(self: *const T, ulNumerator: u32, ulDenominator: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).SeekRowApprox(@ptrCast(*const IMAPITable, self), ulNumerator, ulDenominator); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_QueryPosition(self: *const T, lpulRow: ?*u32, lpulNumerator: ?*u32, lpulDenominator: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).QueryPosition(@ptrCast(*const IMAPITable, self), lpulRow, lpulNumerator, lpulDenominator); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_FindRow(self: *const T, lpRestriction: ?*SRestriction, bkOrigin: u32, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).FindRow(@ptrCast(*const IMAPITable, self), lpRestriction, bkOrigin, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_Restrict(self: *const T, lpRestriction: ?*SRestriction, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).Restrict(@ptrCast(*const IMAPITable, self), lpRestriction, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_CreateBookmark(self: *const T, lpbkPosition: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).CreateBookmark(@ptrCast(*const IMAPITable, self), lpbkPosition); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_FreeBookmark(self: *const T, bkPosition: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).FreeBookmark(@ptrCast(*const IMAPITable, self), bkPosition); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_SortTable(self: *const T, lpSortCriteria: ?*SSortOrderSet, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).SortTable(@ptrCast(*const IMAPITable, self), lpSortCriteria, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_QuerySortOrder(self: *const T, lppSortCriteria: ?*?*SSortOrderSet) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).QuerySortOrder(@ptrCast(*const IMAPITable, self), lppSortCriteria); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_QueryRows(self: *const T, lRowCount: i32, ulFlags: u32, lppRows: ?*?*SRowSet) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).QueryRows(@ptrCast(*const IMAPITable, self), lRowCount, ulFlags, lppRows); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_Abort(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).Abort(@ptrCast(*const IMAPITable, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_ExpandRow(self: *const T, cbInstanceKey: u32, pbInstanceKey: ?*u8, ulRowCount: u32, ulFlags: u32, lppRows: ?*?*SRowSet, lpulMoreRows: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).ExpandRow(@ptrCast(*const IMAPITable, self), cbInstanceKey, pbInstanceKey, ulRowCount, ulFlags, lppRows, lpulMoreRows); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_CollapseRow(self: *const T, cbInstanceKey: u32, pbInstanceKey: ?*u8, ulFlags: u32, lpulRowCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).CollapseRow(@ptrCast(*const IMAPITable, self), cbInstanceKey, pbInstanceKey, ulFlags, lpulRowCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_WaitForCompletion(self: *const T, ulFlags: u32, ulTimeout: u32, lpulTableStatus: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).WaitForCompletion(@ptrCast(*const IMAPITable, self), ulFlags, ulTimeout, lpulTableStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_GetCollapseState(self: *const T, ulFlags: u32, cbInstanceKey: u32, lpbInstanceKey: ?*u8, lpcbCollapseState: ?*u32, lppbCollapseState: ?*?*u8) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).GetCollapseState(@ptrCast(*const IMAPITable, self), ulFlags, cbInstanceKey, lpbInstanceKey, lpcbCollapseState, lppbCollapseState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_SetCollapseState(self: *const T, ulFlags: u32, cbCollapseState: u32, pbCollapseState: ?*u8, lpbkLocation: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).SetCollapseState(@ptrCast(*const IMAPITable, self), ulFlags, cbCollapseState, pbCollapseState, lpbkLocation); } };} pub usingnamespace MethodMixin(@This()); }; pub const IProfSect = extern struct { pub const VTable = extern struct { base: IMAPIProp.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IMAPIProp.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; pub const IMAPIStatus = extern struct { pub const VTable = extern struct { base: IMAPIProp.VTable, ValidateState: fn( self: *const IMAPIStatus, ulUIParam: usize, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SettingsDialog: fn( self: *const IMAPIStatus, ulUIParam: usize, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ChangePassword: fn( self: *const IMAPIStatus, lpOldPass: ?*i8, lpNewPass: ?*i8, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FlushQueues: fn( self: *const IMAPIStatus, ulUIParam: usize, cbTargetTransport: u32, lpTargetTransport: ?[*]ENTRYID, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IMAPIProp.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIStatus_ValidateState(self: *const T, ulUIParam: usize, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIStatus.VTable, self.vtable).ValidateState(@ptrCast(*const IMAPIStatus, self), ulUIParam, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIStatus_SettingsDialog(self: *const T, ulUIParam: usize, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIStatus.VTable, self.vtable).SettingsDialog(@ptrCast(*const IMAPIStatus, self), ulUIParam, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIStatus_ChangePassword(self: *const T, lpOldPass: ?*i8, lpNewPass: ?*i8, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIStatus.VTable, self.vtable).ChangePassword(@ptrCast(*const IMAPIStatus, self), lpOldPass, lpNewPass, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIStatus_FlushQueues(self: *const T, ulUIParam: usize, cbTargetTransport: u32, lpTargetTransport: ?[*]ENTRYID, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIStatus.VTable, self.vtable).FlushQueues(@ptrCast(*const IMAPIStatus, self), ulUIParam, cbTargetTransport, lpTargetTransport, ulFlags); } };} pub usingnamespace MethodMixin(@This()); }; pub const IMAPIContainer = extern struct { pub const VTable = extern struct { base: IMAPIProp.VTable, GetContentsTable: fn( self: *const IMAPIContainer, ulFlags: u32, lppTable: ?*?*IMAPITable, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetHierarchyTable: fn( self: *const IMAPIContainer, ulFlags: u32, lppTable: ?*?*IMAPITable, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenEntry: fn( self: *const IMAPIContainer, cbEntryID: u32, // TODO: what to do with BytesParamIndex 0? lpEntryID: ?*ENTRYID, lpInterface: ?*Guid, ulFlags: u32, lpulObjType: ?*u32, lppUnk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSearchCriteria: fn( self: *const IMAPIContainer, lpRestriction: ?*SRestriction, lpContainerList: ?*SBinaryArray, ulSearchFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSearchCriteria: fn( self: *const IMAPIContainer, ulFlags: u32, lppRestriction: ?*?*SRestriction, lppContainerList: ?*?*SBinaryArray, lpulSearchState: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IMAPIProp.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIContainer_GetContentsTable(self: *const T, ulFlags: u32, lppTable: ?*?*IMAPITable) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIContainer.VTable, self.vtable).GetContentsTable(@ptrCast(*const IMAPIContainer, self), ulFlags, lppTable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIContainer_GetHierarchyTable(self: *const T, ulFlags: u32, lppTable: ?*?*IMAPITable) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIContainer.VTable, self.vtable).GetHierarchyTable(@ptrCast(*const IMAPIContainer, self), ulFlags, lppTable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIContainer_OpenEntry(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID, lpInterface: ?*Guid, ulFlags: u32, lpulObjType: ?*u32, lppUnk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIContainer.VTable, self.vtable).OpenEntry(@ptrCast(*const IMAPIContainer, self), cbEntryID, lpEntryID, lpInterface, ulFlags, lpulObjType, lppUnk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIContainer_SetSearchCriteria(self: *const T, lpRestriction: ?*SRestriction, lpContainerList: ?*SBinaryArray, ulSearchFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIContainer.VTable, self.vtable).SetSearchCriteria(@ptrCast(*const IMAPIContainer, self), lpRestriction, lpContainerList, ulSearchFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIContainer_GetSearchCriteria(self: *const T, ulFlags: u32, lppRestriction: ?*?*SRestriction, lppContainerList: ?*?*SBinaryArray, lpulSearchState: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIContainer.VTable, self.vtable).GetSearchCriteria(@ptrCast(*const IMAPIContainer, self), ulFlags, lppRestriction, lppContainerList, lpulSearchState); } };} pub usingnamespace MethodMixin(@This()); }; pub const _flaglist = extern struct { cFlags: u32, ulFlag: [1]u32, }; // TODO: this type is limited to platform 'windows5.0' pub const IABContainer = extern struct { pub const VTable = extern struct { base: IMAPIContainer.VTable, CreateEntry: fn( self: *const IABContainer, cbEntryID: u32, // TODO: what to do with BytesParamIndex 0? lpEntryID: ?*ENTRYID, ulCreateFlags: u32, lppMAPIPropEntry: ?*?*IMAPIProp, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyEntries: fn( self: *const IABContainer, lpEntries: ?*SBinaryArray, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteEntries: fn( self: *const IABContainer, lpEntries: ?*SBinaryArray, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ResolveNames: fn( self: *const IABContainer, lpPropTagArray: ?*SPropTagArray, ulFlags: u32, lpAdrList: ?*ADRLIST, lpFlagList: ?*_flaglist, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IMAPIContainer.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IABContainer_CreateEntry(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID, ulCreateFlags: u32, lppMAPIPropEntry: ?*?*IMAPIProp) callconv(.Inline) HRESULT { return @ptrCast(*const IABContainer.VTable, self.vtable).CreateEntry(@ptrCast(*const IABContainer, self), cbEntryID, lpEntryID, ulCreateFlags, lppMAPIPropEntry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IABContainer_CopyEntries(self: *const T, lpEntries: ?*SBinaryArray, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IABContainer.VTable, self.vtable).CopyEntries(@ptrCast(*const IABContainer, self), lpEntries, ulUIParam, lpProgress, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IABContainer_DeleteEntries(self: *const T, lpEntries: ?*SBinaryArray, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IABContainer.VTable, self.vtable).DeleteEntries(@ptrCast(*const IABContainer, self), lpEntries, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IABContainer_ResolveNames(self: *const T, lpPropTagArray: ?*SPropTagArray, ulFlags: u32, lpAdrList: ?*ADRLIST, lpFlagList: ?*_flaglist) callconv(.Inline) HRESULT { return @ptrCast(*const IABContainer.VTable, self.vtable).ResolveNames(@ptrCast(*const IABContainer, self), lpPropTagArray, ulFlags, lpAdrList, lpFlagList); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' pub const IMailUser = extern struct { pub const VTable = extern struct { base: IMAPIProp.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IMAPIProp.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' pub const IDistList = extern struct { pub const VTable = extern struct { base: IMAPIContainer.VTable, CreateEntry: fn( self: *const IDistList, cbEntryID: u32, // TODO: what to do with BytesParamIndex 0? lpEntryID: ?*ENTRYID, ulCreateFlags: u32, lppMAPIPropEntry: ?*?*IMAPIProp, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyEntries: fn( self: *const IDistList, lpEntries: ?*SBinaryArray, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteEntries: fn( self: *const IDistList, lpEntries: ?*SBinaryArray, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ResolveNames: fn( self: *const IDistList, lpPropTagArray: ?*SPropTagArray, ulFlags: u32, lpAdrList: ?*ADRLIST, lpFlagList: ?*_flaglist, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IMAPIContainer.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDistList_CreateEntry(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID, ulCreateFlags: u32, lppMAPIPropEntry: ?*?*IMAPIProp) callconv(.Inline) HRESULT { return @ptrCast(*const IDistList.VTable, self.vtable).CreateEntry(@ptrCast(*const IDistList, self), cbEntryID, lpEntryID, ulCreateFlags, lppMAPIPropEntry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDistList_CopyEntries(self: *const T, lpEntries: ?*SBinaryArray, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDistList.VTable, self.vtable).CopyEntries(@ptrCast(*const IDistList, self), lpEntries, ulUIParam, lpProgress, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDistList_DeleteEntries(self: *const T, lpEntries: ?*SBinaryArray, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDistList.VTable, self.vtable).DeleteEntries(@ptrCast(*const IDistList, self), lpEntries, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDistList_ResolveNames(self: *const T, lpPropTagArray: ?*SPropTagArray, ulFlags: u32, lpAdrList: ?*ADRLIST, lpFlagList: ?*_flaglist) callconv(.Inline) HRESULT { return @ptrCast(*const IDistList.VTable, self.vtable).ResolveNames(@ptrCast(*const IDistList, self), lpPropTagArray, ulFlags, lpAdrList, lpFlagList); } };} pub usingnamespace MethodMixin(@This()); }; pub const IMAPIFolder = extern struct { pub const VTable = extern struct { base: IMAPIContainer.VTable, CreateMessage: fn( self: *const IMAPIFolder, lpInterface: ?*Guid, ulFlags: u32, lppMessage: ?*?*IMessage, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyMessages: fn( self: *const IMAPIFolder, lpMsgList: ?*SBinaryArray, lpInterface: ?*Guid, lpDestFolder: ?*c_void, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteMessages: fn( self: *const IMAPIFolder, lpMsgList: ?*SBinaryArray, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateFolder: fn( self: *const IMAPIFolder, ulFolderType: u32, lpszFolderName: ?*i8, lpszFolderComment: ?*i8, lpInterface: ?*Guid, ulFlags: u32, lppFolder: ?*?*IMAPIFolder, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyFolder: fn( self: *const IMAPIFolder, cbEntryID: u32, // TODO: what to do with BytesParamIndex 0? lpEntryID: ?*ENTRYID, lpInterface: ?*Guid, lpDestFolder: ?*c_void, lpszNewFolderName: ?*i8, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteFolder: fn( self: *const IMAPIFolder, cbEntryID: u32, // TODO: what to do with BytesParamIndex 0? lpEntryID: ?*ENTRYID, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetReadFlags: fn( self: *const IMAPIFolder, lpMsgList: ?*SBinaryArray, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMessageStatus: fn( self: *const IMAPIFolder, cbEntryID: u32, // TODO: what to do with BytesParamIndex 0? lpEntryID: ?*ENTRYID, ulFlags: u32, lpulMessageStatus: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetMessageStatus: fn( self: *const IMAPIFolder, cbEntryID: u32, // TODO: what to do with BytesParamIndex 0? lpEntryID: ?*ENTRYID, ulNewStatus: u32, ulNewStatusMask: u32, lpulOldStatus: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SaveContentsSort: fn( self: *const IMAPIFolder, lpSortCriteria: ?*SSortOrderSet, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EmptyFolder: fn( self: *const IMAPIFolder, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IMAPIContainer.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIFolder_CreateMessage(self: *const T, lpInterface: ?*Guid, ulFlags: u32, lppMessage: ?*?*IMessage) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIFolder.VTable, self.vtable).CreateMessage(@ptrCast(*const IMAPIFolder, self), lpInterface, ulFlags, lppMessage); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIFolder_CopyMessages(self: *const T, lpMsgList: ?*SBinaryArray, lpInterface: ?*Guid, lpDestFolder: ?*c_void, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIFolder.VTable, self.vtable).CopyMessages(@ptrCast(*const IMAPIFolder, self), lpMsgList, lpInterface, lpDestFolder, ulUIParam, lpProgress, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIFolder_DeleteMessages(self: *const T, lpMsgList: ?*SBinaryArray, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIFolder.VTable, self.vtable).DeleteMessages(@ptrCast(*const IMAPIFolder, self), lpMsgList, ulUIParam, lpProgress, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIFolder_CreateFolder(self: *const T, ulFolderType: u32, lpszFolderName: ?*i8, lpszFolderComment: ?*i8, lpInterface: ?*Guid, ulFlags: u32, lppFolder: ?*?*IMAPIFolder) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIFolder.VTable, self.vtable).CreateFolder(@ptrCast(*const IMAPIFolder, self), ulFolderType, lpszFolderName, lpszFolderComment, lpInterface, ulFlags, lppFolder); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIFolder_CopyFolder(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID, lpInterface: ?*Guid, lpDestFolder: ?*c_void, lpszNewFolderName: ?*i8, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIFolder.VTable, self.vtable).CopyFolder(@ptrCast(*const IMAPIFolder, self), cbEntryID, lpEntryID, lpInterface, lpDestFolder, lpszNewFolderName, ulUIParam, lpProgress, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIFolder_DeleteFolder(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIFolder.VTable, self.vtable).DeleteFolder(@ptrCast(*const IMAPIFolder, self), cbEntryID, lpEntryID, ulUIParam, lpProgress, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIFolder_SetReadFlags(self: *const T, lpMsgList: ?*SBinaryArray, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIFolder.VTable, self.vtable).SetReadFlags(@ptrCast(*const IMAPIFolder, self), lpMsgList, ulUIParam, lpProgress, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIFolder_GetMessageStatus(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID, ulFlags: u32, lpulMessageStatus: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIFolder.VTable, self.vtable).GetMessageStatus(@ptrCast(*const IMAPIFolder, self), cbEntryID, lpEntryID, ulFlags, lpulMessageStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIFolder_SetMessageStatus(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID, ulNewStatus: u32, ulNewStatusMask: u32, lpulOldStatus: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIFolder.VTable, self.vtable).SetMessageStatus(@ptrCast(*const IMAPIFolder, self), cbEntryID, lpEntryID, ulNewStatus, ulNewStatusMask, lpulOldStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIFolder_SaveContentsSort(self: *const T, lpSortCriteria: ?*SSortOrderSet, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIFolder.VTable, self.vtable).SaveContentsSort(@ptrCast(*const IMAPIFolder, self), lpSortCriteria, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIFolder_EmptyFolder(self: *const T, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIFolder.VTable, self.vtable).EmptyFolder(@ptrCast(*const IMAPIFolder, self), ulUIParam, lpProgress, ulFlags); } };} pub usingnamespace MethodMixin(@This()); }; pub const IMsgStore = extern struct { pub const VTable = extern struct { base: IMAPIProp.VTable, Advise: fn( self: *const IMsgStore, cbEntryID: u32, // TODO: what to do with BytesParamIndex 0? lpEntryID: ?*ENTRYID, ulEventMask: u32, lpAdviseSink: ?*IMAPIAdviseSink, lpulConnection: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Unadvise: fn( self: *const IMsgStore, ulConnection: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CompareEntryIDs: fn( self: *const IMsgStore, cbEntryID1: u32, // TODO: what to do with BytesParamIndex 0? lpEntryID1: ?*ENTRYID, cbEntryID2: u32, // TODO: what to do with BytesParamIndex 2? lpEntryID2: ?*ENTRYID, ulFlags: u32, lpulResult: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenEntry: fn( self: *const IMsgStore, cbEntryID: u32, // TODO: what to do with BytesParamIndex 0? lpEntryID: ?*ENTRYID, lpInterface: ?*Guid, ulFlags: u32, lpulObjType: ?*u32, ppUnk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetReceiveFolder: fn( self: *const IMsgStore, lpszMessageClass: ?*i8, ulFlags: u32, cbEntryID: u32, // TODO: what to do with BytesParamIndex 2? lpEntryID: ?*ENTRYID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetReceiveFolder: fn( self: *const IMsgStore, lpszMessageClass: ?*i8, ulFlags: u32, lpcbEntryID: ?*u32, lppEntryID: ?*?*ENTRYID, lppszExplicitClass: ?*?*i8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetReceiveFolderTable: fn( self: *const IMsgStore, ulFlags: u32, lppTable: ?*?*IMAPITable, ) callconv(@import("std").os.windows.WINAPI) HRESULT, StoreLogoff: fn( self: *const IMsgStore, lpulFlags: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AbortSubmit: fn( self: *const IMsgStore, cbEntryID: u32, // TODO: what to do with BytesParamIndex 0? lpEntryID: ?*ENTRYID, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOutgoingQueue: fn( self: *const IMsgStore, ulFlags: u32, lppTable: ?*?*IMAPITable, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetLockState: fn( self: *const IMsgStore, lpMessage: ?*IMessage, ulLockState: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FinishedMsg: fn( self: *const IMsgStore, ulFlags: u32, cbEntryID: u32, // TODO: what to do with BytesParamIndex 1? lpEntryID: ?*ENTRYID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NotifyNewMail: fn( self: *const IMsgStore, lpNotification: ?*NOTIFICATION, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IMAPIProp.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_Advise(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID, ulEventMask: u32, lpAdviseSink: ?*IMAPIAdviseSink, lpulConnection: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).Advise(@ptrCast(*const IMsgStore, self), cbEntryID, lpEntryID, ulEventMask, lpAdviseSink, lpulConnection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_Unadvise(self: *const T, ulConnection: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).Unadvise(@ptrCast(*const IMsgStore, self), ulConnection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_CompareEntryIDs(self: *const T, cbEntryID1: u32, lpEntryID1: ?*ENTRYID, cbEntryID2: u32, lpEntryID2: ?*ENTRYID, ulFlags: u32, lpulResult: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).CompareEntryIDs(@ptrCast(*const IMsgStore, self), cbEntryID1, lpEntryID1, cbEntryID2, lpEntryID2, ulFlags, lpulResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_OpenEntry(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID, lpInterface: ?*Guid, ulFlags: u32, lpulObjType: ?*u32, ppUnk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).OpenEntry(@ptrCast(*const IMsgStore, self), cbEntryID, lpEntryID, lpInterface, ulFlags, lpulObjType, ppUnk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_SetReceiveFolder(self: *const T, lpszMessageClass: ?*i8, ulFlags: u32, cbEntryID: u32, lpEntryID: ?*ENTRYID) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).SetReceiveFolder(@ptrCast(*const IMsgStore, self), lpszMessageClass, ulFlags, cbEntryID, lpEntryID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_GetReceiveFolder(self: *const T, lpszMessageClass: ?*i8, ulFlags: u32, lpcbEntryID: ?*u32, lppEntryID: ?*?*ENTRYID, lppszExplicitClass: ?*?*i8) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).GetReceiveFolder(@ptrCast(*const IMsgStore, self), lpszMessageClass, ulFlags, lpcbEntryID, lppEntryID, lppszExplicitClass); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_GetReceiveFolderTable(self: *const T, ulFlags: u32, lppTable: ?*?*IMAPITable) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).GetReceiveFolderTable(@ptrCast(*const IMsgStore, self), ulFlags, lppTable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_StoreLogoff(self: *const T, lpulFlags: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).StoreLogoff(@ptrCast(*const IMsgStore, self), lpulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_AbortSubmit(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).AbortSubmit(@ptrCast(*const IMsgStore, self), cbEntryID, lpEntryID, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_GetOutgoingQueue(self: *const T, ulFlags: u32, lppTable: ?*?*IMAPITable) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).GetOutgoingQueue(@ptrCast(*const IMsgStore, self), ulFlags, lppTable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_SetLockState(self: *const T, lpMessage: ?*IMessage, ulLockState: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).SetLockState(@ptrCast(*const IMsgStore, self), lpMessage, ulLockState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_FinishedMsg(self: *const T, ulFlags: u32, cbEntryID: u32, lpEntryID: ?*ENTRYID) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).FinishedMsg(@ptrCast(*const IMsgStore, self), ulFlags, cbEntryID, lpEntryID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_NotifyNewMail(self: *const T, lpNotification: ?*NOTIFICATION) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).NotifyNewMail(@ptrCast(*const IMsgStore, self), lpNotification); } };} pub usingnamespace MethodMixin(@This()); }; pub const IMessage = extern struct { pub const VTable = extern struct { base: IMAPIProp.VTable, GetAttachmentTable: fn( self: *const IMessage, ulFlags: u32, lppTable: ?*?*IMAPITable, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenAttach: fn( self: *const IMessage, ulAttachmentNum: u32, lpInterface: ?*Guid, ulFlags: u32, lppAttach: ?*?*IAttach, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateAttach: fn( self: *const IMessage, lpInterface: ?*Guid, ulFlags: u32, lpulAttachmentNum: ?*u32, lppAttach: ?*?*IAttach, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteAttach: fn( self: *const IMessage, ulAttachmentNum: u32, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRecipientTable: fn( self: *const IMessage, ulFlags: u32, lppTable: ?*?*IMAPITable, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ModifyRecipients: fn( self: *const IMessage, ulFlags: u32, lpMods: ?*ADRLIST, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SubmitMessage: fn( self: *const IMessage, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetReadFlag: fn( self: *const IMessage, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IMAPIProp.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMessage_GetAttachmentTable(self: *const T, ulFlags: u32, lppTable: ?*?*IMAPITable) callconv(.Inline) HRESULT { return @ptrCast(*const IMessage.VTable, self.vtable).GetAttachmentTable(@ptrCast(*const IMessage, self), ulFlags, lppTable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMessage_OpenAttach(self: *const T, ulAttachmentNum: u32, lpInterface: ?*Guid, ulFlags: u32, lppAttach: ?*?*IAttach) callconv(.Inline) HRESULT { return @ptrCast(*const IMessage.VTable, self.vtable).OpenAttach(@ptrCast(*const IMessage, self), ulAttachmentNum, lpInterface, ulFlags, lppAttach); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMessage_CreateAttach(self: *const T, lpInterface: ?*Guid, ulFlags: u32, lpulAttachmentNum: ?*u32, lppAttach: ?*?*IAttach) callconv(.Inline) HRESULT { return @ptrCast(*const IMessage.VTable, self.vtable).CreateAttach(@ptrCast(*const IMessage, self), lpInterface, ulFlags, lpulAttachmentNum, lppAttach); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMessage_DeleteAttach(self: *const T, ulAttachmentNum: u32, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMessage.VTable, self.vtable).DeleteAttach(@ptrCast(*const IMessage, self), ulAttachmentNum, ulUIParam, lpProgress, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMessage_GetRecipientTable(self: *const T, ulFlags: u32, lppTable: ?*?*IMAPITable) callconv(.Inline) HRESULT { return @ptrCast(*const IMessage.VTable, self.vtable).GetRecipientTable(@ptrCast(*const IMessage, self), ulFlags, lppTable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMessage_ModifyRecipients(self: *const T, ulFlags: u32, lpMods: ?*ADRLIST) callconv(.Inline) HRESULT { return @ptrCast(*const IMessage.VTable, self.vtable).ModifyRecipients(@ptrCast(*const IMessage, self), ulFlags, lpMods); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMessage_SubmitMessage(self: *const T, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMessage.VTable, self.vtable).SubmitMessage(@ptrCast(*const IMessage, self), ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMessage_SetReadFlag(self: *const T, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMessage.VTable, self.vtable).SetReadFlag(@ptrCast(*const IMessage, self), ulFlags); } };} pub usingnamespace MethodMixin(@This()); }; pub const IAttach = extern struct { pub const VTable = extern struct { base: IMAPIProp.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IMAPIProp.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; pub const LPFNABSDI = fn( ulUIParam: usize, lpvmsg: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const LPFNDISMISS = fn( ulUIParam: usize, lpvContext: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) void; pub const LPFNBUTTON = fn( ulUIParam: usize, lpvContext: ?*c_void, cbEntryID: u32, lpSelection: ?*ENTRYID, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub const ADRPARM = extern struct { cbABContEntryID: u32, lpABContEntryID: ?*ENTRYID, ulFlags: u32, lpReserved: ?*c_void, ulHelpContext: u32, lpszHelpFileName: ?*i8, lpfnABSDI: ?LPFNABSDI, lpfnDismiss: ?LPFNDISMISS, lpvDismissContext: ?*c_void, lpszCaption: ?*i8, lpszNewEntryTitle: ?*i8, lpszDestWellsTitle: ?*i8, cDestFields: u32, nDestFieldFocus: u32, lppszDestTitles: ?*?*i8, lpulDestComps: ?*u32, lpContRestriction: ?*SRestriction, lpHierRestriction: ?*SRestriction, }; pub const IMAPIControl = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetLastError: fn( self: *const IMAPIControl, hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Activate: fn( self: *const IMAPIControl, ulFlags: u32, ulUIParam: usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetState: fn( self: *const IMAPIControl, ulFlags: u32, lpulState: ?*u32, ) 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 IMAPIControl_GetLastError(self: *const T, hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIControl.VTable, self.vtable).GetLastError(@ptrCast(*const IMAPIControl, self), hResult, ulFlags, lppMAPIError); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIControl_Activate(self: *const T, ulFlags: u32, ulUIParam: usize) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIControl.VTable, self.vtable).Activate(@ptrCast(*const IMAPIControl, self), ulFlags, ulUIParam); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIControl_GetState(self: *const T, ulFlags: u32, lpulState: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIControl.VTable, self.vtable).GetState(@ptrCast(*const IMAPIControl, self), ulFlags, lpulState); } };} pub usingnamespace MethodMixin(@This()); }; pub const DTBLLABEL = extern struct { ulbLpszLabelName: u32, ulFlags: u32, }; pub const DTBLEDIT = extern struct { ulbLpszCharsAllowed: u32, ulFlags: u32, ulNumCharsAllowed: u32, ulPropTag: u32, }; pub const DTBLLBX = extern struct { ulFlags: u32, ulPRSetProperty: u32, ulPRTableName: u32, }; pub const DTBLCOMBOBOX = extern struct { ulbLpszCharsAllowed: u32, ulFlags: u32, ulNumCharsAllowed: u32, ulPRPropertyName: u32, ulPRTableName: u32, }; pub const DTBLDDLBX = extern struct { ulFlags: u32, ulPRDisplayProperty: u32, ulPRSetProperty: u32, ulPRTableName: u32, }; pub const DTBLCHECKBOX = extern struct { ulbLpszLabel: u32, ulFlags: u32, ulPRPropertyName: u32, }; pub const DTBLGROUPBOX = extern struct { ulbLpszLabel: u32, ulFlags: u32, }; pub const DTBLBUTTON = extern struct { ulbLpszLabel: u32, ulFlags: u32, ulPRControl: u32, }; pub const DTBLPAGE = extern struct { ulbLpszLabel: u32, ulFlags: u32, ulbLpszComponent: u32, ulContext: u32, }; pub const DTBLRADIOBUTTON = extern struct { ulbLpszLabel: u32, ulFlags: u32, ulcButtons: u32, ulPropTag: u32, lReturnValue: i32, }; pub const DTBLMVLISTBOX = extern struct { ulFlags: u32, ulMVPropTag: u32, }; pub const DTBLMVDDLBX = extern struct { ulFlags: u32, ulMVPropTag: u32, }; pub const IProviderAdmin = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetLastError: fn( self: *const IProviderAdmin, hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProviderTable: fn( self: *const IProviderAdmin, ulFlags: u32, lppTable: ?*?*IMAPITable, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateProvider: fn( self: *const IProviderAdmin, lpszProvider: ?*i8, cValues: u32, lpProps: [*]SPropValue, ulUIParam: usize, ulFlags: u32, lpUID: ?*MAPIUID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteProvider: fn( self: *const IProviderAdmin, lpUID: ?*MAPIUID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenProfileSection: fn( self: *const IProviderAdmin, lpUID: ?*MAPIUID, lpInterface: ?*Guid, ulFlags: u32, lppProfSect: ?*?*IProfSect, ) 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 IProviderAdmin_GetLastError(self: *const T, hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderAdmin.VTable, self.vtable).GetLastError(@ptrCast(*const IProviderAdmin, self), hResult, ulFlags, lppMAPIError); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProviderAdmin_GetProviderTable(self: *const T, ulFlags: u32, lppTable: ?*?*IMAPITable) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderAdmin.VTable, self.vtable).GetProviderTable(@ptrCast(*const IProviderAdmin, self), ulFlags, lppTable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProviderAdmin_CreateProvider(self: *const T, lpszProvider: ?*i8, cValues: u32, lpProps: [*]SPropValue, ulUIParam: usize, ulFlags: u32, lpUID: ?*MAPIUID) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderAdmin.VTable, self.vtable).CreateProvider(@ptrCast(*const IProviderAdmin, self), lpszProvider, cValues, lpProps, ulUIParam, ulFlags, lpUID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProviderAdmin_DeleteProvider(self: *const T, lpUID: ?*MAPIUID) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderAdmin.VTable, self.vtable).DeleteProvider(@ptrCast(*const IProviderAdmin, self), lpUID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProviderAdmin_OpenProfileSection(self: *const T, lpUID: ?*MAPIUID, lpInterface: ?*Guid, ulFlags: u32, lppProfSect: ?*?*IProfSect) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderAdmin.VTable, self.vtable).OpenProfileSection(@ptrCast(*const IProviderAdmin, self), lpUID, lpInterface, ulFlags, lppProfSect); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' pub const IAddrBook = extern struct { pub const VTable = extern struct { base: IMAPIProp.VTable, OpenEntry: fn( self: *const IAddrBook, cbEntryID: u32, lpEntryID: ?*ENTRYID, lpInterface: ?*Guid, ulFlags: u32, lpulObjType: ?*u32, lppUnk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CompareEntryIDs: fn( self: *const IAddrBook, cbEntryID1: u32, lpEntryID1: ?*ENTRYID, cbEntryID2: u32, lpEntryID2: ?*ENTRYID, ulFlags: u32, lpulResult: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Advise: fn( self: *const IAddrBook, cbEntryID: u32, lpEntryID: ?*ENTRYID, ulEventMask: u32, lpAdviseSink: ?*IMAPIAdviseSink, lpulConnection: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Unadvise: fn( self: *const IAddrBook, ulConnection: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateOneOff: fn( self: *const IAddrBook, lpszName: ?*i8, lpszAdrType: ?*i8, lpszAddress: ?*i8, ulFlags: u32, lpcbEntryID: ?*u32, lppEntryID: ?*?*ENTRYID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NewEntry: fn( self: *const IAddrBook, ulUIParam: u32, ulFlags: u32, cbEIDContainer: u32, lpEIDContainer: ?*ENTRYID, cbEIDNewEntryTpl: u32, lpEIDNewEntryTpl: ?*ENTRYID, lpcbEIDNewEntry: ?*u32, lppEIDNewEntry: ?*?*ENTRYID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ResolveName: fn( self: *const IAddrBook, ulUIParam: usize, ulFlags: u32, lpszNewEntryTitle: ?*i8, lpAdrList: ?*ADRLIST, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Address: fn( self: *const IAddrBook, lpulUIParam: ?*u32, lpAdrParms: ?*ADRPARM, lppAdrList: ?*?*ADRLIST, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Details: fn( self: *const IAddrBook, lpulUIParam: ?*usize, lpfnDismiss: ?LPFNDISMISS, lpvDismissContext: ?*c_void, cbEntryID: u32, lpEntryID: ?*ENTRYID, lpfButtonCallback: ?LPFNBUTTON, lpvButtonContext: ?*c_void, lpszButtonText: ?*i8, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RecipOptions: fn( self: *const IAddrBook, ulUIParam: u32, ulFlags: u32, lpRecip: ?*ADRENTRY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryDefaultRecipOpt: fn( self: *const IAddrBook, lpszAdrType: ?*i8, ulFlags: u32, lpcValues: ?*u32, lppOptions: ?*?*SPropValue, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPAB: fn( self: *const IAddrBook, lpcbEntryID: ?*u32, lppEntryID: ?*?*ENTRYID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPAB: fn( self: *const IAddrBook, cbEntryID: u32, lpEntryID: ?*ENTRYID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDefaultDir: fn( self: *const IAddrBook, lpcbEntryID: ?*u32, lppEntryID: ?*?*ENTRYID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDefaultDir: fn( self: *const IAddrBook, cbEntryID: u32, lpEntryID: ?*ENTRYID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSearchPath: fn( self: *const IAddrBook, ulFlags: u32, lppSearchPath: ?*?*SRowSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSearchPath: fn( self: *const IAddrBook, ulFlags: u32, lpSearchPath: ?*SRowSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PrepareRecips: fn( self: *const IAddrBook, ulFlags: u32, lpPropTagArray: ?*SPropTagArray, lpRecipList: ?*ADRLIST, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IMAPIProp.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_OpenEntry(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID, lpInterface: ?*Guid, ulFlags: u32, lpulObjType: ?*u32, lppUnk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).OpenEntry(@ptrCast(*const IAddrBook, self), cbEntryID, lpEntryID, lpInterface, ulFlags, lpulObjType, lppUnk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_CompareEntryIDs(self: *const T, cbEntryID1: u32, lpEntryID1: ?*ENTRYID, cbEntryID2: u32, lpEntryID2: ?*ENTRYID, ulFlags: u32, lpulResult: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).CompareEntryIDs(@ptrCast(*const IAddrBook, self), cbEntryID1, lpEntryID1, cbEntryID2, lpEntryID2, ulFlags, lpulResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_Advise(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID, ulEventMask: u32, lpAdviseSink: ?*IMAPIAdviseSink, lpulConnection: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).Advise(@ptrCast(*const IAddrBook, self), cbEntryID, lpEntryID, ulEventMask, lpAdviseSink, lpulConnection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_Unadvise(self: *const T, ulConnection: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).Unadvise(@ptrCast(*const IAddrBook, self), ulConnection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_CreateOneOff(self: *const T, lpszName: ?*i8, lpszAdrType: ?*i8, lpszAddress: ?*i8, ulFlags: u32, lpcbEntryID: ?*u32, lppEntryID: ?*?*ENTRYID) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).CreateOneOff(@ptrCast(*const IAddrBook, self), lpszName, lpszAdrType, lpszAddress, ulFlags, lpcbEntryID, lppEntryID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_NewEntry(self: *const T, ulUIParam: u32, ulFlags: u32, cbEIDContainer: u32, lpEIDContainer: ?*ENTRYID, cbEIDNewEntryTpl: u32, lpEIDNewEntryTpl: ?*ENTRYID, lpcbEIDNewEntry: ?*u32, lppEIDNewEntry: ?*?*ENTRYID) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).NewEntry(@ptrCast(*const IAddrBook, self), ulUIParam, ulFlags, cbEIDContainer, lpEIDContainer, cbEIDNewEntryTpl, lpEIDNewEntryTpl, lpcbEIDNewEntry, lppEIDNewEntry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_ResolveName(self: *const T, ulUIParam: usize, ulFlags: u32, lpszNewEntryTitle: ?*i8, lpAdrList: ?*ADRLIST) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).ResolveName(@ptrCast(*const IAddrBook, self), ulUIParam, ulFlags, lpszNewEntryTitle, lpAdrList); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_Address(self: *const T, lpulUIParam: ?*u32, lpAdrParms: ?*ADRPARM, lppAdrList: ?*?*ADRLIST) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).Address(@ptrCast(*const IAddrBook, self), lpulUIParam, lpAdrParms, lppAdrList); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_Details(self: *const T, lpulUIParam: ?*usize, lpfnDismiss: ?LPFNDISMISS, lpvDismissContext: ?*c_void, cbEntryID: u32, lpEntryID: ?*ENTRYID, lpfButtonCallback: ?LPFNBUTTON, lpvButtonContext: ?*c_void, lpszButtonText: ?*i8, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).Details(@ptrCast(*const IAddrBook, self), lpulUIParam, lpfnDismiss, lpvDismissContext, cbEntryID, lpEntryID, lpfButtonCallback, lpvButtonContext, lpszButtonText, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_RecipOptions(self: *const T, ulUIParam: u32, ulFlags: u32, lpRecip: ?*ADRENTRY) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).RecipOptions(@ptrCast(*const IAddrBook, self), ulUIParam, ulFlags, lpRecip); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_QueryDefaultRecipOpt(self: *const T, lpszAdrType: ?*i8, ulFlags: u32, lpcValues: ?*u32, lppOptions: ?*?*SPropValue) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).QueryDefaultRecipOpt(@ptrCast(*const IAddrBook, self), lpszAdrType, ulFlags, lpcValues, lppOptions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_GetPAB(self: *const T, lpcbEntryID: ?*u32, lppEntryID: ?*?*ENTRYID) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).GetPAB(@ptrCast(*const IAddrBook, self), lpcbEntryID, lppEntryID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_SetPAB(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).SetPAB(@ptrCast(*const IAddrBook, self), cbEntryID, lpEntryID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_GetDefaultDir(self: *const T, lpcbEntryID: ?*u32, lppEntryID: ?*?*ENTRYID) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).GetDefaultDir(@ptrCast(*const IAddrBook, self), lpcbEntryID, lppEntryID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_SetDefaultDir(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).SetDefaultDir(@ptrCast(*const IAddrBook, self), cbEntryID, lpEntryID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_GetSearchPath(self: *const T, ulFlags: u32, lppSearchPath: ?*?*SRowSet) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).GetSearchPath(@ptrCast(*const IAddrBook, self), ulFlags, lppSearchPath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_SetSearchPath(self: *const T, ulFlags: u32, lpSearchPath: ?*SRowSet) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).SetSearchPath(@ptrCast(*const IAddrBook, self), ulFlags, lpSearchPath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_PrepareRecips(self: *const T, ulFlags: u32, lpPropTagArray: ?*SPropTagArray, lpRecipList: ?*ADRLIST) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).PrepareRecips(@ptrCast(*const IAddrBook, self), ulFlags, lpPropTagArray, lpRecipList); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' pub const IWABObject = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetLastError: fn( self: *const IWABObject, hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AllocateBuffer: fn( self: *const IWABObject, cbSize: u32, lppBuffer: ?*?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AllocateMore: fn( self: *const IWABObject, cbSize: u32, lpObject: ?*c_void, lppBuffer: ?*?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FreeBuffer: fn( self: *const IWABObject, lpBuffer: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Backup: fn( self: *const IWABObject, lpFileName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Import: fn( self: *const IWABObject, lpWIP: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Find: fn( self: *const IWABObject, lpIAB: ?*IAddrBook, hWnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT, VCardDisplay: fn( self: *const IWABObject, lpIAB: ?*IAddrBook, hWnd: ?HWND, lpszFileName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LDAPUrl: fn( self: *const IWABObject, lpIAB: ?*IAddrBook, hWnd: ?HWND, ulFlags: u32, lpszURL: ?PSTR, lppMailUser: ?*?*IMailUser, ) callconv(@import("std").os.windows.WINAPI) HRESULT, VCardCreate: fn( self: *const IWABObject, lpIAB: ?*IAddrBook, ulFlags: u32, lpszVCard: ?PSTR, lpMailUser: ?*IMailUser, ) callconv(@import("std").os.windows.WINAPI) HRESULT, VCardRetrieve: fn( self: *const IWABObject, lpIAB: ?*IAddrBook, ulFlags: u32, lpszVCard: ?PSTR, lppMailUser: ?*?*IMailUser, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMe: fn( self: *const IWABObject, lpIAB: ?*IAddrBook, ulFlags: u32, lpdwAction: ?*u32, lpsbEID: ?*SBinary, hwnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetMe: fn( self: *const IWABObject, lpIAB: ?*IAddrBook, ulFlags: u32, sbEID: SBinary, hwnd: ?HWND, ) 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 IWABObject_GetLastError(self: *const T, hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).GetLastError(@ptrCast(*const IWABObject, self), hResult, ulFlags, lppMAPIError); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABObject_AllocateBuffer(self: *const T, cbSize: u32, lppBuffer: ?*?*c_void) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).AllocateBuffer(@ptrCast(*const IWABObject, self), cbSize, lppBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABObject_AllocateMore(self: *const T, cbSize: u32, lpObject: ?*c_void, lppBuffer: ?*?*c_void) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).AllocateMore(@ptrCast(*const IWABObject, self), cbSize, lpObject, lppBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABObject_FreeBuffer(self: *const T, lpBuffer: ?*c_void) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).FreeBuffer(@ptrCast(*const IWABObject, self), lpBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABObject_Backup(self: *const T, lpFileName: ?PSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).Backup(@ptrCast(*const IWABObject, self), lpFileName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABObject_Import(self: *const T, lpWIP: ?PSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).Import(@ptrCast(*const IWABObject, self), lpWIP); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABObject_Find(self: *const T, lpIAB: ?*IAddrBook, hWnd: ?HWND) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).Find(@ptrCast(*const IWABObject, self), lpIAB, hWnd); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABObject_VCardDisplay(self: *const T, lpIAB: ?*IAddrBook, hWnd: ?HWND, lpszFileName: ?PSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).VCardDisplay(@ptrCast(*const IWABObject, self), lpIAB, hWnd, lpszFileName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABObject_LDAPUrl(self: *const T, lpIAB: ?*IAddrBook, hWnd: ?HWND, ulFlags: u32, lpszURL: ?PSTR, lppMailUser: ?*?*IMailUser) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).LDAPUrl(@ptrCast(*const IWABObject, self), lpIAB, hWnd, ulFlags, lpszURL, lppMailUser); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABObject_VCardCreate(self: *const T, lpIAB: ?*IAddrBook, ulFlags: u32, lpszVCard: ?PSTR, lpMailUser: ?*IMailUser) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).VCardCreate(@ptrCast(*const IWABObject, self), lpIAB, ulFlags, lpszVCard, lpMailUser); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABObject_VCardRetrieve(self: *const T, lpIAB: ?*IAddrBook, ulFlags: u32, lpszVCard: ?PSTR, lppMailUser: ?*?*IMailUser) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).VCardRetrieve(@ptrCast(*const IWABObject, self), lpIAB, ulFlags, lpszVCard, lppMailUser); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABObject_GetMe(self: *const T, lpIAB: ?*IAddrBook, ulFlags: u32, lpdwAction: ?*u32, lpsbEID: ?*SBinary, hwnd: ?HWND) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).GetMe(@ptrCast(*const IWABObject, self), lpIAB, ulFlags, lpdwAction, lpsbEID, hwnd); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABObject_SetMe(self: *const T, lpIAB: ?*IAddrBook, ulFlags: u32, sbEID: SBinary, hwnd: ?HWND) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).SetMe(@ptrCast(*const IWABObject, self), lpIAB, ulFlags, sbEID, hwnd); } };} pub usingnamespace MethodMixin(@This()); }; pub const IWABOBJECT_QueryInterface_METHOD = fn( riid: ?*const Guid, ppvObj: ?*?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_AddRef_METHOD = fn( ) callconv(@import("std").os.windows.WINAPI) u32; pub const IWABOBJECT_Release_METHOD = fn( ) callconv(@import("std").os.windows.WINAPI) u32; pub const IWABOBJECT_GetLastError_METHOD = fn( hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_AllocateBuffer_METHOD = fn( cbSize: u32, lppBuffer: ?*?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_AllocateMore_METHOD = fn( cbSize: u32, lpObject: ?*c_void, lppBuffer: ?*?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_FreeBuffer_METHOD = fn( lpBuffer: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_Backup_METHOD = fn( lpFileName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_Import_METHOD = fn( lpWIP: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_Find_METHOD = fn( lpIAB: ?*IAddrBook, hWnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_VCardDisplay_METHOD = fn( lpIAB: ?*IAddrBook, hWnd: ?HWND, lpszFileName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_LDAPUrl_METHOD = fn( lpIAB: ?*IAddrBook, hWnd: ?HWND, ulFlags: u32, lpszURL: ?PSTR, lppMailUser: ?*?*IMailUser, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_VCardCreate_METHOD = fn( lpIAB: ?*IAddrBook, ulFlags: u32, lpszVCard: ?PSTR, lpMailUser: ?*IMailUser, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_VCardRetrieve_METHOD = fn( lpIAB: ?*IAddrBook, ulFlags: u32, lpszVCard: ?PSTR, lppMailUser: ?*?*IMailUser, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_GetMe_METHOD = fn( lpIAB: ?*IAddrBook, ulFlags: u32, lpdwAction: ?*u32, lpsbEID: ?*SBinary, hwnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_SetMe_METHOD = fn( lpIAB: ?*IAddrBook, ulFlags: u32, sbEID: SBinary, hwnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_ = extern struct { pub const VTable = extern struct { QueryInterface: fn( self: *const IWABOBJECT_, riid: ?*const Guid, ppvObj: ?*?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddRef: fn( self: *const IWABOBJECT_, ) callconv(@import("std").os.windows.WINAPI) u32, Release: fn( self: *const IWABOBJECT_, ) callconv(@import("std").os.windows.WINAPI) u32, GetLastError: fn( self: *const IWABOBJECT_, hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AllocateBuffer: fn( self: *const IWABOBJECT_, cbSize: u32, lppBuffer: ?*?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AllocateMore: fn( self: *const IWABOBJECT_, cbSize: u32, lpObject: ?*c_void, lppBuffer: ?*?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FreeBuffer: fn( self: *const IWABOBJECT_, lpBuffer: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Backup: fn( self: *const IWABOBJECT_, lpFileName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Import: fn( self: *const IWABOBJECT_, lpWIP: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Find: fn( self: *const IWABOBJECT_, lpIAB: ?*IAddrBook, hWnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT, VCardDisplay: fn( self: *const IWABOBJECT_, lpIAB: ?*IAddrBook, hWnd: ?HWND, lpszFileName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LDAPUrl: fn( self: *const IWABOBJECT_, lpIAB: ?*IAddrBook, hWnd: ?HWND, ulFlags: u32, lpszURL: ?PSTR, lppMailUser: ?*?*IMailUser, ) callconv(@import("std").os.windows.WINAPI) HRESULT, VCardCreate: fn( self: *const IWABOBJECT_, lpIAB: ?*IAddrBook, ulFlags: u32, lpszVCard: ?PSTR, lpMailUser: ?*IMailUser, ) callconv(@import("std").os.windows.WINAPI) HRESULT, VCardRetrieve: fn( self: *const IWABOBJECT_, lpIAB: ?*IAddrBook, ulFlags: u32, lpszVCard: ?PSTR, lppMailUser: ?*?*IMailUser, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMe: fn( self: *const IWABOBJECT_, lpIAB: ?*IAddrBook, ulFlags: u32, lpdwAction: ?*u32, lpsbEID: ?*SBinary, hwnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetMe: fn( self: *const IWABOBJECT_, lpIAB: ?*IAddrBook, ulFlags: u32, sbEID: SBinary, hwnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__QueryInterface(self: *const T, riid: ?*const Guid, ppvObj: ?*?*c_void) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).QueryInterface(@ptrCast(*const IWABOBJECT_, self), riid, ppvObj); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__AddRef(self: *const T) callconv(.Inline) u32 { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).AddRef(@ptrCast(*const IWABOBJECT_, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__Release(self: *const T) callconv(.Inline) u32 { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).Release(@ptrCast(*const IWABOBJECT_, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__GetLastError(self: *const T, hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).GetLastError(@ptrCast(*const IWABOBJECT_, self), hResult, ulFlags, lppMAPIError); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__AllocateBuffer(self: *const T, cbSize: u32, lppBuffer: ?*?*c_void) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).AllocateBuffer(@ptrCast(*const IWABOBJECT_, self), cbSize, lppBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__AllocateMore(self: *const T, cbSize: u32, lpObject: ?*c_void, lppBuffer: ?*?*c_void) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).AllocateMore(@ptrCast(*const IWABOBJECT_, self), cbSize, lpObject, lppBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__FreeBuffer(self: *const T, lpBuffer: ?*c_void) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).FreeBuffer(@ptrCast(*const IWABOBJECT_, self), lpBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__Backup(self: *const T, lpFileName: ?PSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).Backup(@ptrCast(*const IWABOBJECT_, self), lpFileName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__Import(self: *const T, lpWIP: ?PSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).Import(@ptrCast(*const IWABOBJECT_, self), lpWIP); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__Find(self: *const T, lpIAB: ?*IAddrBook, hWnd: ?HWND) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).Find(@ptrCast(*const IWABOBJECT_, self), lpIAB, hWnd); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__VCardDisplay(self: *const T, lpIAB: ?*IAddrBook, hWnd: ?HWND, lpszFileName: ?PSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).VCardDisplay(@ptrCast(*const IWABOBJECT_, self), lpIAB, hWnd, lpszFileName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__LDAPUrl(self: *const T, lpIAB: ?*IAddrBook, hWnd: ?HWND, ulFlags: u32, lpszURL: ?PSTR, lppMailUser: ?*?*IMailUser) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).LDAPUrl(@ptrCast(*const IWABOBJECT_, self), lpIAB, hWnd, ulFlags, lpszURL, lppMailUser); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__VCardCreate(self: *const T, lpIAB: ?*IAddrBook, ulFlags: u32, lpszVCard: ?PSTR, lpMailUser: ?*IMailUser) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).VCardCreate(@ptrCast(*const IWABOBJECT_, self), lpIAB, ulFlags, lpszVCard, lpMailUser); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__VCardRetrieve(self: *const T, lpIAB: ?*IAddrBook, ulFlags: u32, lpszVCard: ?PSTR, lppMailUser: ?*?*IMailUser) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).VCardRetrieve(@ptrCast(*const IWABOBJECT_, self), lpIAB, ulFlags, lpszVCard, lppMailUser); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__GetMe(self: *const T, lpIAB: ?*IAddrBook, ulFlags: u32, lpdwAction: ?*u32, lpsbEID: ?*SBinary, hwnd: ?HWND) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).GetMe(@ptrCast(*const IWABOBJECT_, self), lpIAB, ulFlags, lpdwAction, lpsbEID, hwnd); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__SetMe(self: *const T, lpIAB: ?*IAddrBook, ulFlags: u32, sbEID: SBinary, hwnd: ?HWND) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).SetMe(@ptrCast(*const IWABOBJECT_, self), lpIAB, ulFlags, sbEID, hwnd); } };} pub usingnamespace MethodMixin(@This()); }; pub const WAB_PARAM = extern struct { cbSize: u32, hwnd: ?HWND, szFileName: ?PSTR, ulFlags: u32, guidPSExt: Guid, }; pub const LPWABOPEN = fn( lppAdrBook: ?*?*IAddrBook, lppWABObject: ?*?*IWABObject, lpWP: ?*WAB_PARAM, Reserved2: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const LPWABOPENEX = fn( lppAdrBook: ?*?*IAddrBook, lppWABObject: ?*?*IWABObject, lpWP: ?*WAB_PARAM, Reserved: u32, fnAllocateBuffer: ?LPALLOCATEBUFFER, fnAllocateMore: ?LPALLOCATEMORE, fnFreeBuffer: ?LPFREEBUFFER, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const WABIMPORTPARAM = extern struct { cbSize: u32, lpAdrBook: ?*IAddrBook, hWnd: ?HWND, ulFlags: u32, lpszFileName: ?PSTR, }; pub const WABEXTDISPLAY = extern struct { cbSize: u32, lpWABObject: ?*IWABObject, lpAdrBook: ?*IAddrBook, lpPropObj: ?*IMAPIProp, fReadOnly: BOOL, fDataChanged: BOOL, ulFlags: u32, lpv: ?*c_void, lpsz: ?*i8, }; // TODO: this type is limited to platform 'windows5.0' const IID_IWABExtInit_Value = @import("../zig.zig").Guid.initString("ea22ebf0-87a4-11d1-9acf-00a0c91f9c8b"); pub const IID_IWABExtInit = &IID_IWABExtInit_Value; pub const IWABExtInit = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IWABExtInit, lpWABExtDisplay: ?*WABEXTDISPLAY, ) 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 IWABExtInit_Initialize(self: *const T, lpWABExtDisplay: ?*WABEXTDISPLAY) callconv(.Inline) HRESULT { return @ptrCast(*const IWABExtInit.VTable, self.vtable).Initialize(@ptrCast(*const IWABExtInit, self), lpWABExtDisplay); } };} pub usingnamespace MethodMixin(@This()); }; pub const Gender = enum(i32) { Unspecified = 0, Female = 1, Male = 2, }; pub const genderUnspecified = Gender.Unspecified; pub const genderFemale = Gender.Female; pub const genderMale = Gender.Male; //-------------------------------------------------------------------------------- // 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 (10) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const CY = @import("../system/system_services.zig").CY; const FILETIME = @import("../foundation.zig").FILETIME; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const IUnknown = @import("../system/com.zig").IUnknown; const LARGE_INTEGER = @import("../system/system_services.zig").LARGE_INTEGER; const PSTR = @import("../foundation.zig").PSTR; const PWSTR = @import("../foundation.zig").PWSTR; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "LPALLOCATEBUFFER")) { _ = LPALLOCATEBUFFER; } if (@hasDecl(@This(), "LPALLOCATEMORE")) { _ = LPALLOCATEMORE; } if (@hasDecl(@This(), "LPFREEBUFFER")) { _ = LPFREEBUFFER; } if (@hasDecl(@This(), "LPNOTIFCALLBACK")) { _ = LPNOTIFCALLBACK; } if (@hasDecl(@This(), "LPFNABSDI")) { _ = LPFNABSDI; } if (@hasDecl(@This(), "LPFNDISMISS")) { _ = LPFNDISMISS; } if (@hasDecl(@This(), "LPFNBUTTON")) { _ = LPFNBUTTON; } if (@hasDecl(@This(), "IWABOBJECT_QueryInterface_METHOD")) { _ = IWABOBJECT_QueryInterface_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_AddRef_METHOD")) { _ = IWABOBJECT_AddRef_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_Release_METHOD")) { _ = IWABOBJECT_Release_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_GetLastError_METHOD")) { _ = IWABOBJECT_GetLastError_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_AllocateBuffer_METHOD")) { _ = IWABOBJECT_AllocateBuffer_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_AllocateMore_METHOD")) { _ = IWABOBJECT_AllocateMore_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_FreeBuffer_METHOD")) { _ = IWABOBJECT_FreeBuffer_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_Backup_METHOD")) { _ = IWABOBJECT_Backup_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_Import_METHOD")) { _ = IWABOBJECT_Import_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_Find_METHOD")) { _ = IWABOBJECT_Find_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_VCardDisplay_METHOD")) { _ = IWABOBJECT_VCardDisplay_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_LDAPUrl_METHOD")) { _ = IWABOBJECT_LDAPUrl_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_VCardCreate_METHOD")) { _ = IWABOBJECT_VCardCreate_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_VCardRetrieve_METHOD")) { _ = IWABOBJECT_VCardRetrieve_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_GetMe_METHOD")) { _ = IWABOBJECT_GetMe_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_SetMe_METHOD")) { _ = IWABOBJECT_SetMe_METHOD; } if (@hasDecl(@This(), "LPWABOPEN")) { _ = LPWABOPEN; } if (@hasDecl(@This(), "LPWABOPENEX")) { _ = LPWABOPENEX; } @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; } } }
deps/zigwin32/win32/system/address_book.zig
const std = @import("std"); const builtin = @import("builtin"); const Target = std.Target; const fs = std.fs; const Allocator = std.mem.Allocator; const Batch = std.event.Batch; const build_options = @import("build_options"); const is_darwin = Target.current.isDarwin(); const is_windows = Target.current.os.tag == .windows; const is_gnu = Target.current.isGnu(); const log = std.log.scoped(.libc_installation); usingnamespace @import("windows_sdk.zig"); /// See the render function implementation for documentation of the fields. pub const LibCInstallation = struct { include_dir: ?[]const u8 = null, sys_include_dir: ?[]const u8 = null, crt_dir: ?[]const u8 = null, msvc_lib_dir: ?[]const u8 = null, kernel32_lib_dir: ?[]const u8 = null, pub const FindError = error{ OutOfMemory, FileSystem, UnableToSpawnCCompiler, CCompilerExitCode, CCompilerCrashed, CCompilerCannotFindHeaders, LibCRuntimeNotFound, LibCStdLibHeaderNotFound, LibCKernel32LibNotFound, UnsupportedArchitecture, WindowsSdkNotFound, ZigIsTheCCompiler, }; pub fn parse( allocator: *Allocator, libc_file: []const u8, ) !LibCInstallation { var self: LibCInstallation = .{}; const fields = std.meta.fields(LibCInstallation); const FoundKey = struct { found: bool, allocated: ?[:0]u8, }; var found_keys = [1]FoundKey{FoundKey{ .found = false, .allocated = null }} ** fields.len; errdefer { self = .{}; for (found_keys) |found_key| { if (found_key.allocated) |s| allocator.free(s); } } const contents = try std.fs.cwd().readFileAlloc(allocator, libc_file, std.math.maxInt(usize)); defer allocator.free(contents); var it = std.mem.tokenize(contents, "\n"); while (it.next()) |line| { if (line.len == 0 or line[0] == '#') continue; var line_it = std.mem.split(line, "="); const name = line_it.next() orelse { log.err("missing equal sign after field name\n", .{}); return error.ParseError; }; const value = line_it.rest(); inline for (fields) |field, i| { if (std.mem.eql(u8, name, field.name)) { found_keys[i].found = true; if (value.len == 0) { @field(self, field.name) = null; } else { found_keys[i].allocated = try std.mem.dupeZ(allocator, u8, value); @field(self, field.name) = found_keys[i].allocated; } break; } } } inline for (fields) |field, i| { if (!found_keys[i].found) { log.err("missing field: {}\n", .{field.name}); return error.ParseError; } } if (self.include_dir == null) { log.err("include_dir may not be empty\n", .{}); return error.ParseError; } if (self.sys_include_dir == null) { log.err("sys_include_dir may not be empty\n", .{}); return error.ParseError; } if (self.crt_dir == null and !is_darwin) { log.err("crt_dir may not be empty for {}\n", .{@tagName(Target.current.os.tag)}); return error.ParseError; } if (self.msvc_lib_dir == null and is_windows and !is_gnu) { log.err("msvc_lib_dir may not be empty for {}-{}\n", .{ @tagName(Target.current.os.tag), @tagName(Target.current.abi), }); return error.ParseError; } if (self.kernel32_lib_dir == null and is_windows and !is_gnu) { log.err("kernel32_lib_dir may not be empty for {}-{}\n", .{ @tagName(Target.current.os.tag), @tagName(Target.current.abi), }); return error.ParseError; } return self; } pub fn render(self: LibCInstallation, out: anytype) !void { @setEvalBranchQuota(4000); const include_dir = self.include_dir orelse ""; const sys_include_dir = self.sys_include_dir orelse ""; const crt_dir = self.crt_dir orelse ""; const msvc_lib_dir = self.msvc_lib_dir orelse ""; const kernel32_lib_dir = self.kernel32_lib_dir orelse ""; try out.print( \\# The directory that contains `stdlib.h`. \\# On POSIX-like systems, include directories be found with: `cc -E -Wp,-v -xc /dev/null` \\include_dir={} \\ \\# The system-specific include directory. May be the same as `include_dir`. \\# On Windows it's the directory that includes `vcruntime.h`. \\# On POSIX it's the directory that includes `sys/errno.h`. \\sys_include_dir={} \\ \\# The directory that contains `crt1.o` or `crt2.o`. \\# On POSIX, can be found with `cc -print-file-name=crt1.o`. \\# Not needed when targeting MacOS. \\crt_dir={} \\ \\# The directory that contains `vcruntime.lib`. \\# Only needed when targeting MSVC on Windows. \\msvc_lib_dir={} \\ \\# The directory that contains `kernel32.lib`. \\# Only needed when targeting MSVC on Windows. \\kernel32_lib_dir={} \\ , .{ include_dir, sys_include_dir, crt_dir, msvc_lib_dir, kernel32_lib_dir, }); } pub const FindNativeOptions = struct { allocator: *Allocator, /// If enabled, will print human-friendly errors to stderr. verbose: bool = false, }; /// Finds the default, native libc. pub fn findNative(args: FindNativeOptions) FindError!LibCInstallation { var self: LibCInstallation = .{}; if (is_windows) { if (!build_options.have_llvm) return error.WindowsSdkNotFound; var sdk: *ZigWindowsSDK = undefined; switch (zig_find_windows_sdk(&sdk)) { .None => { defer zig_free_windows_sdk(sdk); var batch = Batch(FindError!void, 5, .auto_async).init(); batch.add(&async self.findNativeMsvcIncludeDir(args, sdk)); batch.add(&async self.findNativeMsvcLibDir(args, sdk)); batch.add(&async self.findNativeKernel32LibDir(args, sdk)); batch.add(&async self.findNativeIncludeDirWindows(args, sdk)); batch.add(&async self.findNativeCrtDirWindows(args, sdk)); try batch.wait(); }, .OutOfMemory => return error.OutOfMemory, .NotFound => return error.WindowsSdkNotFound, .PathTooLong => return error.WindowsSdkNotFound, } } else { try blk: { var batch = Batch(FindError!void, 2, .auto_async).init(); errdefer batch.wait() catch {}; batch.add(&async self.findNativeIncludeDirPosix(args)); switch (Target.current.os.tag) { .freebsd, .netbsd, .openbsd => self.crt_dir = try std.mem.dupeZ(args.allocator, u8, "/usr/lib"), .linux, .dragonfly => batch.add(&async self.findNativeCrtDirPosix(args)), else => {}, } break :blk batch.wait(); }; } return self; } /// Must be the same allocator passed to `parse` or `findNative`. pub fn deinit(self: *LibCInstallation, allocator: *Allocator) void { const fields = std.meta.fields(LibCInstallation); inline for (fields) |field| { if (@field(self, field.name)) |payload| { allocator.free(payload); } } self.* = undefined; } fn findNativeIncludeDirPosix(self: *LibCInstallation, args: FindNativeOptions) FindError!void { const allocator = args.allocator; const dev_null = if (is_windows) "nul" else "/dev/null"; const cc_exe = std.os.getenvZ("CC") orelse default_cc_exe; const argv = [_][]const u8{ cc_exe, "-E", "-Wp,-v", "-xc", dev_null, }; var env_map = try std.process.getEnvMap(allocator); defer env_map.deinit(); // Detect infinite loops. const inf_loop_env_key = "ZIG_IS_DETECTING_LIBC_PATHS"; if (env_map.get(inf_loop_env_key) != null) return error.ZigIsTheCCompiler; try env_map.set(inf_loop_env_key, "1"); const exec_res = std.ChildProcess.exec(.{ .allocator = allocator, .argv = &argv, .max_output_bytes = 1024 * 1024, .env_map = &env_map, // Some C compilers, such as Clang, are known to rely on argv[0] to find the path // to their own executable, without even bothering to resolve PATH. This results in the message: // error: unable to execute command: Executable "" doesn't exist! // So we use the expandArg0 variant of ChildProcess to give them a helping hand. .expand_arg0 = .expand, }) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => { printVerboseInvocation(&argv, null, args.verbose, null); return error.UnableToSpawnCCompiler; }, }; defer { allocator.free(exec_res.stdout); allocator.free(exec_res.stderr); } switch (exec_res.term) { .Exited => |code| if (code != 0) { printVerboseInvocation(&argv, null, args.verbose, exec_res.stderr); return error.CCompilerExitCode; }, else => { printVerboseInvocation(&argv, null, args.verbose, exec_res.stderr); return error.CCompilerCrashed; }, } var it = std.mem.tokenize(exec_res.stderr, "\n\r"); var search_paths = std.ArrayList([]const u8).init(allocator); defer search_paths.deinit(); while (it.next()) |line| { if (line.len != 0 and line[0] == ' ') { try search_paths.append(line); } } if (search_paths.items.len == 0) { return error.CCompilerCannotFindHeaders; } const include_dir_example_file = "stdlib.h"; const sys_include_dir_example_file = if (is_windows) "sys\\types.h" else "sys/errno.h"; var path_i: usize = 0; while (path_i < search_paths.items.len) : (path_i += 1) { // search in reverse order const search_path_untrimmed = search_paths.items[search_paths.items.len - path_i - 1]; const search_path = std.mem.trimLeft(u8, search_path_untrimmed, " "); var search_dir = fs.cwd().openDir(search_path, .{}) catch |err| switch (err) { error.FileNotFound, error.NotDir, error.NoDevice, => continue, else => return error.FileSystem, }; defer search_dir.close(); if (self.include_dir == null) { if (search_dir.accessZ(include_dir_example_file, .{})) |_| { self.include_dir = try std.mem.dupeZ(allocator, u8, search_path); } else |err| switch (err) { error.FileNotFound => {}, else => return error.FileSystem, } } if (self.sys_include_dir == null) { if (search_dir.accessZ(sys_include_dir_example_file, .{})) |_| { self.sys_include_dir = try std.mem.dupeZ(allocator, u8, search_path); } else |err| switch (err) { error.FileNotFound => {}, else => return error.FileSystem, } } if (self.include_dir != null and self.sys_include_dir != null) { // Success. return; } } return error.LibCStdLibHeaderNotFound; } fn findNativeIncludeDirWindows( self: *LibCInstallation, args: FindNativeOptions, sdk: *ZigWindowsSDK, ) FindError!void { const allocator = args.allocator; var search_buf: [2]Search = undefined; const searches = fillSearch(&search_buf, sdk); var result_buf = std.ArrayList(u8).init(allocator); defer result_buf.deinit(); for (searches) |search| { result_buf.shrink(0); try result_buf.outStream().print("{}\\Include\\{}\\ucrt", .{ search.path, search.version }); var dir = fs.cwd().openDir(result_buf.items, .{}) catch |err| switch (err) { error.FileNotFound, error.NotDir, error.NoDevice, => continue, else => return error.FileSystem, }; defer dir.close(); dir.accessZ("stdlib.h", .{}) catch |err| switch (err) { error.FileNotFound => continue, else => return error.FileSystem, }; self.include_dir = result_buf.toOwnedSlice(); return; } return error.LibCStdLibHeaderNotFound; } fn findNativeCrtDirWindows( self: *LibCInstallation, args: FindNativeOptions, sdk: *ZigWindowsSDK, ) FindError!void { const allocator = args.allocator; var search_buf: [2]Search = undefined; const searches = fillSearch(&search_buf, sdk); var result_buf = std.ArrayList(u8).init(allocator); defer result_buf.deinit(); const arch_sub_dir = switch (builtin.arch) { .i386 => "x86", .x86_64 => "x64", .arm, .armeb => "arm", else => return error.UnsupportedArchitecture, }; for (searches) |search| { result_buf.shrink(0); try result_buf.outStream().print("{}\\Lib\\{}\\ucrt\\{}", .{ search.path, search.version, arch_sub_dir }); var dir = fs.cwd().openDir(result_buf.items, .{}) catch |err| switch (err) { error.FileNotFound, error.NotDir, error.NoDevice, => continue, else => return error.FileSystem, }; defer dir.close(); dir.accessZ("ucrt.lib", .{}) catch |err| switch (err) { error.FileNotFound => continue, else => return error.FileSystem, }; self.crt_dir = result_buf.toOwnedSlice(); return; } return error.LibCRuntimeNotFound; } fn findNativeCrtDirPosix(self: *LibCInstallation, args: FindNativeOptions) FindError!void { self.crt_dir = try ccPrintFileName(.{ .allocator = args.allocator, .search_basename = "crt1.o", .want_dirname = .only_dir, .verbose = args.verbose, }); } fn findNativeKernel32LibDir( self: *LibCInstallation, args: FindNativeOptions, sdk: *ZigWindowsSDK, ) FindError!void { const allocator = args.allocator; var search_buf: [2]Search = undefined; const searches = fillSearch(&search_buf, sdk); var result_buf = std.ArrayList(u8).init(allocator); defer result_buf.deinit(); const arch_sub_dir = switch (builtin.arch) { .i386 => "x86", .x86_64 => "x64", .arm, .armeb => "arm", else => return error.UnsupportedArchitecture, }; for (searches) |search| { result_buf.shrink(0); const stream = result_buf.outStream(); try stream.print("{}\\Lib\\{}\\um\\{}", .{ search.path, search.version, arch_sub_dir }); var dir = fs.cwd().openDir(result_buf.items, .{}) catch |err| switch (err) { error.FileNotFound, error.NotDir, error.NoDevice, => continue, else => return error.FileSystem, }; defer dir.close(); dir.accessZ("kernel32.lib", .{}) catch |err| switch (err) { error.FileNotFound => continue, else => return error.FileSystem, }; self.kernel32_lib_dir = result_buf.toOwnedSlice(); return; } return error.LibCKernel32LibNotFound; } fn findNativeMsvcIncludeDir( self: *LibCInstallation, args: FindNativeOptions, sdk: *ZigWindowsSDK, ) FindError!void { const allocator = args.allocator; const msvc_lib_dir_ptr = sdk.msvc_lib_dir_ptr orelse return error.LibCStdLibHeaderNotFound; const msvc_lib_dir = msvc_lib_dir_ptr[0..sdk.msvc_lib_dir_len]; const up1 = fs.path.dirname(msvc_lib_dir) orelse return error.LibCStdLibHeaderNotFound; const up2 = fs.path.dirname(up1) orelse return error.LibCStdLibHeaderNotFound; const dir_path = try fs.path.join(allocator, &[_][]const u8{ up2, "include" }); errdefer allocator.free(dir_path); var dir = fs.cwd().openDir(dir_path, .{}) catch |err| switch (err) { error.FileNotFound, error.NotDir, error.NoDevice, => return error.LibCStdLibHeaderNotFound, else => return error.FileSystem, }; defer dir.close(); dir.accessZ("vcruntime.h", .{}) catch |err| switch (err) { error.FileNotFound => return error.LibCStdLibHeaderNotFound, else => return error.FileSystem, }; self.sys_include_dir = dir_path; } fn findNativeMsvcLibDir( self: *LibCInstallation, args: FindNativeOptions, sdk: *ZigWindowsSDK, ) FindError!void { const allocator = args.allocator; const msvc_lib_dir_ptr = sdk.msvc_lib_dir_ptr orelse return error.LibCRuntimeNotFound; self.msvc_lib_dir = try std.mem.dupeZ(allocator, u8, msvc_lib_dir_ptr[0..sdk.msvc_lib_dir_len]); } }; const default_cc_exe = if (is_windows) "cc.exe" else "cc"; pub const CCPrintFileNameOptions = struct { allocator: *Allocator, search_basename: []const u8, want_dirname: enum { full_path, only_dir }, verbose: bool = false, }; /// caller owns returned memory fn ccPrintFileName(args: CCPrintFileNameOptions) ![:0]u8 { const allocator = args.allocator; const cc_exe = std.os.getenvZ("CC") orelse default_cc_exe; const arg1 = try std.fmt.allocPrint(allocator, "-print-file-name={}", .{args.search_basename}); defer allocator.free(arg1); const argv = [_][]const u8{ cc_exe, arg1 }; var env_map = try std.process.getEnvMap(allocator); defer env_map.deinit(); // Detect infinite loops. const inf_loop_env_key = "ZIG_IS_DETECTING_LIBC_PATHS"; if (env_map.get(inf_loop_env_key) != null) return error.ZigIsTheCCompiler; try env_map.set(inf_loop_env_key, "1"); const exec_res = std.ChildProcess.exec(.{ .allocator = allocator, .argv = &argv, .max_output_bytes = 1024 * 1024, .env_map = &env_map, // Some C compilers, such as Clang, are known to rely on argv[0] to find the path // to their own executable, without even bothering to resolve PATH. This results in the message: // error: unable to execute command: Executable "" doesn't exist! // So we use the expandArg0 variant of ChildProcess to give them a helping hand. .expand_arg0 = .expand, }) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => return error.UnableToSpawnCCompiler, }; defer { allocator.free(exec_res.stdout); allocator.free(exec_res.stderr); } switch (exec_res.term) { .Exited => |code| if (code != 0) { printVerboseInvocation(&argv, args.search_basename, args.verbose, exec_res.stderr); return error.CCompilerExitCode; }, else => { printVerboseInvocation(&argv, args.search_basename, args.verbose, exec_res.stderr); return error.CCompilerCrashed; }, } var it = std.mem.tokenize(exec_res.stdout, "\n\r"); const line = it.next() orelse return error.LibCRuntimeNotFound; // When this command fails, it returns exit code 0 and duplicates the input file name. // So we detect failure by checking if the output matches exactly the input. if (std.mem.eql(u8, line, args.search_basename)) return error.LibCRuntimeNotFound; switch (args.want_dirname) { .full_path => return std.mem.dupeZ(allocator, u8, line), .only_dir => { const dirname = fs.path.dirname(line) orelse return error.LibCRuntimeNotFound; return std.mem.dupeZ(allocator, u8, dirname); }, } } fn printVerboseInvocation( argv: []const []const u8, search_basename: ?[]const u8, verbose: bool, stderr: ?[]const u8, ) void { if (!verbose) return; if (search_basename) |s| { std.debug.warn("Zig attempted to find the file '{}' by executing this command:\n", .{s}); } else { std.debug.warn("Zig attempted to find the path to native system libc headers by executing this command:\n", .{}); } for (argv) |arg, i| { if (i != 0) std.debug.warn(" ", .{}); std.debug.warn("{}", .{arg}); } std.debug.warn("\n", .{}); if (stderr) |s| { std.debug.warn("Output:\n==========\n{}\n==========\n", .{s}); } } const Search = struct { path: []const u8, version: []const u8, }; fn fillSearch(search_buf: *[2]Search, sdk: *ZigWindowsSDK) []Search { var search_end: usize = 0; if (sdk.path10_ptr) |path10_ptr| { if (sdk.version10_ptr) |version10_ptr| { search_buf[search_end] = Search{ .path = path10_ptr[0..sdk.path10_len], .version = version10_ptr[0..sdk.version10_len], }; search_end += 1; } } if (sdk.path81_ptr) |path81_ptr| { if (sdk.version81_ptr) |version81_ptr| { search_buf[search_end] = Search{ .path = path81_ptr[0..sdk.path81_len], .version = version81_ptr[0..sdk.version81_len], }; search_end += 1; } } return search_buf[0..search_end]; }
src/libc_installation.zig
const std = @import("../std.zig"); const mem = std.mem; const math = std.math; const debug = std.debug; const assert = std.debug.assert; const testing = std.testing; const htest = @import("test.zig"); const Vector = std.meta.Vector; pub const State = struct { pub const BLOCKBYTES = 48; pub const RATE = 16; data: [BLOCKBYTES / 4]u32 align(16), const Self = @This(); pub fn init(initial_state: [State.BLOCKBYTES]u8) Self { var data: [BLOCKBYTES / 4]u32 = undefined; var i: usize = 0; while (i < State.BLOCKBYTES) : (i += 4) { data[i / 4] = mem.readIntNative(u32, initial_state[i..][0..4]); } return Self{ .data = data }; } /// TODO follow the span() convention instead of having this and `toSliceConst` pub fn toSlice(self: *Self) *[BLOCKBYTES]u8 { return mem.asBytes(&self.data); } /// TODO follow the span() convention instead of having this and `toSlice` pub fn toSliceConst(self: *const Self) *const [BLOCKBYTES]u8 { return mem.asBytes(&self.data); } inline fn endianSwap(self: *Self) void { for (self.data) |*w| { w.* = mem.littleToNative(u32, w.*); } } fn permute_unrolled(self: *Self) void { self.endianSwap(); const state = &self.data; comptime var round = @as(u32, 24); inline while (round > 0) : (round -= 1) { var column = @as(usize, 0); while (column < 4) : (column += 1) { const x = math.rotl(u32, state[column], 24); const y = math.rotl(u32, state[4 + column], 9); const z = state[8 + column]; state[8 + column] = ((x ^ (z << 1)) ^ ((y & z) << 2)); state[4 + column] = ((y ^ x) ^ ((x | z) << 1)); state[column] = ((z ^ y) ^ ((x & y) << 3)); } switch (round & 3) { 0 => { mem.swap(u32, &state[0], &state[1]); mem.swap(u32, &state[2], &state[3]); state[0] ^= round | 0x9e377900; }, 2 => { mem.swap(u32, &state[0], &state[2]); mem.swap(u32, &state[1], &state[3]); }, else => {}, } } self.endianSwap(); } fn permute_small(self: *Self) void { self.endianSwap(); const state = &self.data; var round = @as(u32, 24); while (round > 0) : (round -= 1) { var column = @as(usize, 0); while (column < 4) : (column += 1) { const x = math.rotl(u32, state[column], 24); const y = math.rotl(u32, state[4 + column], 9); const z = state[8 + column]; state[8 + column] = ((x ^ (z << 1)) ^ ((y & z) << 2)); state[4 + column] = ((y ^ x) ^ ((x | z) << 1)); state[column] = ((z ^ y) ^ ((x & y) << 3)); } switch (round & 3) { 0 => { mem.swap(u32, &state[0], &state[1]); mem.swap(u32, &state[2], &state[3]); state[0] ^= round | 0x9e377900; }, 2 => { mem.swap(u32, &state[0], &state[2]); mem.swap(u32, &state[1], &state[3]); }, else => {}, } } self.endianSwap(); } const Lane = Vector(4, u32); inline fn shift(x: Lane, comptime n: comptime_int) Lane { return x << @splat(4, @as(u5, n)); } fn permute_vectorized(self: *Self) void { self.endianSwap(); const state = &self.data; var x = Lane{ state[0], state[1], state[2], state[3] }; var y = Lane{ state[4], state[5], state[6], state[7] }; var z = Lane{ state[8], state[9], state[10], state[11] }; var round = @as(u32, 24); while (round > 0) : (round -= 1) { x = math.rotl(Lane, x, 24); y = math.rotl(Lane, y, 9); const newz = x ^ shift(z, 1) ^ shift(y & z, 2); const newy = y ^ x ^ shift(x | z, 1); const newx = z ^ y ^ shift(x & y, 3); x = newx; y = newy; z = newz; switch (round & 3) { 0 => { x = @shuffle(u32, x, undefined, [_]i32{ 1, 0, 3, 2 }); x[0] ^= round | 0x9e377900; }, 2 => { x = @shuffle(u32, x, undefined, [_]i32{ 2, 3, 0, 1 }); }, else => {}, } } comptime var i: usize = 0; inline while (i < 4) : (i += 1) { state[0 + i] = x[i]; state[4 + i] = y[i]; state[8 + i] = z[i]; } self.endianSwap(); } pub const permute = if (std.Target.current.cpu.arch == .x86_64) impl: { break :impl permute_vectorized; } else if (std.builtin.mode == .ReleaseSmall) impl: { break :impl permute_small; } else impl: { break :impl permute_unrolled; }; pub fn squeeze(self: *Self, out: []u8) void { var i = @as(usize, 0); while (i + RATE <= out.len) : (i += RATE) { self.permute(); mem.copy(u8, out[i..], self.toSliceConst()[0..RATE]); } const leftover = out.len - i; if (leftover != 0) { self.permute(); mem.copy(u8, out[i..], self.toSliceConst()[0..leftover]); } } }; test "permute" { // test vector from gimli-20170627 const tv_input = [3][4]u32{ [4]u32{ 0x00000000, 0x9e3779ba, 0x3c6ef37a, 0xdaa66d46 }, [4]u32{ 0x78dde724, 0x1715611a, 0xb54cdb2e, 0x53845566 }, [4]u32{ 0xf1bbcfc8, 0x8ff34a5a, 0x2e2ac522, 0xcc624026 }, }; var input: [48]u8 = undefined; var i: usize = 0; while (i < 12) : (i += 1) { mem.writeIntLittle(u32, input[i * 4 ..][0..4], tv_input[i / 4][i % 4]); } var state = State.init(input); state.permute(); const tv_output = [3][4]u32{ [4]u32{ 0xba11c85a, 0x91bad119, 0x380ce880, 0xd24c2c68 }, [4]u32{ 0x3eceffea, 0x277a921c, 0x4f73a0bd, 0xda5a9cd8 }, [4]u32{ 0x84b673f0, 0x34e52ff7, 0x9e2bef49, 0xf41bb8d6 }, }; var expected_output: [48]u8 = undefined; i = 0; while (i < 12) : (i += 1) { mem.writeIntLittle(u32, expected_output[i * 4 ..][0..4], tv_output[i / 4][i % 4]); } testing.expectEqualSlices(u8, state.toSliceConst(), expected_output[0..]); } pub const Hash = struct { state: State, buf_off: usize, pub const block_length = State.RATE; pub const digest_length = 32; pub const Options = struct {}; const Self = @This(); pub fn init(options: Options) Self { return Self{ .state = State{ .data = [_]u32{0} ** (State.BLOCKBYTES / 4) }, .buf_off = 0, }; } /// Also known as 'absorb' pub fn update(self: *Self, data: []const u8) void { const buf = self.state.toSlice(); var in = data; while (in.len > 0) { var left = State.RATE - self.buf_off; if (left == 0) { self.state.permute(); self.buf_off = 0; left = State.RATE; } const ps = math.min(in.len, left); for (buf[self.buf_off .. self.buf_off + ps]) |*p, i| { p.* ^= in[i]; } self.buf_off += ps; in = in[ps..]; } } /// Finish the current hashing operation, writing the hash to `out` /// /// From 4.9 "Application to hashing" /// By default, Gimli-Hash provides a fixed-length output of 32 bytes /// (the concatenation of two 16-byte blocks). However, Gimli-Hash can /// be used as an β€œextendable one-way function” (XOF). pub fn final(self: *Self, out: []u8) void { const buf = self.state.toSlice(); // XOR 1 into the next byte of the state buf[self.buf_off] ^= 1; // XOR 1 into the last byte of the state, position 47. buf[buf.len - 1] ^= 1; self.state.squeeze(out); } }; pub fn hash(out: []u8, in: []const u8, options: Hash.Options) void { var st = Hash.init(options); st.update(in); st.final(out); } test "hash" { // a test vector (30) from NIST KAT submission. var msg: [58 / 2]u8 = undefined; try std.fmt.hexToBytes(&msg, "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C"); var md: [32]u8 = undefined; hash(&md, &msg, .{}); htest.assertEqual("1C9A03DC6A5DDC5444CFC6F4B154CFF5CF081633B2CEA4D7D0AE7CCFED5AAA44", &md); } pub const Aead = struct { pub const tag_length = State.RATE; pub const nonce_length = 16; pub const key_length = 32; /// ad: Associated Data /// npub: public nonce /// k: private key fn init(ad: []const u8, npub: [nonce_length]u8, k: [key_length]u8) State { var state = State{ .data = undefined, }; const buf = state.toSlice(); // Gimli-Cipher initializes a 48-byte Gimli state to a 16-byte nonce // followed by a 32-byte key. assert(npub.len + k.len == State.BLOCKBYTES); std.mem.copy(u8, buf[0..npub.len], &npub); std.mem.copy(u8, buf[npub.len .. npub.len + k.len], &k); // It then applies the Gimli permutation. state.permute(); { // Gimli-Cipher then handles each block of associated data, including // exactly one final non-full block, in the same way as Gimli-Hash. var data = ad; while (data.len >= State.RATE) : (data = data[State.RATE..]) { for (buf[0..State.RATE]) |*p, i| { p.* ^= data[i]; } state.permute(); } for (buf[0..data.len]) |*p, i| { p.* ^= data[i]; } // XOR 1 into the next byte of the state buf[data.len] ^= 1; // XOR 1 into the last byte of the state, position 47. buf[buf.len - 1] ^= 1; state.permute(); } return state; } /// c: ciphertext: output buffer should be of size m.len /// tag: authentication tag: output MAC /// m: message /// ad: Associated Data /// npub: public nonce /// k: private key pub fn encrypt(c: []u8, tag: *[tag_length]u8, m: []const u8, ad: []const u8, npub: [nonce_length]u8, k: [key_length]u8) void { assert(c.len == m.len); var state = Aead.init(ad, npub, k); const buf = state.toSlice(); // Gimli-Cipher then handles each block of plaintext, including // exactly one final non-full block, in the same way as Gimli-Hash. // Whenever a plaintext byte is XORed into a state byte, the new state // byte is output as ciphertext. var in = m; var out = c; while (in.len >= State.RATE) : ({ in = in[State.RATE..]; out = out[State.RATE..]; }) { for (in[0..State.RATE]) |v, i| { buf[i] ^= v; } mem.copy(u8, out[0..State.RATE], buf[0..State.RATE]); state.permute(); } for (in[0..]) |v, i| { buf[i] ^= v; out[i] = buf[i]; } // XOR 1 into the next byte of the state buf[in.len] ^= 1; // XOR 1 into the last byte of the state, position 47. buf[buf.len - 1] ^= 1; state.permute(); // After the final non-full block of plaintext, the first 16 bytes // of the state are output as an authentication tag. std.mem.copy(u8, tag, buf[0..State.RATE]); } /// m: message: output buffer should be of size c.len /// c: ciphertext /// tag: authentication tag /// ad: Associated Data /// npub: public nonce /// k: private key /// NOTE: the check of the authentication tag is currently not done in constant time pub fn decrypt(m: []u8, c: []const u8, tag: [tag_length]u8, ad: []const u8, npub: [nonce_length]u8, k: [key_length]u8) !void { assert(c.len == m.len); var state = Aead.init(ad, npub, k); const buf = state.toSlice(); var in = c; var out = m; while (in.len >= State.RATE) : ({ in = in[State.RATE..]; out = out[State.RATE..]; }) { const d = in[0..State.RATE].*; for (d) |v, i| { out[i] = buf[i] ^ v; } mem.copy(u8, buf[0..State.RATE], d[0..State.RATE]); state.permute(); } for (buf[0..in.len]) |*p, i| { const d = in[i]; out[i] = p.* ^ d; p.* = d; } // XOR 1 into the next byte of the state buf[in.len] ^= 1; // XOR 1 into the last byte of the state, position 47. buf[buf.len - 1] ^= 1; state.permute(); // After the final non-full block of plaintext, the first 16 bytes // of the state are the authentication tag. // TODO: use a constant-time equality check here, see https://github.com/ziglang/zig/issues/1776 if (!mem.eql(u8, buf[0..State.RATE], &tag)) { @memset(m.ptr, undefined, m.len); return error.InvalidMessage; } } }; test "cipher" { var key: [32]u8 = undefined; try std.fmt.hexToBytes(&key, "<KEY>"); var nonce: [16]u8 = undefined; try std.fmt.hexToBytes(&nonce, "000102030405060708090A0B0C0D0E0F"); { // test vector (1) from NIST KAT submission. const ad: [0]u8 = undefined; const pt: [0]u8 = undefined; var ct: [pt.len]u8 = undefined; var tag: [16]u8 = undefined; Aead.encrypt(&ct, &tag, &pt, &ad, nonce, key); htest.assertEqual("", &ct); htest.assertEqual("14DA9BB7120BF58B985A8E00FDEBA15B", &tag); var pt2: [pt.len]u8 = undefined; try Aead.decrypt(&pt2, &ct, tag, &ad, nonce, key); testing.expectEqualSlices(u8, &pt, &pt2); } { // test vector (34) from NIST KAT submission. const ad: [0]u8 = undefined; var pt: [2 / 2]u8 = undefined; try std.fmt.hexToBytes(&pt, "00"); var ct: [pt.len]u8 = undefined; var tag: [16]u8 = undefined; Aead.encrypt(&ct, &tag, &pt, &ad, nonce, key); htest.assertEqual("7F", &ct); htest.assertEqual("80492C317B1CD58A1EDC3A0D3E9876FC", &tag); var pt2: [pt.len]u8 = undefined; try Aead.decrypt(&pt2, &ct, tag, &ad, nonce, key); testing.expectEqualSlices(u8, &pt, &pt2); } { // test vector (106) from NIST KAT submission. var ad: [12 / 2]u8 = undefined; try std.fmt.hexToBytes(&ad, "000102030405"); var pt: [6 / 2]u8 = undefined; try std.fmt.hexToBytes(&pt, "000102"); var ct: [pt.len]u8 = undefined; var tag: [16]u8 = undefined; Aead.encrypt(&ct, &tag, &pt, &ad, nonce, key); htest.assertEqual("484D35", &ct); htest.assertEqual("030BBEA23B61C00CED60A923BDCF9147", &tag); var pt2: [pt.len]u8 = undefined; try Aead.decrypt(&pt2, &ct, tag, &ad, nonce, key); testing.expectEqualSlices(u8, &pt, &pt2); } { // test vector (790) from NIST KAT submission. var ad: [60 / 2]u8 = undefined; try std.fmt.hexToBytes(&ad, "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D"); var pt: [46 / 2]u8 = undefined; try std.fmt.hexToBytes(&pt, "000102030405060708090A0B0C0D0E0F10111213141516"); var ct: [pt.len]u8 = undefined; var tag: [16]u8 = undefined; Aead.encrypt(&ct, &tag, &pt, &ad, nonce, key); htest.assertEqual("6815B4A0ECDAD01596EAD87D9E690697475D234C6A13D1", &ct); htest.assertEqual("DFE23F1642508290D68245279558B2FB", &tag); var pt2: [pt.len]u8 = undefined; try Aead.decrypt(&pt2, &ct, tag, &ad, nonce, key); testing.expectEqualSlices(u8, &pt, &pt2); } { // test vector (1057) from NIST KAT submission. const ad: [0]u8 = undefined; var pt: [64 / 2]u8 = undefined; try std.fmt.hexToBytes(&pt, "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F"); var ct: [pt.len]u8 = undefined; var tag: [16]u8 = undefined; Aead.encrypt(&ct, &tag, &pt, &ad, nonce, key); htest.assertEqual("7F8A2CF4F52AA4D6B2E74105C30A2777B9D0C8AEFDD555DE35861BD3011F652F", &ct); htest.assertEqual("7256456FA935AC34BBF55AE135F33257", &tag); var pt2: [pt.len]u8 = undefined; try Aead.decrypt(&pt2, &ct, tag, &ad, nonce, key); testing.expectEqualSlices(u8, &pt, &pt2); } }
lib/std/crypto/gimli.zig
const std = @import("std.zig"); const debug = std.debug; const assert = debug.assert; const testing = std.testing; const math = std.math; const mem = std.mem; const meta = std.meta; const trait = meta.trait; const autoHash = std.hash.autoHash; const Wyhash = std.hash.Wyhash; const Allocator = mem.Allocator; const hash_map = @This(); /// An ArrayHashMap with default hash and equal functions. /// See AutoContext for a description of the hash and equal implementations. pub fn AutoArrayHashMap(comptime K: type, comptime V: type) type { return ArrayHashMap(K, V, AutoContext(K), !autoEqlIsCheap(K)); } /// An ArrayHashMapUnmanaged with default hash and equal functions. /// See AutoContext for a description of the hash and equal implementations. pub fn AutoArrayHashMapUnmanaged(comptime K: type, comptime V: type) type { return ArrayHashMapUnmanaged(K, V, AutoContext(K), !autoEqlIsCheap(K)); } /// Builtin hashmap for strings as keys. pub fn StringArrayHashMap(comptime V: type) type { return ArrayHashMap([]const u8, V, StringContext, true); } pub fn StringArrayHashMapUnmanaged(comptime V: type) type { return ArrayHashMapUnmanaged([]const u8, V, StringContext, true); } pub const StringContext = struct { pub fn hash(self: @This(), s: []const u8) u32 { _ = self; return hashString(s); } pub fn eql(self: @This(), a: []const u8, b: []const u8, b_index: usize) bool { _ = self; _ = b_index; return eqlString(a, b); } }; pub fn eqlString(a: []const u8, b: []const u8) bool { return mem.eql(u8, a, b); } pub fn hashString(s: []const u8) u32 { return @truncate(u32, std.hash.Wyhash.hash(0, s)); } /// Insertion order is preserved. /// Deletions perform a "swap removal" on the entries list. /// Modifying the hash map while iterating is allowed, however one must understand /// the (well defined) behavior when mixing insertions and deletions with iteration. /// For a hash map that can be initialized directly that does not store an Allocator /// field, see `ArrayHashMapUnmanaged`. /// When `store_hash` is `false`, this data structure is biased towards cheap `eql` /// functions. It does not store each item's hash in the table. Setting `store_hash` /// to `true` incurs slightly more memory cost by storing each key's hash in the table /// but only has to call `eql` for hash collisions. /// If typical operations (except iteration over entries) need to be faster, prefer /// the alternative `std.HashMap`. /// Context must be a struct type with two member functions: /// hash(self, K) u32 /// eql(self, K, K) bool /// Adapted variants of many functions are provided. These variants /// take a pseudo key instead of a key. Their context must have the functions: /// hash(self, PseudoKey) u32 /// eql(self, PseudoKey, K) bool pub fn ArrayHashMap( comptime K: type, comptime V: type, comptime Context: type, comptime store_hash: bool, ) type { return struct { unmanaged: Unmanaged, allocator: Allocator, ctx: Context, comptime { std.hash_map.verifyContext(Context, K, K, u32, true); } /// The ArrayHashMapUnmanaged type using the same settings as this managed map. pub const Unmanaged = ArrayHashMapUnmanaged(K, V, Context, store_hash); /// Pointers to a key and value in the backing store of this map. /// Modifying the key is allowed only if it does not change the hash. /// Modifying the value is allowed. /// Entry pointers become invalid whenever this ArrayHashMap is modified, /// unless `ensureTotalCapacity`/`ensureUnusedCapacity` was previously used. pub const Entry = Unmanaged.Entry; /// A KV pair which has been copied out of the backing store pub const KV = Unmanaged.KV; /// The Data type used for the MultiArrayList backing this map pub const Data = Unmanaged.Data; /// The MultiArrayList type backing this map pub const DataList = Unmanaged.DataList; /// The stored hash type, either u32 or void. pub const Hash = Unmanaged.Hash; /// getOrPut variants return this structure, with pointers /// to the backing store and a flag to indicate whether an /// existing entry was found. /// Modifying the key is allowed only if it does not change the hash. /// Modifying the value is allowed. /// Entry pointers become invalid whenever this ArrayHashMap is modified, /// unless `ensureTotalCapacity`/`ensureUnusedCapacity` was previously used. pub const GetOrPutResult = Unmanaged.GetOrPutResult; /// An Iterator over Entry pointers. pub const Iterator = Unmanaged.Iterator; const Self = @This(); /// Create an ArrayHashMap instance which will use a specified allocator. pub fn init(allocator: Allocator) Self { if (@sizeOf(Context) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call initContext instead."); return initContext(allocator, undefined); } pub fn initContext(allocator: Allocator, ctx: Context) Self { return .{ .unmanaged = .{}, .allocator = allocator, .ctx = ctx, }; } /// Frees the backing allocation and leaves the map in an undefined state. /// Note that this does not free keys or values. You must take care of that /// before calling this function, if it is needed. pub fn deinit(self: *Self) void { self.unmanaged.deinit(self.allocator); self.* = undefined; } /// Clears the map but retains the backing allocation for future use. pub fn clearRetainingCapacity(self: *Self) void { return self.unmanaged.clearRetainingCapacity(); } /// Clears the map and releases the backing allocation pub fn clearAndFree(self: *Self) void { return self.unmanaged.clearAndFree(self.allocator); } /// Returns the number of KV pairs stored in this map. pub fn count(self: Self) usize { return self.unmanaged.count(); } /// Returns the backing array of keys in this map. /// Modifying the map may invalidate this array. pub fn keys(self: Self) []K { return self.unmanaged.keys(); } /// Returns the backing array of values in this map. /// Modifying the map may invalidate this array. pub fn values(self: Self) []V { return self.unmanaged.values(); } /// Returns an iterator over the pairs in this map. /// Modifying the map may invalidate this iterator. pub fn iterator(self: *const Self) Iterator { return self.unmanaged.iterator(); } /// If key exists this function cannot fail. /// If there is an existing item with `key`, then the result /// `Entry` pointer points to it, and found_existing is true. /// Otherwise, puts a new item with undefined value, and /// the `Entry` pointer points to it. Caller should then initialize /// the value (but not the key). pub fn getOrPut(self: *Self, key: K) !GetOrPutResult { return self.unmanaged.getOrPutContext(self.allocator, key, self.ctx); } pub fn getOrPutAdapted(self: *Self, key: anytype, ctx: anytype) !GetOrPutResult { return self.unmanaged.getOrPutContextAdapted(key, ctx, self.ctx); } /// If there is an existing item with `key`, then the result /// `Entry` pointer points to it, and found_existing is true. /// Otherwise, puts a new item with undefined value, and /// the `Entry` pointer points to it. Caller should then initialize /// the value (but not the key). /// If a new entry needs to be stored, this function asserts there /// is enough capacity to store it. pub fn getOrPutAssumeCapacity(self: *Self, key: K) GetOrPutResult { return self.unmanaged.getOrPutAssumeCapacityContext(key, self.ctx); } pub fn getOrPutAssumeCapacityAdapted(self: *Self, key: anytype, ctx: anytype) GetOrPutResult { return self.unmanaged.getOrPutAssumeCapacityAdapted(key, ctx); } pub fn getOrPutValue(self: *Self, key: K, value: V) !GetOrPutResult { return self.unmanaged.getOrPutValueContext(self.allocator, key, value, self.ctx); } pub const ensureCapacity = @compileError("deprecated; call `ensureUnusedCapacity` or `ensureTotalCapacity`"); /// Increases capacity, guaranteeing that insertions up until the /// `expected_count` will not cause an allocation, and therefore cannot fail. pub fn ensureTotalCapacity(self: *Self, new_capacity: usize) !void { return self.unmanaged.ensureTotalCapacityContext(self.allocator, new_capacity, self.ctx); } /// Increases capacity, guaranteeing that insertions up until /// `additional_count` **more** items will not cause an allocation, and /// therefore cannot fail. pub fn ensureUnusedCapacity(self: *Self, additional_count: usize) !void { return self.unmanaged.ensureUnusedCapacityContext(self.allocator, additional_count, self.ctx); } /// Returns the number of total elements which may be present before it is /// no longer guaranteed that no allocations will be performed. pub fn capacity(self: *Self) usize { return self.unmanaged.capacity(); } /// Clobbers any existing data. To detect if a put would clobber /// existing data, see `getOrPut`. pub fn put(self: *Self, key: K, value: V) !void { return self.unmanaged.putContext(self.allocator, key, value, self.ctx); } /// Inserts a key-value pair into the hash map, asserting that no previous /// entry with the same key is already present pub fn putNoClobber(self: *Self, key: K, value: V) !void { return self.unmanaged.putNoClobberContext(self.allocator, key, value, self.ctx); } /// Asserts there is enough capacity to store the new key-value pair. /// Clobbers any existing data. To detect if a put would clobber /// existing data, see `getOrPutAssumeCapacity`. pub fn putAssumeCapacity(self: *Self, key: K, value: V) void { return self.unmanaged.putAssumeCapacityContext(key, value, self.ctx); } /// Asserts there is enough capacity to store the new key-value pair. /// Asserts that it does not clobber any existing data. /// To detect if a put would clobber existing data, see `getOrPutAssumeCapacity`. pub fn putAssumeCapacityNoClobber(self: *Self, key: K, value: V) void { return self.unmanaged.putAssumeCapacityNoClobberContext(key, value, self.ctx); } /// Inserts a new `Entry` into the hash map, returning the previous one, if any. pub fn fetchPut(self: *Self, key: K, value: V) !?KV { return self.unmanaged.fetchPutContext(self.allocator, key, value, self.ctx); } /// Inserts a new `Entry` into the hash map, returning the previous one, if any. /// If insertion happuns, asserts there is enough capacity without allocating. pub fn fetchPutAssumeCapacity(self: *Self, key: K, value: V) ?KV { return self.unmanaged.fetchPutAssumeCapacityContext(key, value, self.ctx); } /// Finds pointers to the key and value storage associated with a key. pub fn getEntry(self: Self, key: K) ?Entry { return self.unmanaged.getEntryContext(key, self.ctx); } pub fn getEntryAdapted(self: Self, key: anytype, ctx: anytype) ?Entry { return self.unmanaged.getEntryAdapted(key, ctx); } /// Finds the index in the `entries` array where a key is stored pub fn getIndex(self: Self, key: K) ?usize { return self.unmanaged.getIndexContext(key, self.ctx); } pub fn getIndexAdapted(self: Self, key: anytype, ctx: anytype) ?usize { return self.unmanaged.getIndexAdapted(key, ctx); } /// Find the value associated with a key pub fn get(self: Self, key: K) ?V { return self.unmanaged.getContext(key, self.ctx); } pub fn getAdapted(self: Self, key: anytype, ctx: anytype) ?V { return self.unmanaged.getAdapted(key, ctx); } /// Find a pointer to the value associated with a key pub fn getPtr(self: Self, key: K) ?*V { return self.unmanaged.getPtrContext(key, self.ctx); } pub fn getPtrAdapted(self: Self, key: anytype, ctx: anytype) ?*V { return self.unmanaged.getPtrAdapted(key, ctx); } /// Find the actual key associated with an adapted key pub fn getKey(self: Self, key: K) ?K { return self.unmanaged.getKeyContext(key, self.ctx); } pub fn getKeyAdapted(self: Self, key: anytype, ctx: anytype) ?K { return self.unmanaged.getKeyAdapted(key, ctx); } /// Find a pointer to the actual key associated with an adapted key pub fn getKeyPtr(self: Self, key: K) ?*K { return self.unmanaged.getKeyPtrContext(key, self.ctx); } pub fn getKeyPtrAdapted(self: Self, key: anytype, ctx: anytype) ?*K { return self.unmanaged.getKeyPtrAdapted(key, ctx); } /// Check whether a key is stored in the map pub fn contains(self: Self, key: K) bool { return self.unmanaged.containsContext(key, self.ctx); } pub fn containsAdapted(self: Self, key: anytype, ctx: anytype) bool { return self.unmanaged.containsAdapted(key, ctx); } /// If there is an `Entry` with a matching key, it is deleted from /// the hash map, and then returned from this function. The entry is /// removed from the underlying array by swapping it with the last /// element. pub fn fetchSwapRemove(self: *Self, key: K) ?KV { return self.unmanaged.fetchSwapRemoveContext(key, self.ctx); } pub fn fetchSwapRemoveAdapted(self: *Self, key: anytype, ctx: anytype) ?KV { return self.unmanaged.fetchSwapRemoveContextAdapted(key, ctx, self.ctx); } /// If there is an `Entry` with a matching key, it is deleted from /// the hash map, and then returned from this function. The entry is /// removed from the underlying array by shifting all elements forward /// thereby maintaining the current ordering. pub fn fetchOrderedRemove(self: *Self, key: K) ?KV { return self.unmanaged.fetchOrderedRemoveContext(key, self.ctx); } pub fn fetchOrderedRemoveAdapted(self: *Self, key: anytype, ctx: anytype) ?KV { return self.unmanaged.fetchOrderedRemoveContextAdapted(key, ctx, self.ctx); } /// If there is an `Entry` with a matching key, it is deleted from /// the hash map. The entry is removed from the underlying array /// by swapping it with the last element. Returns true if an entry /// was removed, false otherwise. pub fn swapRemove(self: *Self, key: K) bool { return self.unmanaged.swapRemoveContext(key, self.ctx); } pub fn swapRemoveAdapted(self: *Self, key: anytype, ctx: anytype) bool { return self.unmanaged.swapRemoveContextAdapted(key, ctx, self.ctx); } /// If there is an `Entry` with a matching key, it is deleted from /// the hash map. The entry is removed from the underlying array /// by shifting all elements forward, thereby maintaining the /// current ordering. Returns true if an entry was removed, false otherwise. pub fn orderedRemove(self: *Self, key: K) bool { return self.unmanaged.orderedRemoveContext(key, self.ctx); } pub fn orderedRemoveAdapted(self: *Self, key: anytype, ctx: anytype) bool { return self.unmanaged.orderedRemoveContextAdapted(key, ctx, self.ctx); } /// Deletes the item at the specified index in `entries` from /// the hash map. The entry is removed from the underlying array /// by swapping it with the last element. pub fn swapRemoveAt(self: *Self, index: usize) void { self.unmanaged.swapRemoveAtContext(index, self.ctx); } /// Deletes the item at the specified index in `entries` from /// the hash map. The entry is removed from the underlying array /// by shifting all elements forward, thereby maintaining the /// current ordering. pub fn orderedRemoveAt(self: *Self, index: usize) void { self.unmanaged.orderedRemoveAtContext(index, self.ctx); } /// Create a copy of the hash map which can be modified separately. /// The copy uses the same context and allocator as this instance. pub fn clone(self: Self) !Self { var other = try self.unmanaged.cloneContext(self.allocator, self.ctx); return other.promoteContext(self.allocator, self.ctx); } /// Create a copy of the hash map which can be modified separately. /// The copy uses the same context as this instance, but the specified /// allocator. pub fn cloneWithAllocator(self: Self, allocator: Allocator) !Self { var other = try self.unmanaged.cloneContext(allocator, self.ctx); return other.promoteContext(allocator, self.ctx); } /// Create a copy of the hash map which can be modified separately. /// The copy uses the same allocator as this instance, but the /// specified context. pub fn cloneWithContext(self: Self, ctx: anytype) !ArrayHashMap(K, V, @TypeOf(ctx), store_hash) { var other = try self.unmanaged.cloneContext(self.allocator, ctx); return other.promoteContext(self.allocator, ctx); } /// Create a copy of the hash map which can be modified separately. /// The copy uses the specified allocator and context. pub fn cloneWithAllocatorAndContext(self: Self, allocator: Allocator, ctx: anytype) !ArrayHashMap(K, V, @TypeOf(ctx), store_hash) { var other = try self.unmanaged.cloneContext(allocator, ctx); return other.promoteContext(allocator, ctx); } /// Rebuilds the key indexes. If the underlying entries has been modified directly, users /// can call `reIndex` to update the indexes to account for these new entries. pub fn reIndex(self: *Self) !void { return self.unmanaged.reIndexContext(self.allocator, self.ctx); } /// Sorts the entries and then rebuilds the index. /// `sort_ctx` must have this method: /// `fn lessThan(ctx: @TypeOf(ctx), a_index: usize, b_index: usize) bool` pub fn sort(self: *Self, sort_ctx: anytype) void { return self.unmanaged.sortContext(sort_ctx, self.ctx); } /// Shrinks the underlying `Entry` array to `new_len` elements and discards any associated /// index entries. Keeps capacity the same. pub fn shrinkRetainingCapacity(self: *Self, new_len: usize) void { return self.unmanaged.shrinkRetainingCapacityContext(new_len, self.ctx); } /// Shrinks the underlying `Entry` array to `new_len` elements and discards any associated /// index entries. Reduces allocated capacity. pub fn shrinkAndFree(self: *Self, new_len: usize) void { return self.unmanaged.shrinkAndFreeContext(self.allocator, new_len, self.ctx); } /// Removes the last inserted `Entry` in the hash map and returns it. pub fn pop(self: *Self) KV { return self.unmanaged.popContext(self.ctx); } /// Removes the last inserted `Entry` in the hash map and returns it if count is nonzero. /// Otherwise returns null. pub fn popOrNull(self: *Self) ?KV { return self.unmanaged.popOrNullContext(self.ctx); } }; } /// General purpose hash table. /// Insertion order is preserved. /// Deletions perform a "swap removal" on the entries list. /// Modifying the hash map while iterating is allowed, however one must understand /// the (well defined) behavior when mixing insertions and deletions with iteration. /// This type does not store an Allocator field - the Allocator must be passed in /// with each function call that requires it. See `ArrayHashMap` for a type that stores /// an Allocator field for convenience. /// Can be initialized directly using the default field values. /// This type is designed to have low overhead for small numbers of entries. When /// `store_hash` is `false` and the number of entries in the map is less than 9, /// the overhead cost of using `ArrayHashMapUnmanaged` rather than `std.ArrayList` is /// only a single pointer-sized integer. /// When `store_hash` is `false`, this data structure is biased towards cheap `eql` /// functions. It does not store each item's hash in the table. Setting `store_hash` /// to `true` incurs slightly more memory cost by storing each key's hash in the table /// but guarantees only one call to `eql` per insertion/deletion. /// Context must be a struct type with two member functions: /// hash(self, K) u32 /// eql(self, K, K) bool /// Adapted variants of many functions are provided. These variants /// take a pseudo key instead of a key. Their context must have the functions: /// hash(self, PseudoKey) u32 /// eql(self, PseudoKey, K) bool pub fn ArrayHashMapUnmanaged( comptime K: type, comptime V: type, comptime Context: type, comptime store_hash: bool, ) type { return struct { /// It is permitted to access this field directly. entries: DataList = .{}, /// When entries length is less than `linear_scan_max`, this remains `null`. /// Once entries length grows big enough, this field is allocated. There is /// an IndexHeader followed by an array of Index(I) structs, where I is defined /// by how many total indexes there are. index_header: ?*IndexHeader = null, comptime { std.hash_map.verifyContext(Context, K, K, u32, true); } /// Modifying the key is allowed only if it does not change the hash. /// Modifying the value is allowed. /// Entry pointers become invalid whenever this ArrayHashMap is modified, /// unless `ensureTotalCapacity`/`ensureUnusedCapacity` was previously used. pub const Entry = struct { key_ptr: *K, value_ptr: *V, }; /// A KV pair which has been copied out of the backing store pub const KV = struct { key: K, value: V, }; /// The Data type used for the MultiArrayList backing this map pub const Data = struct { hash: Hash, key: K, value: V, }; /// The MultiArrayList type backing this map pub const DataList = std.MultiArrayList(Data); /// The stored hash type, either u32 or void. pub const Hash = if (store_hash) u32 else void; /// getOrPut variants return this structure, with pointers /// to the backing store and a flag to indicate whether an /// existing entry was found. /// Modifying the key is allowed only if it does not change the hash. /// Modifying the value is allowed. /// Entry pointers become invalid whenever this ArrayHashMap is modified, /// unless `ensureTotalCapacity`/`ensureUnusedCapacity` was previously used. pub const GetOrPutResult = struct { key_ptr: *K, value_ptr: *V, found_existing: bool, index: usize, }; /// The ArrayHashMap type using the same settings as this managed map. pub const Managed = ArrayHashMap(K, V, Context, store_hash); /// Some functions require a context only if hashes are not stored. /// To keep the api simple, this type is only used internally. const ByIndexContext = if (store_hash) void else Context; const Self = @This(); const linear_scan_max = 8; const RemovalType = enum { swap, ordered, }; /// Convert from an unmanaged map to a managed map. After calling this, /// the promoted map should no longer be used. pub fn promote(self: Self, allocator: Allocator) Managed { if (@sizeOf(Context) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call promoteContext instead."); return self.promoteContext(allocator, undefined); } pub fn promoteContext(self: Self, allocator: Allocator, ctx: Context) Managed { return .{ .unmanaged = self, .allocator = allocator, .ctx = ctx, }; } /// Frees the backing allocation and leaves the map in an undefined state. /// Note that this does not free keys or values. You must take care of that /// before calling this function, if it is needed. pub fn deinit(self: *Self, allocator: Allocator) void { self.entries.deinit(allocator); if (self.index_header) |header| { header.free(allocator); } self.* = undefined; } /// Clears the map but retains the backing allocation for future use. pub fn clearRetainingCapacity(self: *Self) void { self.entries.len = 0; if (self.index_header) |header| { switch (header.capacityIndexType()) { .u8 => mem.set(Index(u8), header.indexes(u8), Index(u8).empty), .u16 => mem.set(Index(u16), header.indexes(u16), Index(u16).empty), .u32 => mem.set(Index(u32), header.indexes(u32), Index(u32).empty), } } } /// Clears the map and releases the backing allocation pub fn clearAndFree(self: *Self, allocator: Allocator) void { self.entries.shrinkAndFree(allocator, 0); if (self.index_header) |header| { header.free(allocator); self.index_header = null; } } /// Returns the number of KV pairs stored in this map. pub fn count(self: Self) usize { return self.entries.len; } /// Returns the backing array of keys in this map. /// Modifying the map may invalidate this array. pub fn keys(self: Self) []K { return self.entries.items(.key); } /// Returns the backing array of values in this map. /// Modifying the map may invalidate this array. pub fn values(self: Self) []V { return self.entries.items(.value); } /// Returns an iterator over the pairs in this map. /// Modifying the map may invalidate this iterator. pub fn iterator(self: Self) Iterator { const slice = self.entries.slice(); return .{ .keys = slice.items(.key).ptr, .values = slice.items(.value).ptr, .len = @intCast(u32, slice.len), }; } pub const Iterator = struct { keys: [*]K, values: [*]V, len: u32, index: u32 = 0, pub fn next(it: *Iterator) ?Entry { if (it.index >= it.len) return null; const result = Entry{ .key_ptr = &it.keys[it.index], // workaround for #6974 .value_ptr = if (@sizeOf(*V) == 0) undefined else &it.values[it.index], }; it.index += 1; return result; } /// Reset the iterator to the initial index pub fn reset(it: *Iterator) void { it.index = 0; } }; /// If key exists this function cannot fail. /// If there is an existing item with `key`, then the result /// `Entry` pointer points to it, and found_existing is true. /// Otherwise, puts a new item with undefined value, and /// the `Entry` pointer points to it. Caller should then initialize /// the value (but not the key). pub fn getOrPut(self: *Self, allocator: Allocator, key: K) !GetOrPutResult { if (@sizeOf(Context) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call getOrPutContext instead."); return self.getOrPutContext(allocator, key, undefined); } pub fn getOrPutContext(self: *Self, allocator: Allocator, key: K, ctx: Context) !GetOrPutResult { const gop = try self.getOrPutContextAdapted(allocator, key, ctx, ctx); if (!gop.found_existing) { gop.key_ptr.* = key; } return gop; } pub fn getOrPutAdapted(self: *Self, allocator: Allocator, key: anytype, key_ctx: anytype) !GetOrPutResult { if (@sizeOf(Context) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call getOrPutContextAdapted instead."); return self.getOrPutContextAdapted(allocator, key, key_ctx, undefined); } pub fn getOrPutContextAdapted(self: *Self, allocator: Allocator, key: anytype, key_ctx: anytype, ctx: Context) !GetOrPutResult { self.ensureTotalCapacityContext(allocator, self.entries.len + 1, ctx) catch |err| { // "If key exists this function cannot fail." const index = self.getIndexAdapted(key, key_ctx) orelse return err; const slice = self.entries.slice(); return GetOrPutResult{ .key_ptr = &slice.items(.key)[index], // workaround for #6974 .value_ptr = if (@sizeOf(*V) == 0) undefined else &slice.items(.value)[index], .found_existing = true, .index = index, }; }; return self.getOrPutAssumeCapacityAdapted(key, key_ctx); } /// If there is an existing item with `key`, then the result /// `Entry` pointer points to it, and found_existing is true. /// Otherwise, puts a new item with undefined value, and /// the `Entry` pointer points to it. Caller should then initialize /// the value (but not the key). /// If a new entry needs to be stored, this function asserts there /// is enough capacity to store it. pub fn getOrPutAssumeCapacity(self: *Self, key: K) GetOrPutResult { if (@sizeOf(Context) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call getOrPutAssumeCapacityContext instead."); return self.getOrPutAssumeCapacityContext(key, undefined); } pub fn getOrPutAssumeCapacityContext(self: *Self, key: K, ctx: Context) GetOrPutResult { const gop = self.getOrPutAssumeCapacityAdapted(key, ctx); if (!gop.found_existing) { gop.key_ptr.* = key; } return gop; } /// If there is an existing item with `key`, then the result /// `Entry` pointers point to it, and found_existing is true. /// Otherwise, puts a new item with undefined key and value, and /// the `Entry` pointers point to it. Caller must then initialize /// both the key and the value. /// If a new entry needs to be stored, this function asserts there /// is enough capacity to store it. pub fn getOrPutAssumeCapacityAdapted(self: *Self, key: anytype, ctx: anytype) GetOrPutResult { const header = self.index_header orelse { // Linear scan. const h = if (store_hash) checkedHash(ctx, key) else {}; const slice = self.entries.slice(); const hashes_array = slice.items(.hash); const keys_array = slice.items(.key); for (keys_array) |*item_key, i| { if (hashes_array[i] == h and checkedEql(ctx, key, item_key.*, i)) { return GetOrPutResult{ .key_ptr = item_key, // workaround for #6974 .value_ptr = if (@sizeOf(*V) == 0) undefined else &slice.items(.value)[i], .found_existing = true, .index = i, }; } } const index = self.entries.addOneAssumeCapacity(); // unsafe indexing because the length changed if (store_hash) hashes_array.ptr[index] = h; return GetOrPutResult{ .key_ptr = &keys_array.ptr[index], // workaround for #6974 .value_ptr = if (@sizeOf(*V) == 0) undefined else &slice.items(.value).ptr[index], .found_existing = false, .index = index, }; }; switch (header.capacityIndexType()) { .u8 => return self.getOrPutInternal(key, ctx, header, u8), .u16 => return self.getOrPutInternal(key, ctx, header, u16), .u32 => return self.getOrPutInternal(key, ctx, header, u32), } } pub fn getOrPutValue(self: *Self, allocator: Allocator, key: K, value: V) !GetOrPutResult { if (@sizeOf(Context) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call getOrPutValueContext instead."); return self.getOrPutValueContext(allocator, key, value, undefined); } pub fn getOrPutValueContext(self: *Self, allocator: Allocator, key: K, value: V, ctx: Context) !GetOrPutResult { const res = try self.getOrPutContextAdapted(allocator, key, ctx, ctx); if (!res.found_existing) { res.key_ptr.* = key; res.value_ptr.* = value; } return res; } pub const ensureCapacity = @compileError("deprecated; call `ensureUnusedCapacity` or `ensureTotalCapacity`"); /// Increases capacity, guaranteeing that insertions up until the /// `expected_count` will not cause an allocation, and therefore cannot fail. pub fn ensureTotalCapacity(self: *Self, allocator: Allocator, new_capacity: usize) !void { if (@sizeOf(ByIndexContext) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call ensureTotalCapacityContext instead."); return self.ensureTotalCapacityContext(allocator, new_capacity, undefined); } pub fn ensureTotalCapacityContext(self: *Self, allocator: Allocator, new_capacity: usize, ctx: Context) !void { if (new_capacity <= linear_scan_max) { try self.entries.ensureTotalCapacity(allocator, new_capacity); return; } if (self.index_header) |header| { if (new_capacity <= header.capacity()) { try self.entries.ensureTotalCapacity(allocator, new_capacity); return; } } const new_bit_index = try IndexHeader.findBitIndex(new_capacity); const new_header = try IndexHeader.alloc(allocator, new_bit_index); try self.entries.ensureTotalCapacity(allocator, new_capacity); if (self.index_header) |old_header| old_header.free(allocator); self.insertAllEntriesIntoNewHeader(if (store_hash) {} else ctx, new_header); self.index_header = new_header; } /// Increases capacity, guaranteeing that insertions up until /// `additional_count` **more** items will not cause an allocation, and /// therefore cannot fail. pub fn ensureUnusedCapacity( self: *Self, allocator: Allocator, additional_capacity: usize, ) !void { if (@sizeOf(ByIndexContext) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call ensureTotalCapacityContext instead."); return self.ensureUnusedCapacityContext(allocator, additional_capacity, undefined); } pub fn ensureUnusedCapacityContext( self: *Self, allocator: Allocator, additional_capacity: usize, ctx: Context, ) !void { return self.ensureTotalCapacityContext(allocator, self.count() + additional_capacity, ctx); } /// Returns the number of total elements which may be present before it is /// no longer guaranteed that no allocations will be performed. pub fn capacity(self: Self) usize { const entry_cap = self.entries.capacity; const header = self.index_header orelse return math.min(linear_scan_max, entry_cap); const indexes_cap = header.capacity(); return math.min(entry_cap, indexes_cap); } /// Clobbers any existing data. To detect if a put would clobber /// existing data, see `getOrPut`. pub fn put(self: *Self, allocator: Allocator, key: K, value: V) !void { if (@sizeOf(Context) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call putContext instead."); return self.putContext(allocator, key, value, undefined); } pub fn putContext(self: *Self, allocator: Allocator, key: K, value: V, ctx: Context) !void { const result = try self.getOrPutContext(allocator, key, ctx); result.value_ptr.* = value; } /// Inserts a key-value pair into the hash map, asserting that no previous /// entry with the same key is already present pub fn putNoClobber(self: *Self, allocator: Allocator, key: K, value: V) !void { if (@sizeOf(Context) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call putNoClobberContext instead."); return self.putNoClobberContext(allocator, key, value, undefined); } pub fn putNoClobberContext(self: *Self, allocator: Allocator, key: K, value: V, ctx: Context) !void { const result = try self.getOrPutContext(allocator, key, ctx); assert(!result.found_existing); result.value_ptr.* = value; } /// Asserts there is enough capacity to store the new key-value pair. /// Clobbers any existing data. To detect if a put would clobber /// existing data, see `getOrPutAssumeCapacity`. pub fn putAssumeCapacity(self: *Self, key: K, value: V) void { if (@sizeOf(Context) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call putAssumeCapacityContext instead."); return self.putAssumeCapacityContext(key, value, undefined); } pub fn putAssumeCapacityContext(self: *Self, key: K, value: V, ctx: Context) void { const result = self.getOrPutAssumeCapacityContext(key, ctx); result.value_ptr.* = value; } /// Asserts there is enough capacity to store the new key-value pair. /// Asserts that it does not clobber any existing data. /// To detect if a put would clobber existing data, see `getOrPutAssumeCapacity`. pub fn putAssumeCapacityNoClobber(self: *Self, key: K, value: V) void { if (@sizeOf(Context) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call putAssumeCapacityNoClobberContext instead."); return self.putAssumeCapacityNoClobberContext(key, value, undefined); } pub fn putAssumeCapacityNoClobberContext(self: *Self, key: K, value: V, ctx: Context) void { const result = self.getOrPutAssumeCapacityContext(key, ctx); assert(!result.found_existing); result.value_ptr.* = value; } /// Inserts a new `Entry` into the hash map, returning the previous one, if any. pub fn fetchPut(self: *Self, allocator: Allocator, key: K, value: V) !?KV { if (@sizeOf(Context) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call fetchPutContext instead."); return self.fetchPutContext(allocator, key, value, undefined); } pub fn fetchPutContext(self: *Self, allocator: Allocator, key: K, value: V, ctx: Context) !?KV { const gop = try self.getOrPutContext(allocator, key, ctx); var result: ?KV = null; if (gop.found_existing) { result = KV{ .key = gop.key_ptr.*, .value = gop.value_ptr.*, }; } gop.value_ptr.* = value; return result; } /// Inserts a new `Entry` into the hash map, returning the previous one, if any. /// If insertion happens, asserts there is enough capacity without allocating. pub fn fetchPutAssumeCapacity(self: *Self, key: K, value: V) ?KV { if (@sizeOf(Context) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call fetchPutAssumeCapacityContext instead."); return self.fetchPutAssumeCapacityContext(key, value, undefined); } pub fn fetchPutAssumeCapacityContext(self: *Self, key: K, value: V, ctx: Context) ?KV { const gop = self.getOrPutAssumeCapacityContext(key, ctx); var result: ?KV = null; if (gop.found_existing) { result = KV{ .key = gop.key_ptr.*, .value = gop.value_ptr.*, }; } gop.value_ptr.* = value; return result; } /// Finds pointers to the key and value storage associated with a key. pub fn getEntry(self: Self, key: K) ?Entry { if (@sizeOf(Context) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call getEntryContext instead."); return self.getEntryContext(key, undefined); } pub fn getEntryContext(self: Self, key: K, ctx: Context) ?Entry { return self.getEntryAdapted(key, ctx); } pub fn getEntryAdapted(self: Self, key: anytype, ctx: anytype) ?Entry { const index = self.getIndexAdapted(key, ctx) orelse return null; const slice = self.entries.slice(); return Entry{ .key_ptr = &slice.items(.key)[index], // workaround for #6974 .value_ptr = if (@sizeOf(*V) == 0) undefined else &slice.items(.value)[index], }; } /// Finds the index in the `entries` array where a key is stored pub fn getIndex(self: Self, key: K) ?usize { if (@sizeOf(Context) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call getIndexContext instead."); return self.getIndexContext(key, undefined); } pub fn getIndexContext(self: Self, key: K, ctx: Context) ?usize { return self.getIndexAdapted(key, ctx); } pub fn getIndexAdapted(self: Self, key: anytype, ctx: anytype) ?usize { const header = self.index_header orelse { // Linear scan. const h = if (store_hash) checkedHash(ctx, key) else {}; const slice = self.entries.slice(); const hashes_array = slice.items(.hash); const keys_array = slice.items(.key); for (keys_array) |*item_key, i| { if (hashes_array[i] == h and checkedEql(ctx, key, item_key.*, i)) { return i; } } return null; }; switch (header.capacityIndexType()) { .u8 => return self.getIndexWithHeaderGeneric(key, ctx, header, u8), .u16 => return self.getIndexWithHeaderGeneric(key, ctx, header, u16), .u32 => return self.getIndexWithHeaderGeneric(key, ctx, header, u32), } } fn getIndexWithHeaderGeneric(self: Self, key: anytype, ctx: anytype, header: *IndexHeader, comptime I: type) ?usize { const indexes = header.indexes(I); const slot = self.getSlotByKey(key, ctx, header, I, indexes) orelse return null; return indexes[slot].entry_index; } /// Find the value associated with a key pub fn get(self: Self, key: K) ?V { if (@sizeOf(Context) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call getContext instead."); return self.getContext(key, undefined); } pub fn getContext(self: Self, key: K, ctx: Context) ?V { return self.getAdapted(key, ctx); } pub fn getAdapted(self: Self, key: anytype, ctx: anytype) ?V { const index = self.getIndexAdapted(key, ctx) orelse return null; return self.values()[index]; } /// Find a pointer to the value associated with a key pub fn getPtr(self: Self, key: K) ?*V { if (@sizeOf(Context) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call getPtrContext instead."); return self.getPtrContext(key, undefined); } pub fn getPtrContext(self: Self, key: K, ctx: Context) ?*V { return self.getPtrAdapted(key, ctx); } pub fn getPtrAdapted(self: Self, key: anytype, ctx: anytype) ?*V { const index = self.getIndexAdapted(key, ctx) orelse return null; // workaround for #6974 return if (@sizeOf(*V) == 0) @as(*V, undefined) else &self.values()[index]; } /// Find the actual key associated with an adapted key pub fn getKey(self: Self, key: K) ?K { if (@sizeOf(Context) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call getKeyContext instead."); return self.getKeyContext(key, undefined); } pub fn getKeyContext(self: Self, key: K, ctx: Context) ?K { return self.getKeyAdapted(key, ctx); } pub fn getKeyAdapted(self: Self, key: anytype, ctx: anytype) ?K { const index = self.getIndexAdapted(key, ctx) orelse return null; return self.keys()[index]; } /// Find a pointer to the actual key associated with an adapted key pub fn getKeyPtr(self: Self, key: K) ?*K { if (@sizeOf(Context) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call getKeyPtrContext instead."); return self.getKeyPtrContext(key, undefined); } pub fn getKeyPtrContext(self: Self, key: K, ctx: Context) ?*K { return self.getKeyPtrAdapted(key, ctx); } pub fn getKeyPtrAdapted(self: Self, key: anytype, ctx: anytype) ?*K { const index = self.getIndexAdapted(key, ctx) orelse return null; return &self.keys()[index]; } /// Check whether a key is stored in the map pub fn contains(self: Self, key: K) bool { if (@sizeOf(Context) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call containsContext instead."); return self.containsContext(key, undefined); } pub fn containsContext(self: Self, key: K, ctx: Context) bool { return self.containsAdapted(key, ctx); } pub fn containsAdapted(self: Self, key: anytype, ctx: anytype) bool { return self.getIndexAdapted(key, ctx) != null; } /// If there is an `Entry` with a matching key, it is deleted from /// the hash map, and then returned from this function. The entry is /// removed from the underlying array by swapping it with the last /// element. pub fn fetchSwapRemove(self: *Self, key: K) ?KV { if (@sizeOf(Context) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call fetchSwapRemoveContext instead."); return self.fetchSwapRemoveContext(key, undefined); } pub fn fetchSwapRemoveContext(self: *Self, key: K, ctx: Context) ?KV { return self.fetchSwapRemoveContextAdapted(key, ctx, ctx); } pub fn fetchSwapRemoveAdapted(self: *Self, key: anytype, ctx: anytype) ?KV { if (@sizeOf(ByIndexContext) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call fetchSwapRemoveContextAdapted instead."); return self.fetchSwapRemoveContextAdapted(key, ctx, undefined); } pub fn fetchSwapRemoveContextAdapted(self: *Self, key: anytype, key_ctx: anytype, ctx: Context) ?KV { return self.fetchRemoveByKey(key, key_ctx, if (store_hash) {} else ctx, .swap); } /// If there is an `Entry` with a matching key, it is deleted from /// the hash map, and then returned from this function. The entry is /// removed from the underlying array by shifting all elements forward /// thereby maintaining the current ordering. pub fn fetchOrderedRemove(self: *Self, key: K) ?KV { if (@sizeOf(Context) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call fetchOrderedRemoveContext instead."); return self.fetchOrderedRemoveContext(key, undefined); } pub fn fetchOrderedRemoveContext(self: *Self, key: K, ctx: Context) ?KV { return self.fetchOrderedRemoveContextAdapted(key, ctx, ctx); } pub fn fetchOrderedRemoveAdapted(self: *Self, key: anytype, ctx: anytype) ?KV { if (@sizeOf(ByIndexContext) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call fetchOrderedRemoveContextAdapted instead."); return self.fetchOrderedRemoveContextAdapted(key, ctx, undefined); } pub fn fetchOrderedRemoveContextAdapted(self: *Self, key: anytype, key_ctx: anytype, ctx: Context) ?KV { return self.fetchRemoveByKey(key, key_ctx, if (store_hash) {} else ctx, .ordered); } /// If there is an `Entry` with a matching key, it is deleted from /// the hash map. The entry is removed from the underlying array /// by swapping it with the last element. Returns true if an entry /// was removed, false otherwise. pub fn swapRemove(self: *Self, key: K) bool { if (@sizeOf(Context) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call swapRemoveContext instead."); return self.swapRemoveContext(key, undefined); } pub fn swapRemoveContext(self: *Self, key: K, ctx: Context) bool { return self.swapRemoveContextAdapted(key, ctx, ctx); } pub fn swapRemoveAdapted(self: *Self, key: anytype, ctx: anytype) bool { if (@sizeOf(ByIndexContext) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call swapRemoveContextAdapted instead."); return self.swapRemoveContextAdapted(key, ctx, undefined); } pub fn swapRemoveContextAdapted(self: *Self, key: anytype, key_ctx: anytype, ctx: Context) bool { return self.removeByKey(key, key_ctx, if (store_hash) {} else ctx, .swap); } /// If there is an `Entry` with a matching key, it is deleted from /// the hash map. The entry is removed from the underlying array /// by shifting all elements forward, thereby maintaining the /// current ordering. Returns true if an entry was removed, false otherwise. pub fn orderedRemove(self: *Self, key: K) bool { if (@sizeOf(Context) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call orderedRemoveContext instead."); return self.orderedRemoveContext(key, undefined); } pub fn orderedRemoveContext(self: *Self, key: K, ctx: Context) bool { return self.orderedRemoveContextAdapted(key, ctx, ctx); } pub fn orderedRemoveAdapted(self: *Self, key: anytype, ctx: anytype) bool { if (@sizeOf(ByIndexContext) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call orderedRemoveContextAdapted instead."); return self.orderedRemoveContextAdapted(key, ctx, undefined); } pub fn orderedRemoveContextAdapted(self: *Self, key: anytype, key_ctx: anytype, ctx: Context) bool { return self.removeByKey(key, key_ctx, if (store_hash) {} else ctx, .ordered); } /// Deletes the item at the specified index in `entries` from /// the hash map. The entry is removed from the underlying array /// by swapping it with the last element. pub fn swapRemoveAt(self: *Self, index: usize) void { if (@sizeOf(ByIndexContext) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call swapRemoveAtContext instead."); return self.swapRemoveAtContext(index, undefined); } pub fn swapRemoveAtContext(self: *Self, index: usize, ctx: Context) void { self.removeByIndex(index, if (store_hash) {} else ctx, .swap); } /// Deletes the item at the specified index in `entries` from /// the hash map. The entry is removed from the underlying array /// by shifting all elements forward, thereby maintaining the /// current ordering. pub fn orderedRemoveAt(self: *Self, index: usize) void { if (@sizeOf(ByIndexContext) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call orderedRemoveAtContext instead."); return self.orderedRemoveAtContext(index, undefined); } pub fn orderedRemoveAtContext(self: *Self, index: usize, ctx: Context) void { self.removeByIndex(index, if (store_hash) {} else ctx, .ordered); } /// Create a copy of the hash map which can be modified separately. /// The copy uses the same context and allocator as this instance. pub fn clone(self: Self, allocator: Allocator) !Self { if (@sizeOf(ByIndexContext) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call cloneContext instead."); return self.cloneContext(allocator, undefined); } pub fn cloneContext(self: Self, allocator: Allocator, ctx: Context) !Self { var other: Self = .{}; other.entries = try self.entries.clone(allocator); errdefer other.entries.deinit(allocator); if (self.index_header) |header| { const new_header = try IndexHeader.alloc(allocator, header.bit_index); other.insertAllEntriesIntoNewHeader(if (store_hash) {} else ctx, new_header); other.index_header = new_header; } return other; } /// Rebuilds the key indexes. If the underlying entries has been modified directly, users /// can call `reIndex` to update the indexes to account for these new entries. pub fn reIndex(self: *Self, allocator: Allocator) !void { if (@sizeOf(ByIndexContext) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call reIndexContext instead."); return self.reIndexContext(allocator, undefined); } pub fn reIndexContext(self: *Self, allocator: Allocator, ctx: Context) !void { if (self.entries.capacity <= linear_scan_max) return; // We're going to rebuild the index header and replace the existing one (if any). The // indexes should sized such that they will be at most 60% full. const bit_index = try IndexHeader.findBitIndex(self.entries.capacity); const new_header = try IndexHeader.alloc(allocator, bit_index); if (self.index_header) |header| header.free(allocator); self.insertAllEntriesIntoNewHeader(if (store_hash) {} else ctx, new_header); self.index_header = new_header; } /// Sorts the entries and then rebuilds the index. /// `sort_ctx` must have this method: /// `fn lessThan(ctx: @TypeOf(ctx), a_index: usize, b_index: usize) bool` pub inline fn sort(self: *Self, sort_ctx: anytype) void { if (@sizeOf(ByIndexContext) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call sortContext instead."); return self.sortContext(sort_ctx, undefined); } pub fn sortContext(self: *Self, sort_ctx: anytype, ctx: Context) void { self.entries.sort(sort_ctx); const header = self.index_header orelse return; header.reset(); self.insertAllEntriesIntoNewHeader(if (store_hash) {} else ctx, header); } /// Shrinks the underlying `Entry` array to `new_len` elements and discards any associated /// index entries. Keeps capacity the same. pub fn shrinkRetainingCapacity(self: *Self, new_len: usize) void { if (@sizeOf(ByIndexContext) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call shrinkRetainingCapacityContext instead."); return self.shrinkRetainingCapacityContext(new_len, undefined); } pub fn shrinkRetainingCapacityContext(self: *Self, new_len: usize, ctx: Context) void { // Remove index entries from the new length onwards. // Explicitly choose to ONLY remove index entries and not the underlying array list // entries as we're going to remove them in the subsequent shrink call. if (self.index_header) |header| { var i: usize = new_len; while (i < self.entries.len) : (i += 1) self.removeFromIndexByIndex(i, if (store_hash) {} else ctx, header); } self.entries.shrinkRetainingCapacity(new_len); } /// Shrinks the underlying `Entry` array to `new_len` elements and discards any associated /// index entries. Reduces allocated capacity. pub fn shrinkAndFree(self: *Self, allocator: Allocator, new_len: usize) void { if (@sizeOf(ByIndexContext) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call shrinkAndFreeContext instead."); return self.shrinkAndFreeContext(allocator, new_len, undefined); } pub fn shrinkAndFreeContext(self: *Self, allocator: Allocator, new_len: usize, ctx: Context) void { // Remove index entries from the new length onwards. // Explicitly choose to ONLY remove index entries and not the underlying array list // entries as we're going to remove them in the subsequent shrink call. if (self.index_header) |header| { var i: usize = new_len; while (i < self.entries.len) : (i += 1) self.removeFromIndexByIndex(i, if (store_hash) {} else ctx, header); } self.entries.shrinkAndFree(allocator, new_len); } /// Removes the last inserted `Entry` in the hash map and returns it. pub fn pop(self: *Self) KV { if (@sizeOf(ByIndexContext) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call popContext instead."); return self.popContext(undefined); } pub fn popContext(self: *Self, ctx: Context) KV { const item = self.entries.get(self.entries.len - 1); if (self.index_header) |header| self.removeFromIndexByIndex(self.entries.len - 1, if (store_hash) {} else ctx, header); self.entries.len -= 1; return .{ .key = item.key, .value = item.value, }; } /// Removes the last inserted `Entry` in the hash map and returns it if count is nonzero. /// Otherwise returns null. pub fn popOrNull(self: *Self) ?KV { if (@sizeOf(ByIndexContext) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call popContext instead."); return self.popOrNullContext(undefined); } pub fn popOrNullContext(self: *Self, ctx: Context) ?KV { return if (self.entries.len == 0) null else self.popContext(ctx); } // ------------------ No pub fns below this point ------------------ fn fetchRemoveByKey(self: *Self, key: anytype, key_ctx: anytype, ctx: ByIndexContext, comptime removal_type: RemovalType) ?KV { const header = self.index_header orelse { // Linear scan. const key_hash = if (store_hash) key_ctx.hash(key) else {}; const slice = self.entries.slice(); const hashes_array = if (store_hash) slice.items(.hash) else {}; const keys_array = slice.items(.key); for (keys_array) |*item_key, i| { const hash_match = if (store_hash) hashes_array[i] == key_hash else true; if (hash_match and key_ctx.eql(key, item_key.*, i)) { const removed_entry: KV = .{ .key = keys_array[i], .value = slice.items(.value)[i], }; switch (removal_type) { .swap => self.entries.swapRemove(i), .ordered => self.entries.orderedRemove(i), } return removed_entry; } } return null; }; return switch (header.capacityIndexType()) { .u8 => self.fetchRemoveByKeyGeneric(key, key_ctx, ctx, header, u8, removal_type), .u16 => self.fetchRemoveByKeyGeneric(key, key_ctx, ctx, header, u16, removal_type), .u32 => self.fetchRemoveByKeyGeneric(key, key_ctx, ctx, header, u32, removal_type), }; } fn fetchRemoveByKeyGeneric(self: *Self, key: anytype, key_ctx: anytype, ctx: ByIndexContext, header: *IndexHeader, comptime I: type, comptime removal_type: RemovalType) ?KV { const indexes = header.indexes(I); const entry_index = self.removeFromIndexByKey(key, key_ctx, header, I, indexes) orelse return null; const slice = self.entries.slice(); const removed_entry: KV = .{ .key = slice.items(.key)[entry_index], .value = slice.items(.value)[entry_index], }; self.removeFromArrayAndUpdateIndex(entry_index, ctx, header, I, indexes, removal_type); return removed_entry; } fn removeByKey(self: *Self, key: anytype, key_ctx: anytype, ctx: ByIndexContext, comptime removal_type: RemovalType) bool { const header = self.index_header orelse { // Linear scan. const key_hash = if (store_hash) key_ctx.hash(key) else {}; const slice = self.entries.slice(); const hashes_array = if (store_hash) slice.items(.hash) else {}; const keys_array = slice.items(.key); for (keys_array) |*item_key, i| { const hash_match = if (store_hash) hashes_array[i] == key_hash else true; if (hash_match and key_ctx.eql(key, item_key.*, i)) { switch (removal_type) { .swap => self.entries.swapRemove(i), .ordered => self.entries.orderedRemove(i), } return true; } } return false; }; return switch (header.capacityIndexType()) { .u8 => self.removeByKeyGeneric(key, key_ctx, ctx, header, u8, removal_type), .u16 => self.removeByKeyGeneric(key, key_ctx, ctx, header, u16, removal_type), .u32 => self.removeByKeyGeneric(key, key_ctx, ctx, header, u32, removal_type), }; } fn removeByKeyGeneric(self: *Self, key: anytype, key_ctx: anytype, ctx: ByIndexContext, header: *IndexHeader, comptime I: type, comptime removal_type: RemovalType) bool { const indexes = header.indexes(I); const entry_index = self.removeFromIndexByKey(key, key_ctx, header, I, indexes) orelse return false; self.removeFromArrayAndUpdateIndex(entry_index, ctx, header, I, indexes, removal_type); return true; } fn removeByIndex(self: *Self, entry_index: usize, ctx: ByIndexContext, comptime removal_type: RemovalType) void { assert(entry_index < self.entries.len); const header = self.index_header orelse { switch (removal_type) { .swap => self.entries.swapRemove(entry_index), .ordered => self.entries.orderedRemove(entry_index), } return; }; switch (header.capacityIndexType()) { .u8 => self.removeByIndexGeneric(entry_index, ctx, header, u8, removal_type), .u16 => self.removeByIndexGeneric(entry_index, ctx, header, u16, removal_type), .u32 => self.removeByIndexGeneric(entry_index, ctx, header, u32, removal_type), } } fn removeByIndexGeneric(self: *Self, entry_index: usize, ctx: ByIndexContext, header: *IndexHeader, comptime I: type, comptime removal_type: RemovalType) void { const indexes = header.indexes(I); self.removeFromIndexByIndexGeneric(entry_index, ctx, header, I, indexes); self.removeFromArrayAndUpdateIndex(entry_index, ctx, header, I, indexes, removal_type); } fn removeFromArrayAndUpdateIndex(self: *Self, entry_index: usize, ctx: ByIndexContext, header: *IndexHeader, comptime I: type, indexes: []Index(I), comptime removal_type: RemovalType) void { const last_index = self.entries.len - 1; // overflow => remove from empty map switch (removal_type) { .swap => { if (last_index != entry_index) { // Because of the swap remove, now we need to update the index that was // pointing to the last entry and is now pointing to this removed item slot. self.updateEntryIndex(header, last_index, entry_index, ctx, I, indexes); } // updateEntryIndex reads from the old entry index, // so it needs to run before removal. self.entries.swapRemove(entry_index); }, .ordered => { var i: usize = entry_index; while (i < last_index) : (i += 1) { // Because of the ordered remove, everything from the entry index onwards has // been shifted forward so we'll need to update the index entries. self.updateEntryIndex(header, i + 1, i, ctx, I, indexes); } // updateEntryIndex reads from the old entry index, // so it needs to run before removal. self.entries.orderedRemove(entry_index); }, } } fn updateEntryIndex( self: *Self, header: *IndexHeader, old_entry_index: usize, new_entry_index: usize, ctx: ByIndexContext, comptime I: type, indexes: []Index(I), ) void { const slot = self.getSlotByIndex(old_entry_index, ctx, header, I, indexes); indexes[slot].entry_index = @intCast(I, new_entry_index); } fn removeFromIndexByIndex(self: *Self, entry_index: usize, ctx: ByIndexContext, header: *IndexHeader) void { switch (header.capacityIndexType()) { .u8 => self.removeFromIndexByIndexGeneric(entry_index, ctx, header, u8, header.indexes(u8)), .u16 => self.removeFromIndexByIndexGeneric(entry_index, ctx, header, u16, header.indexes(u16)), .u32 => self.removeFromIndexByIndexGeneric(entry_index, ctx, header, u32, header.indexes(u32)), } } fn removeFromIndexByIndexGeneric(self: *Self, entry_index: usize, ctx: ByIndexContext, header: *IndexHeader, comptime I: type, indexes: []Index(I)) void { const slot = self.getSlotByIndex(entry_index, ctx, header, I, indexes); removeSlot(slot, header, I, indexes); } fn removeFromIndexByKey(self: *Self, key: anytype, ctx: anytype, header: *IndexHeader, comptime I: type, indexes: []Index(I)) ?usize { const slot = self.getSlotByKey(key, ctx, header, I, indexes) orelse return null; const removed_entry_index = indexes[slot].entry_index; removeSlot(slot, header, I, indexes); return removed_entry_index; } fn removeSlot(removed_slot: usize, header: *IndexHeader, comptime I: type, indexes: []Index(I)) void { const start_index = removed_slot +% 1; const end_index = start_index +% indexes.len; var last_slot = removed_slot; var index: usize = start_index; while (index != end_index) : (index +%= 1) { const slot = header.constrainIndex(index); const slot_data = indexes[slot]; if (slot_data.isEmpty() or slot_data.distance_from_start_index == 0) { indexes[last_slot].setEmpty(); return; } indexes[last_slot] = .{ .entry_index = slot_data.entry_index, .distance_from_start_index = slot_data.distance_from_start_index - 1, }; last_slot = slot; } unreachable; } fn getSlotByIndex(self: *Self, entry_index: usize, ctx: ByIndexContext, header: *IndexHeader, comptime I: type, indexes: []Index(I)) usize { const slice = self.entries.slice(); const h = if (store_hash) slice.items(.hash)[entry_index] else checkedHash(ctx, slice.items(.key)[entry_index]); const start_index = safeTruncate(usize, h); const end_index = start_index +% indexes.len; var index = start_index; var distance_from_start_index: I = 0; while (index != end_index) : ({ index +%= 1; distance_from_start_index += 1; }) { const slot = header.constrainIndex(index); const slot_data = indexes[slot]; // This is the fundamental property of the array hash map index. If this // assert fails, it probably means that the entry was not in the index. assert(!slot_data.isEmpty()); assert(slot_data.distance_from_start_index >= distance_from_start_index); if (slot_data.entry_index == entry_index) { return slot; } } unreachable; } /// Must `ensureTotalCapacity`/`ensureUnusedCapacity` before calling this. fn getOrPutInternal(self: *Self, key: anytype, ctx: anytype, header: *IndexHeader, comptime I: type) GetOrPutResult { const slice = self.entries.slice(); const hashes_array = if (store_hash) slice.items(.hash) else {}; const keys_array = slice.items(.key); const values_array = slice.items(.value); const indexes = header.indexes(I); const h = checkedHash(ctx, key); const start_index = safeTruncate(usize, h); const end_index = start_index +% indexes.len; var index = start_index; var distance_from_start_index: I = 0; while (index != end_index) : ({ index +%= 1; distance_from_start_index += 1; }) { var slot = header.constrainIndex(index); var slot_data = indexes[slot]; // If the slot is empty, there can be no more items in this run. // We didn't find a matching item, so this must be new. // Put it in the empty slot. if (slot_data.isEmpty()) { const new_index = self.entries.addOneAssumeCapacity(); indexes[slot] = .{ .distance_from_start_index = distance_from_start_index, .entry_index = @intCast(I, new_index), }; // update the hash if applicable if (store_hash) hashes_array.ptr[new_index] = h; return .{ .found_existing = false, .key_ptr = &keys_array.ptr[new_index], // workaround for #6974 .value_ptr = if (@sizeOf(*V) == 0) undefined else &values_array.ptr[new_index], .index = new_index, }; } // This pointer survives the following append because we call // entries.ensureTotalCapacity before getOrPutInternal. const i = slot_data.entry_index; const hash_match = if (store_hash) h == hashes_array[i] else true; if (hash_match and checkedEql(ctx, key, keys_array[i], i)) { return .{ .found_existing = true, .key_ptr = &keys_array[slot_data.entry_index], // workaround for #6974 .value_ptr = if (@sizeOf(*V) == 0) undefined else &values_array[slot_data.entry_index], .index = slot_data.entry_index, }; } // If the entry is closer to its target than our current distance, // the entry we are looking for does not exist. It would be in // this slot instead if it was here. So stop looking, and switch // to insert mode. if (slot_data.distance_from_start_index < distance_from_start_index) { // In this case, we did not find the item. We will put a new entry. // However, we will use this index for the new entry, and move // the previous index down the line, to keep the max distance_from_start_index // as small as possible. const new_index = self.entries.addOneAssumeCapacity(); if (store_hash) hashes_array.ptr[new_index] = h; indexes[slot] = .{ .entry_index = @intCast(I, new_index), .distance_from_start_index = distance_from_start_index, }; distance_from_start_index = slot_data.distance_from_start_index; var displaced_index = slot_data.entry_index; // Find somewhere to put the index we replaced by shifting // following indexes backwards. index +%= 1; distance_from_start_index += 1; while (index != end_index) : ({ index +%= 1; distance_from_start_index += 1; }) { slot = header.constrainIndex(index); slot_data = indexes[slot]; if (slot_data.isEmpty()) { indexes[slot] = .{ .entry_index = displaced_index, .distance_from_start_index = distance_from_start_index, }; return .{ .found_existing = false, .key_ptr = &keys_array.ptr[new_index], // workaround for #6974 .value_ptr = if (@sizeOf(*V) == 0) undefined else &values_array.ptr[new_index], .index = new_index, }; } if (slot_data.distance_from_start_index < distance_from_start_index) { indexes[slot] = .{ .entry_index = displaced_index, .distance_from_start_index = distance_from_start_index, }; displaced_index = slot_data.entry_index; distance_from_start_index = slot_data.distance_from_start_index; } } unreachable; } } unreachable; } fn getSlotByKey(self: Self, key: anytype, ctx: anytype, header: *IndexHeader, comptime I: type, indexes: []Index(I)) ?usize { const slice = self.entries.slice(); const hashes_array = if (store_hash) slice.items(.hash) else {}; const keys_array = slice.items(.key); const h = checkedHash(ctx, key); const start_index = safeTruncate(usize, h); const end_index = start_index +% indexes.len; var index = start_index; var distance_from_start_index: I = 0; while (index != end_index) : ({ index +%= 1; distance_from_start_index += 1; }) { const slot = header.constrainIndex(index); const slot_data = indexes[slot]; if (slot_data.isEmpty() or slot_data.distance_from_start_index < distance_from_start_index) return null; const i = slot_data.entry_index; const hash_match = if (store_hash) h == hashes_array[i] else true; if (hash_match and checkedEql(ctx, key, keys_array[i], i)) return slot; } unreachable; } fn insertAllEntriesIntoNewHeader(self: *Self, ctx: ByIndexContext, header: *IndexHeader) void { switch (header.capacityIndexType()) { .u8 => return self.insertAllEntriesIntoNewHeaderGeneric(ctx, header, u8), .u16 => return self.insertAllEntriesIntoNewHeaderGeneric(ctx, header, u16), .u32 => return self.insertAllEntriesIntoNewHeaderGeneric(ctx, header, u32), } } fn insertAllEntriesIntoNewHeaderGeneric(self: *Self, ctx: ByIndexContext, header: *IndexHeader, comptime I: type) void { const slice = self.entries.slice(); const items = if (store_hash) slice.items(.hash) else slice.items(.key); const indexes = header.indexes(I); entry_loop: for (items) |key, i| { const h = if (store_hash) key else checkedHash(ctx, key); const start_index = safeTruncate(usize, h); const end_index = start_index +% indexes.len; var index = start_index; var entry_index = @intCast(I, i); var distance_from_start_index: I = 0; while (index != end_index) : ({ index +%= 1; distance_from_start_index += 1; }) { const slot = header.constrainIndex(index); const next_index = indexes[slot]; if (next_index.isEmpty()) { indexes[slot] = .{ .distance_from_start_index = distance_from_start_index, .entry_index = entry_index, }; continue :entry_loop; } if (next_index.distance_from_start_index < distance_from_start_index) { indexes[slot] = .{ .distance_from_start_index = distance_from_start_index, .entry_index = entry_index, }; distance_from_start_index = next_index.distance_from_start_index; entry_index = next_index.entry_index; } } unreachable; } } inline fn checkedHash(ctx: anytype, key: anytype) u32 { comptime std.hash_map.verifyContext(@TypeOf(ctx), @TypeOf(key), K, u32, true); // If you get a compile error on the next line, it means that const hash = ctx.hash(key); // your generic hash function doesn't accept your key if (@TypeOf(hash) != u32) { @compileError("Context " ++ @typeName(@TypeOf(ctx)) ++ " has a generic hash function that returns the wrong type!\n" ++ @typeName(u32) ++ " was expected, but found " ++ @typeName(@TypeOf(hash))); } return hash; } inline fn checkedEql(ctx: anytype, a: anytype, b: K, b_index: usize) bool { comptime std.hash_map.verifyContext(@TypeOf(ctx), @TypeOf(a), K, u32, true); // If you get a compile error on the next line, it means that const eql = ctx.eql(a, b, b_index); // your generic eql function doesn't accept (self, adapt key, K, index) if (@TypeOf(eql) != bool) { @compileError("Context " ++ @typeName(@TypeOf(ctx)) ++ " has a generic eql function that returns the wrong type!\n" ++ @typeName(bool) ++ " was expected, but found " ++ @typeName(@TypeOf(eql))); } return eql; } fn dumpState(self: Self, comptime keyFmt: []const u8, comptime valueFmt: []const u8) void { if (@sizeOf(ByIndexContext) != 0) @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call dumpStateContext instead."); self.dumpStateContext(keyFmt, valueFmt, undefined); } fn dumpStateContext(self: Self, comptime keyFmt: []const u8, comptime valueFmt: []const u8, ctx: Context) void { const p = std.debug.print; p("{s}:\n", .{@typeName(Self)}); const slice = self.entries.slice(); const hash_status = if (store_hash) "stored" else "computed"; p(" len={} capacity={} hashes {s}\n", .{ slice.len, slice.capacity, hash_status }); var i: usize = 0; const mask: u32 = if (self.index_header) |header| header.mask() else ~@as(u32, 0); while (i < slice.len) : (i += 1) { const hash = if (store_hash) slice.items(.hash)[i] else checkedHash(ctx, slice.items(.key)[i]); if (store_hash) { p( " [{}]: key=" ++ keyFmt ++ " value=" ++ valueFmt ++ " hash=0x{x} slot=[0x{x}]\n", .{ i, slice.items(.key)[i], slice.items(.value)[i], hash, hash & mask }, ); } else { p( " [{}]: key=" ++ keyFmt ++ " value=" ++ valueFmt ++ " slot=[0x{x}]\n", .{ i, slice.items(.key)[i], slice.items(.value)[i], hash & mask }, ); } } if (self.index_header) |header| { p("\n", .{}); switch (header.capacityIndexType()) { .u8 => dumpIndex(header, u8), .u16 => dumpIndex(header, u16), .u32 => dumpIndex(header, u32), } } } fn dumpIndex(header: *IndexHeader, comptime I: type) void { const p = std.debug.print; p(" index len=0x{x} type={}\n", .{ header.length(), header.capacityIndexType() }); const indexes = header.indexes(I); if (indexes.len == 0) return; var is_empty = false; for (indexes) |idx, i| { if (idx.isEmpty()) { is_empty = true; } else { if (is_empty) { is_empty = false; p(" ...\n", .{}); } p(" [0x{x}]: [{}] +{}\n", .{ i, idx.entry_index, idx.distance_from_start_index }); } } if (is_empty) { p(" ...\n", .{}); } } }; } const CapacityIndexType = enum { u8, u16, u32 }; fn capacityIndexType(bit_index: u8) CapacityIndexType { if (bit_index <= 8) return .u8; if (bit_index <= 16) return .u16; assert(bit_index <= 32); return .u32; } fn capacityIndexSize(bit_index: u8) usize { switch (capacityIndexType(bit_index)) { .u8 => return @sizeOf(Index(u8)), .u16 => return @sizeOf(Index(u16)), .u32 => return @sizeOf(Index(u32)), } } /// @truncate fails if the target type is larger than the /// target value. This causes problems when one of the types /// is usize, which may be larger or smaller than u32 on different /// systems. This version of truncate is safe to use if either /// parameter has dynamic size, and will perform widening conversion /// when needed. Both arguments must have the same signedness. fn safeTruncate(comptime T: type, val: anytype) T { if (@bitSizeOf(T) >= @bitSizeOf(@TypeOf(val))) return val; return @truncate(T, val); } /// A single entry in the lookup acceleration structure. These structs /// are found in an array after the IndexHeader. Hashes index into this /// array, and linear probing is used for collisions. fn Index(comptime I: type) type { return extern struct { const Self = @This(); /// The index of this entry in the backing store. If the index is /// empty, this is empty_sentinel. entry_index: I, /// The distance between this slot and its ideal placement. This is /// used to keep maximum scan length small. This value is undefined /// if the index is empty. distance_from_start_index: I, /// The special entry_index value marking an empty slot. const empty_sentinel = ~@as(I, 0); /// A constant empty index const empty = Self{ .entry_index = empty_sentinel, .distance_from_start_index = undefined, }; /// Checks if a slot is empty fn isEmpty(idx: Self) bool { return idx.entry_index == empty_sentinel; } /// Sets a slot to empty fn setEmpty(idx: *Self) void { idx.entry_index = empty_sentinel; idx.distance_from_start_index = undefined; } }; } /// the byte size of the index must fit in a usize. This is a power of two /// length * the size of an Index(u32). The index is 8 bytes (3 bits repr) /// and max_usize + 1 is not representable, so we need to subtract out 4 bits. const max_representable_index_len = @bitSizeOf(usize) - 4; const max_bit_index = math.min(32, max_representable_index_len); const min_bit_index = 5; const max_capacity = (1 << max_bit_index) - 1; const index_capacities = blk: { var caps: [max_bit_index + 1]u32 = undefined; for (caps[0..max_bit_index]) |*item, i| { item.* = (1 << i) * 3 / 5; } caps[max_bit_index] = max_capacity; break :blk caps; }; /// This struct is trailed by two arrays of length indexes_len /// of integers, whose integer size is determined by indexes_len. /// These arrays are indexed by constrainIndex(hash). The /// entryIndexes array contains the index in the dense backing store /// where the entry's data can be found. Entries which are not in /// use have their index value set to emptySentinel(I). /// The entryDistances array stores the distance between an entry /// and its ideal hash bucket. This is used when adding elements /// to balance the maximum scan length. const IndexHeader = struct { /// This field tracks the total number of items in the arrays following /// this header. It is the bit index of the power of two number of indices. /// This value is between min_bit_index and max_bit_index, inclusive. bit_index: u8 align(@alignOf(u32)), /// Map from an incrementing index to an index slot in the attached arrays. fn constrainIndex(header: IndexHeader, i: usize) usize { // This is an optimization for modulo of power of two integers; // it requires `indexes_len` to always be a power of two. return @intCast(usize, i & header.mask()); } /// Returns the attached array of indexes. I must match the type /// returned by capacityIndexType. fn indexes(header: *IndexHeader, comptime I: type) []Index(I) { const start_ptr = @ptrCast([*]Index(I), @ptrCast([*]u8, header) + @sizeOf(IndexHeader)); return start_ptr[0..header.length()]; } /// Returns the type used for the index arrays. fn capacityIndexType(header: IndexHeader) CapacityIndexType { return hash_map.capacityIndexType(header.bit_index); } fn capacity(self: IndexHeader) u32 { return index_capacities[self.bit_index]; } fn length(self: IndexHeader) usize { return @as(usize, 1) << @intCast(math.Log2Int(usize), self.bit_index); } fn mask(self: IndexHeader) u32 { return @intCast(u32, self.length() - 1); } fn findBitIndex(desired_capacity: usize) !u8 { if (desired_capacity > max_capacity) return error.OutOfMemory; var new_bit_index = @intCast(u8, std.math.log2_int_ceil(usize, desired_capacity)); if (desired_capacity > index_capacities[new_bit_index]) new_bit_index += 1; if (new_bit_index < min_bit_index) new_bit_index = min_bit_index; assert(desired_capacity <= index_capacities[new_bit_index]); return new_bit_index; } /// Allocates an index header, and fills the entryIndexes array with empty. /// The distance array contents are undefined. fn alloc(allocator: Allocator, new_bit_index: u8) !*IndexHeader { const len = @as(usize, 1) << @intCast(math.Log2Int(usize), new_bit_index); const index_size = hash_map.capacityIndexSize(new_bit_index); const nbytes = @sizeOf(IndexHeader) + index_size * len; const bytes = try allocator.allocAdvanced(u8, @alignOf(IndexHeader), nbytes, .exact); @memset(bytes.ptr + @sizeOf(IndexHeader), 0xff, bytes.len - @sizeOf(IndexHeader)); const result = @ptrCast(*IndexHeader, bytes.ptr); result.* = .{ .bit_index = new_bit_index, }; return result; } /// Releases the memory for a header and its associated arrays. fn free(header: *IndexHeader, allocator: Allocator) void { const index_size = hash_map.capacityIndexSize(header.bit_index); const ptr = @ptrCast([*]align(@alignOf(IndexHeader)) u8, header); const slice = ptr[0 .. @sizeOf(IndexHeader) + header.length() * index_size]; allocator.free(slice); } /// Puts an IndexHeader into the state that it would be in after being freshly allocated. fn reset(header: *IndexHeader) void { const index_size = hash_map.capacityIndexSize(header.bit_index); const ptr = @ptrCast([*]align(@alignOf(IndexHeader)) u8, header); const nbytes = @sizeOf(IndexHeader) + header.length() * index_size; @memset(ptr + @sizeOf(IndexHeader), 0xff, nbytes - @sizeOf(IndexHeader)); } // Verify that the header has sufficient alignment to produce aligned arrays. comptime { if (@alignOf(u32) > @alignOf(IndexHeader)) @compileError("IndexHeader must have a larger alignment than its indexes!"); } }; test "basic hash map usage" { var map = AutoArrayHashMap(i32, i32).init(std.testing.allocator); defer map.deinit(); try testing.expect((try map.fetchPut(1, 11)) == null); try testing.expect((try map.fetchPut(2, 22)) == null); try testing.expect((try map.fetchPut(3, 33)) == null); try testing.expect((try map.fetchPut(4, 44)) == null); try map.putNoClobber(5, 55); try testing.expect((try map.fetchPut(5, 66)).?.value == 55); try testing.expect((try map.fetchPut(5, 55)).?.value == 66); const gop1 = try map.getOrPut(5); try testing.expect(gop1.found_existing == true); try testing.expect(gop1.value_ptr.* == 55); try testing.expect(gop1.index == 4); gop1.value_ptr.* = 77; try testing.expect(map.getEntry(5).?.value_ptr.* == 77); const gop2 = try map.getOrPut(99); try testing.expect(gop2.found_existing == false); try testing.expect(gop2.index == 5); gop2.value_ptr.* = 42; try testing.expect(map.getEntry(99).?.value_ptr.* == 42); const gop3 = try map.getOrPutValue(5, 5); try testing.expect(gop3.value_ptr.* == 77); const gop4 = try map.getOrPutValue(100, 41); try testing.expect(gop4.value_ptr.* == 41); try testing.expect(map.contains(2)); try testing.expect(map.getEntry(2).?.value_ptr.* == 22); try testing.expect(map.get(2).? == 22); const rmv1 = map.fetchSwapRemove(2); try testing.expect(rmv1.?.key == 2); try testing.expect(rmv1.?.value == 22); try testing.expect(map.fetchSwapRemove(2) == null); try testing.expect(map.swapRemove(2) == false); try testing.expect(map.getEntry(2) == null); try testing.expect(map.get(2) == null); // Since we've used `swapRemove` above, the index of this entry should remain unchanged. try testing.expect(map.getIndex(100).? == 1); const gop5 = try map.getOrPut(5); try testing.expect(gop5.found_existing == true); try testing.expect(gop5.value_ptr.* == 77); try testing.expect(gop5.index == 4); // Whereas, if we do an `orderedRemove`, it should move the index forward one spot. const rmv2 = map.fetchOrderedRemove(100); try testing.expect(rmv2.?.key == 100); try testing.expect(rmv2.?.value == 41); try testing.expect(map.fetchOrderedRemove(100) == null); try testing.expect(map.orderedRemove(100) == false); try testing.expect(map.getEntry(100) == null); try testing.expect(map.get(100) == null); const gop6 = try map.getOrPut(5); try testing.expect(gop6.found_existing == true); try testing.expect(gop6.value_ptr.* == 77); try testing.expect(gop6.index == 3); try testing.expect(map.swapRemove(3)); } test "iterator hash map" { var reset_map = AutoArrayHashMap(i32, i32).init(std.testing.allocator); defer reset_map.deinit(); // test ensureTotalCapacity with a 0 parameter try reset_map.ensureTotalCapacity(0); try reset_map.putNoClobber(0, 11); try reset_map.putNoClobber(1, 22); try reset_map.putNoClobber(2, 33); var keys = [_]i32{ 0, 2, 1, }; var values = [_]i32{ 11, 33, 22, }; var buffer = [_]i32{ 0, 0, 0, }; var it = reset_map.iterator(); const first_entry = it.next().?; it.reset(); var count: usize = 0; while (it.next()) |entry| : (count += 1) { buffer[@intCast(usize, entry.key_ptr.*)] = entry.value_ptr.*; } try testing.expect(count == 3); try testing.expect(it.next() == null); for (buffer) |_, i| { try testing.expect(buffer[@intCast(usize, keys[i])] == values[i]); } it.reset(); count = 0; while (it.next()) |entry| { buffer[@intCast(usize, entry.key_ptr.*)] = entry.value_ptr.*; count += 1; if (count >= 2) break; } for (buffer[0..2]) |_, i| { try testing.expect(buffer[@intCast(usize, keys[i])] == values[i]); } it.reset(); var entry = it.next().?; try testing.expect(entry.key_ptr.* == first_entry.key_ptr.*); try testing.expect(entry.value_ptr.* == first_entry.value_ptr.*); } test "ensure capacity" { var map = AutoArrayHashMap(i32, i32).init(std.testing.allocator); defer map.deinit(); try map.ensureTotalCapacity(20); const initial_capacity = map.capacity(); try testing.expect(initial_capacity >= 20); var i: i32 = 0; while (i < 20) : (i += 1) { try testing.expect(map.fetchPutAssumeCapacity(i, i + 10) == null); } // shouldn't resize from putAssumeCapacity try testing.expect(initial_capacity == map.capacity()); } test "big map" { var map = AutoArrayHashMap(i32, i32).init(std.testing.allocator); defer map.deinit(); var i: i32 = 0; while (i < 8) : (i += 1) { try map.put(i, i + 10); } i = 0; while (i < 8) : (i += 1) { try testing.expectEqual(@as(?i32, i + 10), map.get(i)); } while (i < 16) : (i += 1) { try testing.expectEqual(@as(?i32, null), map.get(i)); } i = 4; while (i < 12) : (i += 1) { try map.put(i, i + 12); } i = 0; while (i < 4) : (i += 1) { try testing.expectEqual(@as(?i32, i + 10), map.get(i)); } while (i < 12) : (i += 1) { try testing.expectEqual(@as(?i32, i + 12), map.get(i)); } while (i < 16) : (i += 1) { try testing.expectEqual(@as(?i32, null), map.get(i)); } i = 0; while (i < 4) : (i += 1) { try testing.expect(map.orderedRemove(i)); } while (i < 8) : (i += 1) { try testing.expect(map.swapRemove(i)); } i = 0; while (i < 8) : (i += 1) { try testing.expectEqual(@as(?i32, null), map.get(i)); } while (i < 12) : (i += 1) { try testing.expectEqual(@as(?i32, i + 12), map.get(i)); } while (i < 16) : (i += 1) { try testing.expectEqual(@as(?i32, null), map.get(i)); } } test "clone" { var original = AutoArrayHashMap(i32, i32).init(std.testing.allocator); defer original.deinit(); // put more than `linear_scan_max` so we can test that the index header is properly cloned var i: u8 = 0; while (i < 10) : (i += 1) { try original.putNoClobber(i, i * 10); } var copy = try original.clone(); defer copy.deinit(); i = 0; while (i < 10) : (i += 1) { try testing.expect(original.get(i).? == i * 10); try testing.expect(copy.get(i).? == i * 10); try testing.expect(original.getPtr(i).? != copy.getPtr(i).?); } while (i < 20) : (i += 1) { try testing.expect(original.get(i) == null); try testing.expect(copy.get(i) == null); } } test "shrink" { var map = AutoArrayHashMap(i32, i32).init(std.testing.allocator); defer map.deinit(); // This test is more interesting if we insert enough entries to allocate the index header. const num_entries = 20; var i: i32 = 0; while (i < num_entries) : (i += 1) try testing.expect((try map.fetchPut(i, i * 10)) == null); try testing.expect(map.unmanaged.index_header != null); try testing.expect(map.count() == num_entries); // Test `shrinkRetainingCapacity`. map.shrinkRetainingCapacity(17); try testing.expect(map.count() == 17); try testing.expect(map.capacity() == 20); i = 0; while (i < num_entries) : (i += 1) { const gop = try map.getOrPut(i); if (i < 17) { try testing.expect(gop.found_existing == true); try testing.expect(gop.value_ptr.* == i * 10); } else try testing.expect(gop.found_existing == false); } // Test `shrinkAndFree`. map.shrinkAndFree(15); try testing.expect(map.count() == 15); try testing.expect(map.capacity() == 15); i = 0; while (i < num_entries) : (i += 1) { const gop = try map.getOrPut(i); if (i < 15) { try testing.expect(gop.found_existing == true); try testing.expect(gop.value_ptr.* == i * 10); } else try testing.expect(gop.found_existing == false); } } test "pop" { var map = AutoArrayHashMap(i32, i32).init(std.testing.allocator); defer map.deinit(); // Insert just enough entries so that the map expands. Afterwards, // pop all entries out of the map. var i: i32 = 0; while (i < 9) : (i += 1) { try testing.expect((try map.fetchPut(i, i)) == null); } while (i > 0) : (i -= 1) { const pop = map.pop(); try testing.expect(pop.key == i - 1 and pop.value == i - 1); } } test "popOrNull" { var map = AutoArrayHashMap(i32, i32).init(std.testing.allocator); defer map.deinit(); // Insert just enough entries so that the map expands. Afterwards, // pop all entries out of the map. var i: i32 = 0; while (i < 9) : (i += 1) { try testing.expect((try map.fetchPut(i, i)) == null); } while (map.popOrNull()) |pop| { try testing.expect(pop.key == i - 1 and pop.value == i - 1); i -= 1; } try testing.expect(map.count() == 0); } test "reIndex" { var map = ArrayHashMap(i32, i32, AutoContext(i32), true).init(std.testing.allocator); defer map.deinit(); // Populate via the API. const num_indexed_entries = 20; var i: i32 = 0; while (i < num_indexed_entries) : (i += 1) try testing.expect((try map.fetchPut(i, i * 10)) == null); // Make sure we allocated an index header. try testing.expect(map.unmanaged.index_header != null); // Now write to the underlying array list directly. const num_unindexed_entries = 20; const hash = getAutoHashFn(i32, void); var al = &map.unmanaged.entries; while (i < num_indexed_entries + num_unindexed_entries) : (i += 1) { try al.append(std.testing.allocator, .{ .key = i, .value = i * 10, .hash = hash({}, i), }); } // After reindexing, we should see everything. try map.reIndex(); i = 0; while (i < num_indexed_entries + num_unindexed_entries) : (i += 1) { const gop = try map.getOrPut(i); try testing.expect(gop.found_existing == true); try testing.expect(gop.value_ptr.* == i * 10); try testing.expect(gop.index == i); } } test "auto store_hash" { const HasCheapEql = AutoArrayHashMap(i32, i32); const HasExpensiveEql = AutoArrayHashMap([32]i32, i32); try testing.expect(meta.fieldInfo(HasCheapEql.Data, .hash).field_type == void); try testing.expect(meta.fieldInfo(HasExpensiveEql.Data, .hash).field_type != void); const HasCheapEqlUn = AutoArrayHashMapUnmanaged(i32, i32); const HasExpensiveEqlUn = AutoArrayHashMapUnmanaged([32]i32, i32); try testing.expect(meta.fieldInfo(HasCheapEqlUn.Data, .hash).field_type == void); try testing.expect(meta.fieldInfo(HasExpensiveEqlUn.Data, .hash).field_type != void); } test "sort" { var map = AutoArrayHashMap(i32, i32).init(std.testing.allocator); defer map.deinit(); for ([_]i32{ 8, 3, 12, 10, 2, 4, 9, 5, 6, 13, 14, 15, 16, 1, 11, 17, 7 }) |x| { try map.put(x, x * 3); } const C = struct { keys: []i32, pub fn lessThan(ctx: @This(), a_index: usize, b_index: usize) bool { return ctx.keys[a_index] < ctx.keys[b_index]; } }; map.sort(C{ .keys = map.keys() }); var x: i32 = 1; for (map.keys()) |key, i| { try testing.expect(key == x); try testing.expect(map.values()[i] == x * 3); x += 1; } } pub fn getHashPtrAddrFn(comptime K: type, comptime Context: type) (fn (Context, K) u32) { return struct { fn hash(ctx: Context, key: K) u32 { _ = ctx; return getAutoHashFn(usize, void)({}, @ptrToInt(key)); } }.hash; } pub fn getTrivialEqlFn(comptime K: type, comptime Context: type) (fn (Context, K, K) bool) { return struct { fn eql(ctx: Context, a: K, b: K) bool { _ = ctx; return a == b; } }.eql; } pub fn AutoContext(comptime K: type) type { return struct { pub const hash = getAutoHashFn(K, @This()); pub const eql = getAutoEqlFn(K, @This()); }; } pub fn getAutoHashFn(comptime K: type, comptime Context: type) (fn (Context, K) u32) { return struct { fn hash(ctx: Context, key: K) u32 { _ = ctx; if (comptime trait.hasUniqueRepresentation(K)) { return @truncate(u32, Wyhash.hash(0, std.mem.asBytes(&key))); } else { var hasher = Wyhash.init(0); autoHash(&hasher, key); return @truncate(u32, hasher.final()); } } }.hash; } pub fn getAutoEqlFn(comptime K: type, comptime Context: type) (fn (Context, K, K, usize) bool) { return struct { fn eql(ctx: Context, a: K, b: K, b_index: usize) bool { _ = b_index; _ = ctx; return meta.eql(a, b); } }.eql; } pub fn autoEqlIsCheap(comptime K: type) bool { return switch (@typeInfo(K)) { .Bool, .Int, .Float, .Pointer, .ComptimeFloat, .ComptimeInt, .Enum, .Fn, .ErrorSet, .AnyFrame, .EnumLiteral, => true, else => false, }; } pub fn getAutoHashStratFn(comptime K: type, comptime Context: type, comptime strategy: std.hash.Strategy) (fn (Context, K) u32) { return struct { fn hash(ctx: Context, key: K) u32 { _ = ctx; var hasher = Wyhash.init(0); std.hash.autoHashStrat(&hasher, key, strategy); return @truncate(u32, hasher.final()); } }.hash; }
lib/std/array_hash_map.zig
const std = @import("std"); const assert = std.debug.assert; const builtin = std.builtin; const crypto = std.crypto; const debug = std.debug; const Ghash = std.crypto.onetimeauth.Ghash; const mem = std.mem; const modes = crypto.core.modes; pub const Aes128Gcm = AesGcm(crypto.core.aes.Aes128); pub const Aes256Gcm = AesGcm(crypto.core.aes.Aes256); fn AesGcm(comptime Aes: anytype) type { debug.assert(Aes.block.block_length == 16); return struct { pub const tag_length = 16; pub const nonce_length = 12; pub const key_length = Aes.key_bits / 8; const zeros = [_]u8{0} ** 16; pub fn encrypt(c: []u8, tag: *[tag_length]u8, m: []const u8, ad: []const u8, npub: [nonce_length]u8, key: [key_length]u8) void { debug.assert(c.len == m.len); debug.assert(m.len <= 16 * ((1 << 32) - 2)); const aes = Aes.initEnc(key); var h: [16]u8 = undefined; aes.encrypt(&h, &zeros); var t: [16]u8 = undefined; var j: [16]u8 = undefined; mem.copy(u8, j[0..nonce_length], npub[0..]); mem.writeIntBig(u32, j[nonce_length..][0..4], 1); aes.encrypt(&t, &j); var mac = Ghash.init(&h); mac.update(ad); mac.pad(); mem.writeIntBig(u32, j[nonce_length..][0..4], 2); modes.ctr(@TypeOf(aes), aes, c, m, j, builtin.Endian.Big); mac.update(c[0..m.len][0..]); mac.pad(); var final_block = h; mem.writeIntBig(u64, final_block[0..8], ad.len * 8); mem.writeIntBig(u64, final_block[8..16], m.len * 8); mac.update(&final_block); mac.final(tag); for (t) |x, i| { tag[i] ^= x; } } pub fn decrypt(m: []u8, c: []const u8, tag: [tag_length]u8, ad: []const u8, npub: [nonce_length]u8, key: [key_length]u8) !void { assert(c.len == m.len); const aes = Aes.initEnc(key); var h: [16]u8 = undefined; aes.encrypt(&h, &zeros); var t: [16]u8 = undefined; var j: [16]u8 = undefined; mem.copy(u8, j[0..nonce_length], npub[0..]); mem.writeIntBig(u32, j[nonce_length..][0..4], 1); aes.encrypt(&t, &j); var mac = Ghash.init(&h); mac.update(ad); mac.pad(); mac.update(c); mac.pad(); var final_block = h; mem.writeIntBig(u64, final_block[0..8], ad.len * 8); mem.writeIntBig(u64, final_block[8..16], m.len * 8); mac.update(&final_block); var computed_tag: [Ghash.mac_length]u8 = undefined; mac.final(&computed_tag); for (t) |x, i| { computed_tag[i] ^= x; } var acc: u8 = 0; for (computed_tag) |_, p| { acc |= (computed_tag[p] ^ tag[p]); } if (acc != 0) { mem.set(u8, m, 0xaa); return error.AuthenticationFailed; } mem.writeIntBig(u32, j[nonce_length..][0..4], 2); modes.ctr(@TypeOf(aes), aes, m, c, j, builtin.Endian.Big); } }; } const htest = @import("test.zig"); const testing = std.testing; test "Aes256Gcm - Empty message and no associated data" { const key: [Aes256Gcm.key_length]u8 = [_]u8{0x69} ** Aes256Gcm.key_length; const nonce: [Aes256Gcm.nonce_length]u8 = [_]u8{0x42} ** Aes256Gcm.nonce_length; const ad = ""; const m = ""; var c: [m.len]u8 = undefined; var m2: [m.len]u8 = undefined; var tag: [Aes256Gcm.tag_length]u8 = undefined; Aes256Gcm.encrypt(&c, &tag, m, ad, nonce, key); htest.assertEqual("6b6ff610a16fa4cd59f1fb7903154e92", &tag); } test "Aes256Gcm - Associated data only" { const key: [Aes256Gcm.key_length]u8 = [_]u8{0x69} ** Aes256Gcm.key_length; const nonce: [Aes256Gcm.nonce_length]u8 = [_]u8{0x42} ** Aes256Gcm.nonce_length; const m = ""; const ad = "Test with associated data"; var c: [m.len]u8 = undefined; var tag: [Aes256Gcm.tag_length]u8 = undefined; Aes256Gcm.encrypt(&c, &tag, m, ad, nonce, key); htest.assertEqual("262ed164c2dfb26e080a9d108dd9dd4c", &tag); } test "Aes256Gcm - Message only" { const key: [Aes256Gcm.key_length]u8 = [_]u8{0x69} ** Aes256Gcm.key_length; const nonce: [Aes256Gcm.nonce_length]u8 = [_]u8{0x42} ** Aes256Gcm.nonce_length; const m = "Test with message only"; const ad = ""; var c: [m.len]u8 = undefined; var m2: [m.len]u8 = undefined; var tag: [Aes256Gcm.tag_length]u8 = undefined; Aes256Gcm.encrypt(&c, &tag, m, ad, nonce, key); try Aes256Gcm.decrypt(&m2, &c, tag, ad, nonce, key); testing.expectEqualSlices(u8, m[0..], m2[0..]); htest.assertEqual("5ca1642d90009fea33d01f78cf6eefaf01d539472f7c", &c); htest.assertEqual("07cd7fc9103e2f9e9bf2dfaa319caff4", &tag); } test "Aes256Gcm - Message and associated data" { const key: [Aes256Gcm.key_length]u8 = [_]u8{0x69} ** Aes256Gcm.key_length; const nonce: [Aes256Gcm.nonce_length]u8 = [_]u8{0x42} ** Aes256Gcm.nonce_length; const m = "Test with message"; const ad = "Test with associated data"; var c: [m.len]u8 = undefined; var m2: [m.len]u8 = undefined; var tag: [Aes256Gcm.tag_length]u8 = undefined; Aes256Gcm.encrypt(&c, &tag, m, ad, nonce, key); try Aes256Gcm.decrypt(&m2, &c, tag, ad, nonce, key); testing.expectEqualSlices(u8, m[0..], m2[0..]); htest.assertEqual("5ca1642d90009fea33d01f78cf6eefaf01", &c); htest.assertEqual("64accec679d444e2373bd9f6796c0d2c", &tag); }
lib/std/crypto/aes_gcm.zig
const std = @import("std"); const builtin = @import("builtin"); const ThreadPool = @This(); mutex: std.Thread.Mutex = .{}, is_running: bool = true, allocator: std.mem.Allocator, workers: []Worker, run_queue: RunQueue = .{}, idle_queue: IdleQueue = .{}, const IdleQueue = std.SinglyLinkedList(std.Thread.ResetEvent); const RunQueue = std.SinglyLinkedList(Runnable); const Runnable = struct { runFn: RunProto, }; const RunProto = switch (builtin.zig_backend) { .stage1 => fn (*Runnable) void, else => *const fn (*Runnable) void, }; const Worker = struct { pool: *ThreadPool, thread: std.Thread, /// The node is for this worker only and must have an already initialized event /// when the thread is spawned. idle_node: IdleQueue.Node, fn run(worker: *Worker) void { const pool = worker.pool; while (true) { pool.mutex.lock(); if (pool.run_queue.popFirst()) |run_node| { pool.mutex.unlock(); (run_node.data.runFn)(&run_node.data); continue; } if (pool.is_running) { worker.idle_node.data.reset(); pool.idle_queue.prepend(&worker.idle_node); pool.mutex.unlock(); worker.idle_node.data.wait(); continue; } pool.mutex.unlock(); return; } } }; pub fn init(self: *ThreadPool, allocator: std.mem.Allocator) !void { self.* = .{ .allocator = allocator, .workers = &[_]Worker{}, }; if (builtin.single_threaded) return; const worker_count = std.math.max(1, std.Thread.getCpuCount() catch 1); self.workers = try allocator.alloc(Worker, worker_count); errdefer allocator.free(self.workers); var worker_index: usize = 0; errdefer self.destroyWorkers(worker_index); while (worker_index < worker_count) : (worker_index += 1) { const worker = &self.workers[worker_index]; worker.pool = self; // Each worker requires its ResetEvent to be pre-initialized. try worker.idle_node.data.init(); errdefer worker.idle_node.data.deinit(); worker.thread = try std.Thread.spawn(.{}, Worker.run, .{worker}); } } fn destroyWorkers(self: *ThreadPool, spawned: usize) void { if (builtin.single_threaded) return; for (self.workers[0..spawned]) |*worker| { worker.thread.join(); worker.idle_node.data.deinit(); } } pub fn deinit(self: *ThreadPool) void { { self.mutex.lock(); defer self.mutex.unlock(); self.is_running = false; while (self.idle_queue.popFirst()) |idle_node| idle_node.data.set(); } self.destroyWorkers(self.workers.len); self.allocator.free(self.workers); } pub fn spawn(self: *ThreadPool, comptime func: anytype, args: anytype) !void { if (builtin.single_threaded) { @call(.{}, func, args); return; } const Args = @TypeOf(args); const Closure = struct { arguments: Args, pool: *ThreadPool, run_node: RunQueue.Node = .{ .data = .{ .runFn = runFn } }, fn runFn(runnable: *Runnable) void { const run_node = @fieldParentPtr(RunQueue.Node, "data", runnable); const closure = @fieldParentPtr(@This(), "run_node", run_node); @call(.{}, func, closure.arguments); const mutex = &closure.pool.mutex; mutex.lock(); defer mutex.unlock(); closure.pool.allocator.destroy(closure); } }; self.mutex.lock(); defer self.mutex.unlock(); const closure = try self.allocator.create(Closure); closure.* = .{ .arguments = args, .pool = self, }; self.run_queue.prepend(&closure.run_node); if (self.idle_queue.popFirst()) |idle_node| idle_node.data.set(); }
src/ThreadPool.zig
const std = @import("std"); const fmt = std.fmt; const fs = std.fs; const heap = std.heap; const json = std.json; const mem = std.mem; const meta = std.meta; const os = std.os; const path = std.fs.path; const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const Allocator = mem.Allocator; const util = @import("util.zig"); const json_file = "attributes.json"; pub fn DatasetAttributes(comptime AttributesType: type) type { return struct { allocator: Allocator, dimensions: []u64, blockSize: []u64, dataType: DataType, compression: Compression, const Self = @This(); pub fn init(allocator: Allocator, source: []const u8) !Self { var str: []u8 = undefined; defer allocator.free(str); var attr: AttributesType = undefined; switch (AttributesType) { std.fs.File => { defer attr.close(); var full_path = try path.join(allocator, &.{ source, json_file }); defer allocator.free(full_path); attr = try fs.openFileAbsolute(full_path, .{}); var max_size = try attr.getEndPos(); str = try attr.readToEndAlloc(allocator, max_size); }, []u8, []const u8 => { str = try allocator.alloc(u8, source.len); std.mem.copy(u8, str, source[0..]); }, else => unreachable, } var stream = json.TokenStream.init(str); var next_data_type = false; var next_compression = false; var next_compression_type = false; var next_dimensions = false; var next_block_size = false; var next_level = false; var next_zlib = false; var data_type: DataType = undefined; var compression_type: CompressionType = undefined; var dimensions = std.ArrayList(u64).init(allocator); var block_size = std.ArrayList(u64).init(allocator); var comp_block_size: u32 = 0; var level: i32 = 0; var zlib = false; while (try stream.next()) |token| { switch (token) { .String => |string| { var st = string.slice(stream.slice, stream.i - 1); if (mem.eql(u8, st, "dataType")) { next_data_type = true; continue; } if (mem.eql(u8, st, "compression")) { next_compression = true; continue; } if (mem.eql(u8, st, "type")) { next_compression_type = true; continue; } if (mem.eql(u8, st, "dimensions")) { next_dimensions = true; continue; } if (mem.eql(u8, st, "blockSize")) { next_block_size = true; continue; } if (mem.eql(u8, st, "level")) { next_level = true; continue; } if (mem.eql(u8, st, "useZlib")) { next_zlib = true; continue; } if (next_data_type) { data_type = meta.stringToEnum(DataType, st).?; next_data_type = false; continue; } if (next_compression_type) { compression_type = meta.stringToEnum(CompressionType, st).?; next_compression_type = false; continue; } }, .ObjectBegin => {}, .ObjectEnd => { if (next_compression) { next_compression = false; continue; } }, .ArrayBegin => {}, .ArrayEnd => { if (next_dimensions) { next_dimensions = false; continue; } if (next_block_size) { next_block_size = false; continue; } }, .Number => |num| { if (next_dimensions) { var val = try fmt.parseInt(u64, num.slice(stream.slice, stream.i - 1), 10); try dimensions.append(val); continue; } if (next_block_size) { if (next_compression) { var val = try fmt.parseInt(u32, num.slice(stream.slice, stream.i - 1), 10); comp_block_size = val; next_block_size = false; continue; } else { var val = try fmt.parseInt(u64, num.slice(stream.slice, stream.i - 1), 10); try block_size.append(val); continue; } } if (next_level) { var val = try fmt.parseInt(i32, num.slice(stream.slice, stream.i - 1), 10); level = val; next_level = false; continue; } }, .True => { if (next_zlib) { zlib = true; next_zlib = false; continue; } }, .False => { if (next_zlib) { next_zlib = false; continue; } }, .Null => {}, } } // json.parse does not allow to have optional fields for now // // var d_attr = try json.parse(DatasetAttributes, &stream, .{ .allocator = allocator, .ignore_unknown_fields = true }); // defer json.parseFree(DatasetAttributes, d_attr, .{ .allocator = allocator }); return Self{ .allocator = allocator, .dataType = data_type, .compression = Compression{ .type = compression_type, .useZlib = zlib, .level = level, .blockSize = comp_block_size, }, .dimensions = dimensions.toOwnedSlice(), .blockSize = block_size.toOwnedSlice(), }; } pub fn deinit(self: *Self) void { self.allocator.free(self.dimensions); self.allocator.free(self.blockSize); } }; } pub const Compression = struct { type: CompressionType, useZlib: bool, level: i32, blockSize: u32, }; pub const CompressionType = enum { bzip2, blosc, gzip, lz4, raw, xz, }; pub const DataType = enum { uint8, uint16, uint32, uint64, int8, int16, int32, int64, float32, float64, object, }; test "init file" { var gpa = heap.GeneralPurposeAllocator(.{}){}; var allocator = gpa.allocator(); comptime var buff_size = util.pathBufferSize(); var path_buffer: [buff_size]u8 = undefined; var full_path = try fs.realpath("testdata/lynx_raw/data.n5/0/0", &path_buffer); var da = try DatasetAttributes(std.fs.File).init(allocator, full_path); try expect(da.dataType == DataType.uint8); var expected_dim = [_]u64{ 1920, 1080, 3, 1, 1 }; for (expected_dim) |dim, i| { try expect(da.dimensions[i] == dim); } var expected_block_size = [_]u64{ 512, 512, 1, 1, 1 }; for (expected_block_size) |block, i| { try expect(da.blockSize[i] == block); } try expect(da.compression.type == CompressionType.raw); try expect(da.compression.useZlib == false); try expect(da.compression.blockSize == 0); try expect(da.compression.level == 0); da.deinit(); try expect(!gpa.deinit()); } test "init buffer" { var attr = "{\"dataType\":\"uint8\",\"compression\":{\"type\":\"lz4\",\"blockSize\":65536},\"blockSize\":[512,512,1,1,1],\"dimensions\":[1920,1080,3,1,1]}"; var gpa = heap.GeneralPurposeAllocator(.{}){}; var allocator = gpa.allocator(); var da = try DatasetAttributes([]const u8).init(allocator, attr); try expect(da.dataType == DataType.uint8); var expected_dim = [_]u64{ 1920, 1080, 3, 1, 1 }; for (expected_dim) |dim, i| { try expect(da.dimensions[i] == dim); } var expected_block_size = [_]u64{ 512, 512, 1, 1, 1 }; for (expected_block_size) |block, i| { try expect(da.blockSize[i] == block); } try expect(da.compression.type == CompressionType.lz4); try expect(da.compression.useZlib == false); try expect(da.compression.blockSize == 65536); try expect(da.compression.level == 0); da.deinit(); try expect(!gpa.deinit()); }
src/dataset_attributes.zig
const std = @import("std"); const testing = std.testing; const c = @import("c.zig").c; pub usingnamespace @import("consts.zig"); pub const Error = @import("errors.zig").Error; const getError = @import("errors.zig").getError; pub const action = @import("action.zig"); pub const gamepad_axis = @import("gamepad_axis.zig"); pub const gamepad_button = @import("gamepad_button.zig"); pub const GammaRamp = @import("GammaRamp.zig"); pub const hat = @import("hat.zig"); pub const Image = @import("Image.zig"); pub const joystick = @import("joystick.zig"); pub const key = @import("key.zig"); pub const mod = @import("mod.zig"); pub const Monitor = @import("Monitor.zig"); pub const mouse_button = @import("mouse_button.zig"); pub const version = @import("version.zig"); pub const VideoMode = @import("VideoMode.zig"); pub const Window = @import("Window.zig"); /// Initializes the GLFW library. /// /// This function initializes the GLFW library. Before most GLFW functions can be used, GLFW must /// be initialized, and before an application terminates GLFW should be terminated in order to free /// any resources allocated during or after initialization. /// /// If this function fails, it calls glfw.Terminate before returning. If it succeeds, you should /// call glfw.Terminate before the application exits. /// /// Additional calls to this function after successful initialization but before termination will /// return immediately with no error. /// /// macos: This function will change the current directory of the application to the /// `Contents/Resources` subdirectory of the application's bundle, if present. This can be disabled /// with the glfw.COCOA_CHDIR_RESOURCES init hint. /// /// x11: This function will set the `LC_CTYPE` category of the application locale according to the /// current environment if that category is still "C". This is because the "C" locale breaks /// Unicode text input. /// /// @thread_safety This function must only be called from the main thread. pub inline fn init() Error!void { _ = c.glfwInit(); return try getError(); } /// Terminates the GLFW library. /// /// This function destroys all remaining windows and cursors, restores any modified gamma ramps /// and frees any other allocated resources. Once this function is called, you must again call /// glfw.init successfully before you will be able to use most GLFW functions. /// /// If GLFW has been successfully initialized, this function should be called before the /// application exits. If initialization fails, there is no need to call this function, as it is /// called by glfw.init before it returns failure. /// /// This function has no effect if GLFW is not initialized. /// /// Possible errors include glfw.Error.PlatformError. /// /// remark: This function may be called before glfw.init. /// /// warning: The contexts of any remaining windows must not be current on any other thread when /// this function is called. /// /// reentrancy: This function must not be called from a callback. /// /// thread_safety: This function must only be called from the main thread. pub inline fn terminate() void { c.glfwTerminate(); } /// Sets the specified init hint to the desired value. /// /// This function sets hints for the next initialization of GLFW. /// /// The values you set hints to are never reset by GLFW, but they only take effect during /// initialization. Once GLFW has been initialized, any values you set will be ignored until the /// library is terminated and initialized again. /// /// Some hints are platform specific. These may be set on any platform but they will only affect /// their specific platform. Other platforms will ignore them. Setting these hints requires no /// platform specific headers or functions. /// /// @param hint: The init hint to set. /// @param value: The new value of the init hint. /// /// Possible errors include glfw.Error.InvalidEnum and glfw.Error.InvalidValue. /// /// @remarks This function may be called before glfw.init. /// /// @thread_safety This function must only be called from the main thread. pub inline fn initHint(hint: c_int, value: c_int) Error!void { c.glfwInitHint(hint, value); try getError(); } /// Returns a string describing the compile-time configuration. /// /// This function returns the compile-time generated version string of the GLFW library binary. It /// describes the version, platform, compiler and any platform-specific compile-time options. It /// should not be confused with the OpenGL or OpenGL ES version string, queried with `glGetString`. /// /// __Do not use the version string__ to parse the GLFW library version. Use the glfw.version /// constants instead. /// /// @return The ASCII encoded GLFW version string. /// /// @errors None. /// /// @remark This function may be called before @ref glfwInit. /// /// @pointer_lifetime The returned string is static and compile-time generated. /// /// @thread_safety This function may be called from any thread. pub inline fn getVersionString() [*c]const u8 { return c.glfwGetVersionString(); } pub fn basicTest() !void { try init(); defer terminate(); const window = Window.create(640, 480, "GLFW example", null, null) catch |err| { // return without fail, because most of our CI environments are headless / we cannot open // windows on them. std.debug.print("note: failed to create window: {}\n", .{err}); return; }; defer window.destroy(); var start = std.time.milliTimestamp(); while (std.time.milliTimestamp() < start + 1000 and !window.shouldClose()) { c.glfwPollEvents(); } } test "version" { // Reference these so the tests in these files get pulled in / ran. _ = Monitor; _ = GammaRamp; _ = Image; _ = VideoMode; _ = Window; std.debug.print("\nGLFW version v{}.{}.{}\n", .{ version.major, version.minor, version.revision }); std.debug.print("\nstring: {s}\n", .{getVersionString()}); } test "basic" { try basicTest(); }
glfw/src/main.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/day10.txt"); // const data = @embedFile("../data/day10-tst.txt"); pub fn main() !void { var it = tokenize(u8, data, "\r\n"); var part1: usize = 0; var part2 = List(usize).init(gpa); while (it.next()) |line| { var p2: usize = 0; try handleLine(line, &part1, &p2); if (p2 > 0) { try part2.append(p2); } } std.sort.sort(usize, part2.items, {}, comptime std.sort.asc(usize)); print("{} {}\n", .{ part1, part2.items[(part2.items.len / 2)] }); } fn handleLine(line: []const u8, part1: *usize, part2: *usize) !void { var stack = List(u8).init(gpa); defer stack.deinit(); for (line) |c| { if (isOpening(c)) { try stack.append(c); } else { assert(isClosing(c)); const top = stack.pop(); if (getCorresponding(c) != top) { switch (c) { ')' => part1.* += 3, ']' => part1.* += 57, '}' => part1.* += 1197, '>' => part1.* += 25137, else => unreachable, } return; } } } var score: usize = 0; while (stack.popOrNull()) |top| { score *= 5; const c = getCorresponding(top); switch (c) { ')' => score += 1, ']' => score += 2, '}' => score += 3, '>' => score += 4, else => unreachable, } } part2.* = score; } fn getCorresponding(char: u8) u8 { switch (char) { '(' => return ')', '{' => return '}', '[' => return ']', '<' => return '>', ')' => return '(', '}' => return '{', ']' => return '[', '>' => return '<', else => unreachable, } } fn isOpening(char: u8) bool { switch (char) { '(', '[', '<', '{' => return true, else => return false, } } fn isClosing(char: u8) bool { switch (char) { ')', ']', '>', '}' => return true, else => return false, } } fn getCost(char: u8) usize { switch (char) { ')' => return 3, ']' => return 57, '}' => return 1197, '>' => return 25137, else => unreachable, } } // 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/day10.zig
const std = @import("std"); const io = std.io; const Allocator = std.mem.Allocator; const expect = std.testing.expect; const test_allocator = std.testing.allocator; pub fn main() anyerror!void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); var allocator = &gpa.allocator; var c = try Cpu.load(allocator, "input.txt"); defer c.deinit(); const last_acc = try c.runUntilRepeat(); const fix_acc = try c.fixOpcode(); const stdout = io.getStdOut().writer(); try stdout.print("Part 1: {d}\n", .{last_acc}); try stdout.print("Part 2: {d}\n", .{fix_acc}); } const Operation = enum { nop, acc, jmp }; const Instruction = struct { op: Operation, arg: i16, pub fn parse(str: []const u8) !Instruction { const s = str[0..3]; const i = if (std.mem.eql(u8, s, "acc")) Operation.acc else if (std.mem.eql(u8, s, "jmp")) Operation.jmp else if (std.mem.eql(u8, s, "nop")) Operation.nop else unreachable; const a = try std.fmt.parseInt(i16, str[4..], 10); return Instruction{ .op = i, .arg = a }; } }; const CpuError = error{ InvalidInstruction, RepeatedInstruction }; const Cpu = struct { ip: u16 = 0, acc: i16 = 0, prog: []Instruction, flip_op: ?u16 = null, allocator: *Allocator, pub fn load(allocator: *Allocator, path: []const u8) !Cpu { var file = try std.fs.cwd().openFile(path, .{}); defer file.close(); var list = std.ArrayList(Instruction).init(allocator); defer list.deinit(); var buf_reader = io.bufferedReader(file.reader()); var in_stream = buf_reader.reader(); var buf: [256]u8 = undefined; while (try in_stream.readUntilDelimiterOrEof(&buf, '\n')) |line| { const inst = try Instruction.parse(line); try list.append(inst); } return Cpu{ .allocator = allocator, .prog = list.toOwnedSlice() }; } pub fn deinit(self: *const Cpu) void { self.allocator.free(self.prog); } pub fn step(self: *Cpu) !bool { if (self.ip == self.prog.len) { return true; } if (self.ip > self.prog.len) { return CpuError.InvalidInstruction; } var op = self.prog[self.ip].op; if (self.flip_op) |flip_idx| { if (flip_idx == self.ip) { op = switch (op) { Operation.nop => Operation.jmp, Operation.jmp => Operation.nop, Operation.acc => Operation.acc, }; } } switch (op) { .nop => self.ip += 1, .acc => { self.acc += self.prog[self.ip].arg; self.ip += 1; }, .jmp => { var new_ip: i16 = @intCast(i16, self.ip) + self.prog[self.ip].arg; self.ip = @intCast(u16, new_ip); }, } return false; } pub fn run(self: *Cpu) !void { var done: bool = false; while (!done) { done = try self.step(); } } pub fn runUntilRepeat(self: *Cpu) !i16 { var last_acc: i16 = 0; var map = std.AutoHashMap(u16, bool).init(self.allocator); defer map.deinit(); var done: bool = false; while (!done) { if (map.contains(self.ip)) { return last_acc; } try map.put(self.ip, true); last_acc = self.acc; done = try self.step(); } return last_acc; } pub fn fixOpcodeRun(self: *Cpu) !i16 { self.acc = 0; self.ip = 0; var last_acc: i16 = 0; var map = std.AutoHashMap(u16, bool).init(self.allocator); defer map.deinit(); var done: bool = false; while (!done) { if (map.contains(self.ip)) { return CpuError.RepeatedInstruction; } try map.put(self.ip, true); last_acc = self.acc; done = try self.step(); } return last_acc; } pub fn fixOpcode(self: *Cpu) !i16 { var i: u16 = 0; while (i < self.prog.len) : (i += 1) { if (Operation.acc == self.prog[i].op) continue; self.flip_op = i; return self.fixOpcodeRun() catch continue; } unreachable; } }; test "basic behavior" { var n = try Cpu.load(test_allocator, "nop.txt"); defer n.deinit(); try n.run(); try expect(0 == n.acc); var a = try Cpu.load(test_allocator, "acc.txt"); defer a.deinit(); try a.run(); try expect(-3 == a.acc); var t = try Cpu.load(test_allocator, "test.txt"); defer t.deinit(); const last_acc = try t.runUntilRepeat(); try expect(5 == last_acc); } test "op fix" { var t = try Cpu.load(test_allocator, "test.txt"); defer t.deinit(); const last_acc = try t.fixOpcode(); try expect(8 == last_acc); }
day08/src/main.zig
// x86 I/O Port Access ======================================================== pub fn out8(port: u16, val: u8) void { asm volatile ("outb %[val], %[port]" : : [val] "{al}" (val), [port] "N{dx}" (port)); } pub fn out16(port: u16, val: u16) void { asm volatile ("outw %[val], %[port]" : : [val] "{al}" (val), [port] "N{dx}" (port)); } pub fn out32(port: u16, val: u32) void { asm volatile ("outl %[val], %[port]" : : [val] "{al}" (val), [port] "N{dx}" (port)); } pub fn in8(port: u16) u8 { return asm volatile ("inb %[port], %[rv]" : [rv] "={al}" (-> u8) : [port] "N{dx}" (port) ); } pub fn in16(port: u16) u16 { return asm volatile ("inw %[port], %[rv]" : [rv] "={al}" (-> u16) : [port] "N{dx}" (port) ); } pub fn in32(port: u16) u32 { return asm volatile ("inl %[port], %[rv]" : [rv] "={al}" (-> u32) : [port] "N{dx}" (port) ); } pub fn out(comptime Type: type, port: u16, val: Type) void { switch (Type) { u8 => out8(port, val), u16 => out16(port, val), u32 => out32(port, val), else => @compileError("Invalid Type: " ++ @typeName(Type)), } } pub fn in(comptime Type: type, port: u16) Type { return switch (Type) { u8 => in8(port), u16 => in16(port), u32 => in32(port), else => @compileError("Invalid Type: " ++ @typeName(Type)), }; } /// Copy a series of bytes into destination, like using in8 over the slice. /// /// https://c9x.me/x86/html/file_module_x86_id_141.html pub fn in_bytes(port: u16, destination: []u8) void { asm volatile ("rep insw" : : [port] "{dx}" (port), [dest_ptr] "{di}" (@truncate(u32, @ptrToInt(destination.ptr))), [dest_size] "{ecx}" (@truncate(u32, destination.len) >> 1) : "memory"); } // Mask/Unmask Interrupts ===================================================== pub fn enable_interrupts() void { asm volatile ("sti"); } pub fn disable_interrupts() void { asm volatile ("cli"); } // Halt ======================================================================= pub fn halt() void { asm volatile ("hlt"); } pub fn idle() noreturn { while (true) { enable_interrupts(); halt(); } unreachable; } pub fn done() noreturn { disable_interrupts(); while (true) { halt(); } unreachable; } // x86 Control Registers ====================================================== /// Page Fault Address pub fn cr2() u32 { return asm volatile ("mov %%cr2, %[rv]" : [rv] "={eax}" (-> u32)); }
kernel/platform/util.zig
const std = @import("std"); const math = std.math; const init_jk = [_]i32{ 3, 4, 4, 6 }; // initial value for jk /// /// Table of constants for 2/pi, 396 Hex digits (476 decimal) of 2/pi /// /// integer array, contains the (24*i)-th to (24*i+23)-th /// bit of 2/pi after binary point. The corresponding /// floating value is /// /// ipio2[i] * 2^(-24(i+1)). /// /// NB: This table must have at least (e0-3)/24 + jk terms. /// For quad precision (e0 <= 16360, jk = 6), this is 686. const ipio2 = [_]i32{ 0xA2F983, 0x6E4E44, 0x1529FC, 0x2757D1, 0xF534DD, 0xC0DB62, 0x95993C, 0x439041, 0xFE5163, 0xABDEBB, 0xC561B7, 0x246E3A, 0x424DD2, 0xE00649, 0x2EEA09, 0xD1921C, 0xFE1DEB, 0x1CB129, 0xA73EE8, 0x8235F5, 0x2EBB44, 0x84E99C, 0x7026B4, 0x5F7E41, 0x3991D6, 0x398353, 0x39F49C, 0x845F8B, 0xBDF928, 0x3B1FF8, 0x97FFDE, 0x05980F, 0xEF2F11, 0x8B5A0A, 0x6D1F6D, 0x367ECF, 0x27CB09, 0xB74F46, 0x3F669E, 0x5FEA2D, 0x7527BA, 0xC7EBE5, 0xF17B3D, 0x0739F7, 0x8A5292, 0xEA6BFB, 0x5FB11F, 0x8D5D08, 0x560330, 0x46FC7B, 0x6BABF0, 0xCFBC20, 0x9AF436, 0x1DA9E3, 0x91615E, 0xE61B08, 0x659985, 0x5F14A0, 0x68408D, 0xFFD880, 0x4D7327, 0x310606, 0x1556CA, 0x73A8C9, 0x60E27B, 0xC08C6B, 0x47C419, 0xC367CD, 0xDCE809, 0x2A8359, 0xC4768B, 0x961CA6, 0xDDAF44, 0xD15719, 0x053EA5, 0xFF0705, 0x3F7E33, 0xE832C2, 0xDE4F98, 0x327DBB, 0xC33D26, 0xEF6B1E, 0x5EF89F, 0x3A1F35, 0xCAF27F, 0x1D87F1, 0x21907C, 0x7C246A, 0xFA6ED5, 0x772D30, 0x433B15, 0xC614B5, 0x9D19C3, 0xC2C4AD, 0x414D2C, 0x5D000C, 0x467D86, 0x2D71E3, 0x9AC69B, 0x006233, 0x7CD2B4, 0x97A7B4, 0xD55537, 0xF63ED7, 0x1810A3, 0xFC764D, 0x2A9D64, 0xABD770, 0xF87C63, 0x57B07A, 0xE71517, 0x5649C0, 0xD9D63B, 0x3884A7, 0xCB2324, 0x778AD6, 0x23545A, 0xB91F00, 0x1B0AF1, 0xDFCE19, 0xFF319F, 0x6A1E66, 0x615799, 0x47FBAC, 0xD87F7E, 0xB76522, 0x89E832, 0x60BFE6, 0xCDC4EF, 0x09366C, 0xD43F5D, 0xD7DE16, 0xDE3B58, 0x929BDE, 0x2822D2, 0xE88628, 0x4D58E2, 0x32CAC6, 0x16E308, 0xCB7DE0, 0x50C017, 0xA71DF3, 0x5BE018, 0x34132E, 0x621283, 0x014883, 0x5B8EF5, 0x7FB0AD, 0xF2E91E, 0x434A48, 0xD36710, 0xD8DDAA, 0x425FAE, 0xCE616A, 0xA4280A, 0xB499D3, 0xF2A606, 0x7F775C, 0x83C2A3, 0x883C61, 0x78738A, 0x5A8CAF, 0xBDD76F, 0x63A62D, 0xCBBFF4, 0xEF818D, 0x67C126, 0x45CA55, 0x36D9CA, 0xD2A828, 0x8D61C2, 0x77C912, 0x142604, 0x9B4612, 0xC459C4, 0x44C5C8, 0x91B24D, 0xF31700, 0xAD43D4, 0xE54929, 0x10D5FD, 0xFCBE00, 0xCC941E, 0xEECE70, 0xF53E13, 0x80F1EC, 0xC3E7B3, 0x28F8C7, 0x940593, 0x3E71C1, 0xB3092E, 0xF3450B, 0x9C1288, 0x7B20AB, 0x9FB52E, 0xC29247, 0x2F327B, 0x6D550C, 0x90A772, 0x1FE76B, 0x96CB31, 0x4A1679, 0xE27941, 0x89DFF4, 0x9794E8, 0x84E6E2, 0x973199, 0x6BED88, 0x365F5F, 0x0EFDBB, 0xB49A48, 0x6CA467, 0x427271, 0x325D8D, 0xB8159F, 0x09E5BC, 0x25318D, 0x3974F7, 0x1C0530, 0x010C0D, 0x68084B, 0x58EE2C, 0x90AA47, 0x02E774, 0x24D6BD, 0xA67DF7, 0x72486E, 0xEF169F, 0xA6948E, 0xF691B4, 0x5153D1, 0xF20ACF, 0x339820, 0x7E4BF5, 0x6863B2, 0x5F3EDD, 0x035D40, 0x7F8985, 0x295255, 0xC06437, 0x10D86D, 0x324832, 0x754C5B, 0xD4714E, 0x6E5445, 0xC1090B, 0x69F52A, 0xD56614, 0x9D0727, 0x50045D, 0xDB3BB4, 0xC576EA, 0x17F987, 0x7D6B49, 0xBA271D, 0x296996, 0xACCCC6, 0x5414AD, 0x6AE290, 0x89D988, 0x50722C, 0xBEA404, 0x940777, 0x7030F3, 0x27FC00, 0xA871EA, 0x49C266, 0x3DE064, 0x83DD97, 0x973FA3, 0xFD9443, 0x8C860D, 0xDE4131, 0x9D3992, 0x8C70DD, 0xE7B717, 0x3BDF08, 0x2B3715, 0xA0805C, 0x93805A, 0x921110, 0xD8E80F, 0xAF806C, 0x4BFFDB, 0x0F9038, 0x761859, 0x15A562, 0xBBCB61, 0xB989C7, 0xBD4010, 0x04F2D2, 0x277549, 0xF6B6EB, 0xBB22DB, 0xAA140A, 0x2F2689, 0x768364, 0x333B09, 0x1A940E, 0xAA3A51, 0xC2A31D, 0xAEEDAF, 0x12265C, 0x4DC26D, 0x9C7A2D, 0x9756C0, 0x833F03, 0xF6F009, 0x8C402B, 0x99316D, 0x07B439, 0x15200C, 0x5BC3D8, 0xC492F5, 0x4BADC6, 0xA5CA4E, 0xCD37A7, 0x36A9E6, 0x9492AB, 0x6842DD, 0xDE6319, 0xEF8C76, 0x528B68, 0x37DBFC, 0xABA1AE, 0x3115DF, 0xA1AE00, 0xDAFB0C, 0x664D64, 0xB705ED, 0x306529, 0xBF5657, 0x3AFF47, 0xB9F96A, 0xF3BE75, 0xDF9328, 0x3080AB, 0xF68C66, 0x15CB04, 0x0622FA, 0x1DE4D9, 0xA4B33D, 0x8F1B57, 0x09CD36, 0xE9424E, 0xA4BE13, 0xB52333, 0x1AAAF0, 0xA8654F, 0xA5C1D2, 0x0F3F0B, 0xCD785B, 0x76F923, 0x048B7B, 0x721789, 0x53A6C6, 0xE26E6F, 0x00EBEF, 0x584A9B, 0xB7DAC4, 0xBA66AA, 0xCFCF76, 0x1D02D1, 0x2DF1B1, 0xC1998C, 0x77ADC3, 0xDA4886, 0xA05DF7, 0xF480C6, 0x2FF0AC, 0x9AECDD, 0xBC5C3F, 0x6DDED0, 0x1FC790, 0xB6DB2A, 0x3A25A3, 0x9AAF00, 0x9353AD, 0x0457B6, 0xB42D29, 0x7E804B, 0xA707DA, 0x0EAA76, 0xA1597B, 0x2A1216, 0x2DB7DC, 0xFDE5FA, 0xFEDB89, 0xFDBE89, 0x6C76E4, 0xFCA906, 0x70803E, 0x156E85, 0xFF87FD, 0x073E28, 0x336761, 0x86182A, 0xEABD4D, 0xAFE7B3, 0x6E6D8F, 0x396795, 0x5BBF31, 0x48D784, 0x16DF30, 0x432DC7, 0x356125, 0xCE70C9, 0xB8CB30, 0xFD6CBF, 0xA200A4, 0xE46C05, 0xA0DD5A, 0x476F21, 0xD21262, 0x845CB9, 0x496170, 0xE0566B, 0x015299, 0x375550, 0xB7D51E, 0xC4F133, 0x5F6E13, 0xE4305D, 0xA92E85, 0xC3B21D, 0x3632A1, 0xA4B708, 0xD4B1EA, 0x21F716, 0xE4698F, 0x77FF27, 0x80030C, 0x2D408D, 0xA0CD4F, 0x99A520, 0xD3A2B3, 0x0A5D2F, 0x42F9B4, 0xCBDA11, 0xD0BE7D, 0xC1DB9B, 0xBD17AB, 0x81A2CA, 0x5C6A08, 0x17552E, 0x550027, 0xF0147F, 0x8607E1, 0x640B14, 0x8D4196, 0xDEBE87, 0x2AFDDA, 0xB6256B, 0x34897B, 0xFEF305, 0x9EBFB9, 0x4F6A68, 0xA82A4A, 0x5AC44F, 0xBCF82D, 0x985AD7, 0x95C7F4, 0x8D4D0D, 0xA63A20, 0x5F57A4, 0xB13F14, 0x953880, 0x0120CC, 0x86DD71, 0xB6DEC9, 0xF560BF, 0x11654D, 0x6B0701, 0xACB08C, 0xD0C0B2, 0x485551, 0x0EFB1E, 0xC37295, 0x3B06A3, 0x3540C0, 0x7BDC06, 0xCC45E0, 0xFA294E, 0xC8CAD6, 0x41F3E8, 0xDE647C, 0xD8649B, 0x31BED9, 0xC397A4, 0xD45877, 0xC5E369, 0x13DAF0, 0x3C3ABA, 0x461846, 0x5F7555, 0xF5BDD2, 0xC6926E, 0x5D2EAC, 0xED440E, 0x423E1C, 0x87C461, 0xE9FD29, 0xF3D6E7, 0xCA7C22, 0x35916F, 0xC5E008, 0x8DD7FF, 0xE26A6E, 0xC6FDB0, 0xC10893, 0x745D7C, 0xB2AD6B, 0x9D6ECD, 0x7B723E, 0x6A11C6, 0xA9CFF7, 0xDF7329, 0xBAC9B5, 0x5100B7, 0x0DB2E2, 0x24BA74, 0x607DE5, 0x8AD874, 0x2C150D, 0x0C1881, 0x94667E, 0x162901, 0x767A9F, 0xBEFDFD, 0xEF4556, 0x367ED9, 0x13D9EC, 0xB9BA8B, 0xFC97C4, 0x27A831, 0xC36EF1, 0x36C594, 0x56A8D8, 0xB5A8B4, 0x0ECCCF, 0x2D8912, 0x34576F, 0x89562C, 0xE3CE99, 0xB920D6, 0xAA5E6B, 0x9C2A3E, 0xCC5F11, 0x4A0BFD, 0xFBF4E1, 0x6D3B8E, 0x2C86E2, 0x84D4E9, 0xA9B4FC, 0xD1EEEF, 0xC9352E, 0x61392F, 0x442138, 0xC8D91B, 0x0AFC81, 0x6A4AFB, 0xD81C2F, 0x84B453, 0x8C994E, 0xCC2254, 0xDC552A, 0xD6C6C0, 0x96190B, 0xB8701A, 0x649569, 0x605A26, 0xEE523F, 0x0F117F, 0x11B5F4, 0xF5CBFC, 0x2DBC34, 0xEEBC34, 0xCC5DE8, 0x605EDD, 0x9B8E67, 0xEF3392, 0xB817C9, 0x9B5861, 0xBC57E1, 0xC68351, 0x103ED8, 0x4871DD, 0xDD1C2D, 0xA118AF, 0x462C21, 0xD7F359, 0x987AD9, 0xC0549E, 0xFA864F, 0xFC0656, 0xAE79E5, 0x362289, 0x22AD38, 0xDC9367, 0xAAE855, 0x382682, 0x9BE7CA, 0xA40D51, 0xB13399, 0x0ED7A9, 0x480569, 0xF0B265, 0xA7887F, 0x974C88, 0x36D1F9, 0xB39221, 0x4A827B, 0x21CF98, 0xDC9F40, 0x5547DC, 0x3A74E1, 0x42EB67, 0xDF9DFE, 0x5FD45E, 0xA4677B, 0x7AACBA, 0xA2F655, 0x23882B, 0x55BA41, 0x086E59, 0x862A21, 0x834739, 0xE6E389, 0xD49EE5, 0x40FB49, 0xE956FF, 0xCA0F1C, 0x8A59C5, 0x2BFA94, 0xC5C1D3, 0xCFC50F, 0xAE5ADB, 0x86C547, 0x624385, 0x3B8621, 0x94792C, 0x876110, 0x7B4C2A, 0x1A2C80, 0x12BF43, 0x902688, 0x893C78, 0xE4C4A8, 0x7BDBE5, 0xC23AC4, 0xEAF426, 0x8A67F7, 0xBF920D, 0x2BA365, 0xB1933D, 0x0B7CBD, 0xDC51A4, 0x63DD27, 0xDDE169, 0x19949A, 0x9529A8, 0x28CE68, 0xB4ED09, 0x209F44, 0xCA984E, 0x638270, 0x237C7E, 0x32B90F, 0x8EF5A7, 0xE75614, 0x08F121, 0x2A9DB5, 0x4D7E6F, 0x5119A5, 0xABF9B5, 0xD6DF82, 0x61DD96, 0x023616, 0x9F3AC4, 0xA1A283, 0x6DED72, 0x7A8D39, 0xA9B882, 0x5C326B, 0x5B2746, 0xED3400, 0x7700D2, 0x55F4FC, 0x4D5901, 0x8071E0, }; const PIo2 = [_]f64{ 1.57079625129699707031e+00, // 0x3FF921FB, 0x40000000 7.54978941586159635335e-08, // 0x3E74442D, 0x00000000 5.39030252995776476554e-15, // 0x3CF84698, 0x80000000 3.28200341580791294123e-22, // 0x3B78CC51, 0x60000000 1.27065575308067607349e-29, // 0x39F01B83, 0x80000000 1.22933308981111328932e-36, // 0x387A2520, 0x40000000 2.73370053816464559624e-44, // 0x36E38222, 0x80000000 2.16741683877804819444e-51, // 0x3569F31D, 0x00000000 }; fn U(x: anytype) usize { return @intCast(usize, x); } /// Returns the last three digits of N with y = x - N*pi/2 so that |y| < pi/2. /// /// The method is to compute the integer (mod 8) and fraction parts of /// (2/pi)*x without doing the full multiplication. In general we /// skip the part of the product that are known to be a huge integer ( /// more accurately, = 0 mod 8 ). Thus the number of operations are /// independent of the exponent of the input. /// /// (2/pi) is represented by an array of 24-bit integers in ipio2[]. /// /// Input parameters: /// x[] The input value (must be positive) is broken into nx /// pieces of 24-bit integers in double precision format. /// x[i] will be the i-th 24 bit of x. The scaled exponent /// of x[0] is given in input parameter e0 (i.e., x[0]*2^e0 /// match x's up to 24 bits. /// /// Example of breaking a double positive z into x[0]+x[1]+x[2]: /// e0 = ilogb(z)-23 /// z = scalbn(z,-e0) /// for i = 0,1,2 /// x[i] = floor(z) /// z = (z-x[i])*2**24 /// /// /// y[] ouput result in an array of double precision numbers. /// The dimension of y[] is: /// 24-bit precision 1 /// 53-bit precision 2 /// 64-bit precision 2 /// 113-bit precision 3 /// The actual value is the sum of them. Thus for 113-bit /// precison, one may have to do something like: /// /// long double t,w,r_head, r_tail; /// t = (long double)y[2] + (long double)y[1]; /// w = (long double)y[0]; /// r_head = t+w; /// r_tail = w - (r_head - t); /// /// e0 The exponent of x[0]. Must be <= 16360 or you need to /// expand the ipio2 table. /// /// nx dimension of x[] /// /// prec an integer indicating the precision: /// 0 24 bits (single) /// 1 53 bits (double) /// 2 64 bits (extended) /// 3 113 bits (quad) /// /// Here is the description of some local variables: /// /// jk jk+1 is the initial number of terms of ipio2[] needed /// in the computation. The minimum and recommended value /// for jk is 3,4,4,6 for single, double, extended, and quad. /// jk+1 must be 2 larger than you might expect so that our /// recomputation test works. (Up to 24 bits in the integer /// part (the 24 bits of it that we compute) and 23 bits in /// the fraction part may be lost to cancelation before we /// recompute.) /// /// jz local integer variable indicating the number of /// terms of ipio2[] used. /// /// jx nx - 1 /// /// jv index for pointing to the suitable ipio2[] for the /// computation. In general, we want /// ( 2^e0*x[0] * ipio2[jv-1]*2^(-24jv) )/8 /// is an integer. Thus /// e0-3-24*jv >= 0 or (e0-3)/24 >= jv /// Hence jv = max(0,(e0-3)/24). /// /// jp jp+1 is the number of terms in PIo2[] needed, jp = jk. /// /// q[] double array with integral value, representing the /// 24-bits chunk of the product of x and 2/pi. /// /// q0 the corresponding exponent of q[0]. Note that the /// exponent for q[i] would be q0-24*i. /// /// PIo2[] double precision array, obtained by cutting pi/2 /// into 24 bits chunks. /// /// f[] ipio2[] in floating point /// /// iq[] integer array by breaking up q[] in 24-bits chunk. /// /// fq[] final product of x*(2/pi) in fq[0],..,fq[jk] /// /// ih integer. If >0 it indicates q[] is >= 0.5, hence /// it also indicates the *sign* of the result. /// /// /// /// Constants: /// The hexadecimal values are the intended ones for the following /// constants. The decimal values may be used, provided that the /// compiler will convert from decimal to binary accurately enough /// to produce the hexadecimal values shown. /// pub fn rem_pio2_large(x: []f64, y: []f64, e0: i32, nx: i32, prec: usize) i32 { var jz: i32 = undefined; var jx: i32 = undefined; var jv: i32 = undefined; var jp: i32 = undefined; var jk: i32 = undefined; var carry: i32 = undefined; var n: i32 = undefined; var iq: [20]i32 = undefined; var i: i32 = undefined; var j: i32 = undefined; var k: i32 = undefined; var m: i32 = undefined; var q0: i32 = undefined; var ih: i32 = undefined; var z: f64 = undefined; var fw: f64 = undefined; var f: [20]f64 = undefined; var fq: [20]f64 = undefined; var q: [20]f64 = undefined; // initialize jk jk = init_jk[prec]; jp = jk; // determine jx,jv,q0, note that 3>q0 jx = nx - 1; jv = @divFloor(e0 - 3, 24); if (jv < 0) jv = 0; q0 = e0 - 24 * (jv + 1); // set up f[0] to f[jx+jk] where f[jx+jk] = ipio2[jv+jk] j = jv - jx; m = jx + jk; i = 0; while (i <= m) : ({ i += 1; j += 1; }) { f[U(i)] = if (j < 0) 0.0 else @intToFloat(f64, ipio2[U(j)]); } // compute q[0],q[1],...q[jk] i = 0; while (i <= jk) : (i += 1) { j = 0; fw = 0; while (j <= jx) : (j += 1) { fw += x[U(j)] * f[U(jx + i - j)]; } q[U(i)] = fw; } jz = jk; // This is to handle a non-trivial goto translation from C. // An unconditional return statement is found at the end of this loop. recompute: while (true) { // distill q[] into iq[] reversingly i = 0; j = jz; z = q[U(jz)]; while (j > 0) : ({ i += 1; j -= 1; }) { fw = @intToFloat(f64, @floatToInt(i32, 0x1p-24 * z)); iq[U(i)] = @floatToInt(i32, z - 0x1p24 * fw); z = q[U(j - 1)] + fw; } // compute n z = math.scalbn(z, q0); // actual value of z z -= 8.0 * @floor(z * 0.125); // trim off integer >= 8 n = @floatToInt(i32, z); z -= @intToFloat(f64, n); ih = 0; if (q0 > 0) { // need iq[jz-1] to determine n i = iq[U(jz - 1)] >> @intCast(u5, 24 - q0); n += i; iq[U(jz - 1)] -= i << @intCast(u5, 24 - q0); ih = iq[U(jz - 1)] >> @intCast(u5, 23 - q0); } else if (q0 == 0) { ih = iq[U(jz - 1)] >> 23; } else if (z >= 0.5) { ih = 2; } if (ih > 0) { // q > 0.5 n += 1; carry = 0; i = 0; while (i < jz) : (i += 1) { // compute 1-q j = iq[U(i)]; if (carry == 0) { if (j != 0) { carry = 1; iq[U(i)] = 0x1000000 - j; } } else { iq[U(i)] = 0xffffff - j; } } if (q0 > 0) { // rare case: chance is 1 in 12 switch (q0) { 1 => iq[U(jz - 1)] &= 0x7fffff, 2 => iq[U(jz - 1)] &= 0x3fffff, else => unreachable, } } if (ih == 2) { z = 1.0 - z; if (carry != 0) { z -= math.scalbn(@as(f64, 1.0), q0); } } } // check if recomputation is needed if (z == 0.0) { j = 0; i = jz - 1; while (i >= jk) : (i -= 1) { j |= iq[U(i)]; } if (j == 0) { // need recomputation k = 1; while (iq[U(jk - k)] == 0) : (k += 1) { // k = no. of terms needed } i = jz + 1; while (i <= jz + k) : (i += 1) { // add q[jz+1] to q[jz+k] f[U(jx + i)] = @intToFloat(f64, ipio2[U(jv + i)]); j = 0; fw = 0; while (j <= jx) : (j += 1) { fw += x[U(j)] * f[U(jx + i - j)]; } q[U(i)] = fw; } jz += k; continue :recompute; // mimic goto recompute } } // chop off zero terms if (z == 0.0) { jz -= 1; q0 -= 24; while (iq[U(jz)] == 0) { jz -= 1; q0 -= 24; } } else { // break z into 24-bit if necessary z = math.scalbn(z, -q0); if (z >= 0x1p24) { fw = @intToFloat(f64, @floatToInt(i32, 0x1p-24 * z)); iq[U(jz)] = @floatToInt(i32, z - 0x1p24 * fw); jz += 1; q0 += 24; iq[U(jz)] = @floatToInt(i32, fw); } else { iq[U(jz)] = @floatToInt(i32, z); } } // convert integer "bit" chunk to floating-point value fw = math.scalbn(@as(f64, 1.0), q0); i = jz; while (i >= 0) : (i -= 1) { q[U(i)] = fw * @intToFloat(f64, iq[U(i)]); fw *= 0x1p-24; } // compute PIo2[0,...,jp]*q[jz,...,0] i = jz; while (i >= 0) : (i -= 1) { fw = 0; k = 0; while (k <= jp and k <= jz - i) : (k += 1) { fw += PIo2[U(k)] * q[U(i + k)]; } fq[U(jz - i)] = fw; } // compress fq[] into y[] switch (prec) { 0 => { fw = 0.0; i = jz; while (i >= 0) : (i -= 1) { fw += fq[U(i)]; } y[0] = if (ih == 0) fw else -fw; }, 1, 2 => { fw = 0.0; i = jz; while (i >= 0) : (i -= 1) { fw += fq[U(i)]; } // TODO: drop excess precision here once double_t is used fw = fw; y[0] = if (ih == 0) fw else -fw; fw = fq[0] - fw; i = 1; while (i <= jz) : (i += 1) { fw += fq[U(i)]; } y[1] = if (ih == 0) fw else -fw; }, 3 => { // painful i = jz; while (i > 0) : (i -= 1) { fw = fq[U(i - 1)] + fq[U(i)]; fq[U(i)] += fq[U(i - 1)] - fw; fq[U(i - 1)] = fw; } i = jz; while (i > 1) : (i -= 1) { fw = fq[U(i - 1)] + fq[U(i)]; fq[U(i)] += fq[U(i - 1)] - fw; fq[U(i - 1)] = fw; } fw = 0; i = jz; while (i >= 2) : (i -= 1) { fw += fq[U(i)]; } if (ih == 0) { y[0] = fq[0]; y[1] = fq[1]; y[2] = fw; } else { y[0] = -fq[0]; y[1] = -fq[1]; y[2] = -fw; } }, else => unreachable, } return n & 7; } }
lib/compiler_rt/rem_pio2_large.zig
const std = @import("std"); const zzz = @import("zzz"); pub const Config = struct { allocator: *std.mem.Allocator, raw: []u8, bind: []const u8, port: u16, vhosts: std.StringHashMap(VHost), // Only used in evented mode. client_timeout_seconds: u32 = 10, max_concurrent_clients: usize = 128, pub const VHost = struct { root: []const u8, index: []const u8, fn init(node: *const zzz.ZNode) !VHost { var root: ?[]const u8 = null; var index: ?[]const u8 = null; var maybe_child = node.nextChild(null); while (maybe_child) |child| : (maybe_child = node.nextChild(child)) { if (child.value != .String) return error.BadConfigUnknownVHostNodeType; if (std.mem.eql(u8, child.value.String, "root")) { root = try extractSingleChildString(child); } else if (std.mem.eql(u8, child.value.String, "index")) { index = try extractSingleChildString(child); } else { return error.BadConfigUnknownVHostChild; } } return VHost{ .root = root orelse return error.BadConfigVHostMissingRoot, .index = index orelse "index.gmi", }; } }; // Takes ownership of `raw'; will free it with `allocator' unless this returns an error. // Further uses `allocator' internally. pub fn init(allocator: *std.mem.Allocator, raw: []u8) !Config { var vhosts = std.StringHashMap(VHost).init(allocator); errdefer vhosts.deinit(); var bind: ?[]const u8 = null; var port: ?u16 = null; var tree = zzz.ZTree(1, 100){}; var root = try tree.appendText(raw); var maybe_node = root.nextChild(null); while (maybe_node) |node| : (maybe_node = root.nextChild(node)) { switch (node.value) { .String => |key| { if (std.mem.eql(u8, key, "bind")) { bind = try extractSingleChildString(node); } else if (std.mem.eql(u8, key, "port")) { port = try std.fmt.parseUnsigned(u16, try extractSingleChildString(node), 10); } else { try vhosts.put(key, try VHost.init(node)); } }, else => return error.BadConfigUnknownNodeType, } } return Config{ .allocator = allocator, .raw = raw, .bind = bind orelse "127.0.0.1", .port = port orelse 4003, .vhosts = vhosts, }; } pub fn deinit(self: *Config) void { self.vhosts.deinit(); self.allocator.free(self.raw); } }; fn extractSingleChildString(node: *const zzz.ZNode) ![]const u8 { var child = node.nextChild(null) orelse return error.BadConfigMissingChild; if (child.value != .String) return error.BadConfigUnknownChildType; if (node.nextChild(child) != null) return error.BadConfigMultipleChildren; return child.value.String; }
src/config.zig
const std = @import("std"); test "examples" { const examples = .{ .{ .input = @embedFile("12_example_1.txt"), .answer = 10 }, .{ .input = @embedFile("12_example_2.txt"), .answer = 19 }, .{ .input = @embedFile("12_example_3.txt"), .answer = 226 }, }; inline for (examples) |example| { const result = try run(example.input); try std.testing.expectEqual(@as(usize, example.answer), result); } } pub fn main() !void { const input = @embedFile("12.txt"); const result = try run(input); std.debug.print("{}\n", .{result}); } const Map = struct { caves: Caves, edges: Edges, const Caves = std.BoundedArray([]const u8, 64); const Visited = std.StaticBitSet(64); const Edges = std.BoundedArray([2]usize, 32); const start = 0; const end = 1; fn init() !Map { var map = Map{ .caves = try Caves.fromSlice(&.{ "start", "end" }), .edges = try Edges.init(0), }; return map; } fn getOrInsertCave(self: *Map, cave: []const u8) !usize { for (self.caves.constSlice()) |c, i| { if (std.mem.eql(u8, c, cave)) return i; } else { try self.caves.append(cave); return self.caves.len - 1; } } fn insert(self: *Map, from: []const u8, to: []const u8) !void { const from_idx = try self.getOrInsertCave(from); const to_idx = try self.getOrInsertCave(to); try self.edges.append(.{ from_idx, to_idx }); } inline fn isSmall(self: *const Map, idx: usize) bool { if (idx == start or idx == end) return true; const name = self.caves.get(idx); return (name[0] >= 'a' and name[0] <= 'z'); } fn edgesOf(self: Map, needle: usize) EdgeIterator { return .{ .index = 0, .needle = needle, .edges = self.edges.constSlice(), }; } const EdgeIterator = struct { index: usize, needle: usize, edges: []const [2]usize, fn next(self: *@This()) ?usize { while (self.index < self.edges.len) { const current = self.edges[self.index]; self.index += 1; if (current[0] == self.needle) return current[1]; if (current[1] == self.needle) return current[0]; } else return null; } }; fn countPaths(self: Map) usize { var visited = Visited.initEmpty(); var count: usize = 0; self.visit(&visited, &count, start); return count; } fn visit(self: Map, visited: *Visited, count: *usize, current: usize) void { if (current == end) { count.* += 1; return; } visited.set(current); var edges = self.edgesOf(current); while (edges.next()) |e| { if (self.isSmall(e) and visited.isSet(e)) continue; self.visit(visited, count, e); } visited.unset(current); } }; fn run(input: []const u8) !usize { var map = try Map.init(); var lines = std.mem.split(u8, input, "\n"); while (lines.next()) |line| { const middle = std.mem.indexOfScalar(u8, line, '-').?; try map.insert(line[0..middle], line[middle + 1 ..]); } return map.countPaths(); }
shritesh+zig/12a.zig
const std = @import("std"); const assert = std.debug.assert; const c = @import("c.zig"); pub fn register_function( env: c.napi_env, exports: c.napi_value, comptime name: [:0]const u8, function: fn (env: c.napi_env, info: c.napi_callback_info) callconv(.C) c.napi_value, ) !void { var napi_function: c.napi_value = undefined; if (c.napi_create_function(env, null, 0, function, null, &napi_function) != .napi_ok) { return throw(env, "Failed to create function " ++ name ++ "()."); } if (c.napi_set_named_property(env, exports, name, napi_function) != .napi_ok) { return throw(env, "Failed to add " ++ name ++ "() to exports."); } } const TranslationError = error{ExceptionThrown}; pub fn throw(env: c.napi_env, comptime message: [:0]const u8) TranslationError { var result = c.napi_throw_error(env, null, message); switch (result) { .napi_ok, .napi_pending_exception => {}, else => unreachable, } return TranslationError.ExceptionThrown; } pub fn capture_undefined(env: c.napi_env) !c.napi_value { var result: c.napi_value = undefined; if (c.napi_get_undefined(env, &result) != .napi_ok) { return throw(env, "Failed to capture the value of \"undefined\"."); } return result; } pub fn set_instance_data( env: c.napi_env, data: *c_void, finalize_callback: fn (env: c.napi_env, data: ?*c_void, hint: ?*c_void) callconv(.C) void, ) !void { if (c.napi_set_instance_data(env, data, finalize_callback, null) != .napi_ok) { return throw(env, "Failed to initialize environment."); } } pub fn create_external(env: c.napi_env, context: *c_void) !c.napi_value { var result: c.napi_value = null; if (c.napi_create_external(env, context, null, null, &result) != .napi_ok) { return throw(env, "Failed to create external for client context."); } return result; } pub fn value_external( env: c.napi_env, value: c.napi_value, comptime error_message: [:0]const u8, ) !?*c_void { var result: ?*c_void = undefined; if (c.napi_get_value_external(env, value, &result) != .napi_ok) { return throw(env, error_message); } return result; } pub const UserData = packed struct { env: c.napi_env, callback_reference: c.napi_ref, }; /// This will create a reference in V8 with a ref_count of 1. /// This reference will be destroyed when we return the server response to JS. pub fn user_data_from_value(env: c.napi_env, value: c.napi_value) !UserData { var callback_type: c.napi_valuetype = undefined; if (c.napi_typeof(env, value, &callback_type) != .napi_ok) { return throw(env, "Failed to check callback type."); } if (callback_type != .napi_function) return throw(env, "Callback must be a Function."); var callback_reference: c.napi_ref = undefined; if (c.napi_create_reference(env, value, 1, &callback_reference) != .napi_ok) { return throw(env, "Failed to create reference to callback."); } return UserData{ .env = env, .callback_reference = callback_reference, }; } pub fn globals(env: c.napi_env) !?*c_void { var data: ?*c_void = null; if (c.napi_get_instance_data(env, &data) != .napi_ok) { return throw(env, "Failed to decode globals."); } return data; } pub fn slice_from_object( env: c.napi_env, object: c.napi_value, comptime key: [:0]const u8, ) ![]const u8 { var property: c.napi_value = undefined; if (c.napi_get_named_property(env, object, key, &property) != .napi_ok) { return throw(env, key ++ " must be defined"); } return slice_from_value(env, property, key); } pub fn slice_from_value( env: c.napi_env, value: c.napi_value, comptime key: [:0]const u8, ) ![]u8 { var is_buffer: bool = undefined; assert(c.napi_is_buffer(env, value, &is_buffer) == .napi_ok); if (!is_buffer) return throw(env, key ++ " must be a buffer"); var data: ?*c_void = null; var data_length: usize = undefined; assert(c.napi_get_buffer_info(env, value, &data, &data_length) == .napi_ok); if (data_length < 1) return throw(env, key ++ " must not be empty"); return @ptrCast([*]u8, data.?)[0..data_length]; } pub fn bytes_from_object( env: c.napi_env, object: c.napi_value, comptime length: u8, comptime key: [:0]const u8, ) ![length]u8 { var property: c.napi_value = undefined; if (c.napi_get_named_property(env, object, key, &property) != .napi_ok) { return throw(env, key ++ " must be defined"); } const data = try slice_from_value(env, property, key); if (data.len != length) { return throw(env, key ++ " has incorrect length."); } // Copy this out of V8 as the underlying data lifetime is not guaranteed. var result: [length]u8 = undefined; std.mem.copy(u8, result[0..], data[0..]); return result; } pub fn bytes_from_buffer( env: c.napi_env, buffer: c.napi_value, output: []u8, comptime key: [:0]const u8, ) !usize { const data = try slice_from_value(env, buffer, key); if (data.len < 1) { return throw(env, key ++ " must not be empty."); } if (data.len > output.len) { return throw(env, key ++ " exceeds max message size."); } // Copy this out of V8 as the underlying data lifetime is not guaranteed. std.mem.copy(u8, output[0..], data[0..]); return data.len; } pub fn u128_from_object(env: c.napi_env, object: c.napi_value, comptime key: [:0]const u8) !u128 { var property: c.napi_value = undefined; if (c.napi_get_named_property(env, object, key, &property) != .napi_ok) { return throw(env, key ++ " must be defined"); } return u128_from_value(env, property, key); } pub fn u64_from_object(env: c.napi_env, object: c.napi_value, comptime key: [:0]const u8) !u64 { var property: c.napi_value = undefined; if (c.napi_get_named_property(env, object, key, &property) != .napi_ok) { return throw(env, key ++ " must be defined"); } return u64_from_value(env, property, key); } pub fn u32_from_object(env: c.napi_env, object: c.napi_value, comptime key: [:0]const u8) !u32 { var property: c.napi_value = undefined; if (c.napi_get_named_property(env, object, key, &property) != .napi_ok) { return throw(env, key ++ " must be defined"); } return u32_from_value(env, property, key); } pub fn u16_from_object(env: c.napi_env, object: c.napi_value, comptime key: [:0]const u8) !u16 { const result = try u32_from_object(env, object, key); if (result > 65535) { return throw(env, key ++ " must be a u16."); } return @intCast(u16, result); } pub fn u128_from_value(env: c.napi_env, value: c.napi_value, comptime name: [:0]const u8) !u128 { // A BigInt's value (using ^ to mean exponent) is (words[0] * (2^64)^0 + words[1] * (2^64)^1 + ...) // V8 says that the words are little endian. If we were on a big endian machine // we would need to convert, but big endian is not supported by tigerbeetle. var result: u128 = 0; var sign_bit: c_int = undefined; const words = @ptrCast(*[2]u64, &result); var word_count: usize = 2; switch (c.napi_get_value_bigint_words(env, value, &sign_bit, &word_count, words)) { .napi_ok => {}, .napi_bigint_expected => return throw(env, name ++ " must be a BigInt"), else => unreachable, } if (sign_bit != 0) return throw(env, name ++ " must be positive"); if (word_count > 2) return throw(env, name ++ " must fit in 128 bits"); return result; } pub fn u64_from_value(env: c.napi_env, value: c.napi_value, comptime name: [:0]const u8) !u64 { var result: u64 = undefined; var lossless: bool = undefined; switch (c.napi_get_value_bigint_uint64(env, value, &result, &lossless)) { .napi_ok => {}, .napi_bigint_expected => return throw(env, name ++ " must be an unsigned 64-bit BigInt"), else => unreachable, } if (!lossless) return throw(env, name ++ " conversion was lossy"); return result; } pub fn u32_from_value(env: c.napi_env, value: c.napi_value, comptime name: [:0]const u8) !u32 { var result: u32 = undefined; // TODO Check whether this will coerce signed numbers to a u32: // In that case we need to use the appropriate napi method to do more type checking here. // We want to make sure this is: unsigned, and an integer. switch (c.napi_get_value_uint32(env, value, &result)) { .napi_ok => {}, .napi_number_expected => return throw(env, name ++ " must be a number"), else => unreachable, } return result; } pub fn byte_slice_into_object( env: c.napi_env, object: c.napi_value, comptime key: [:0]const u8, value: []const u8, comptime error_message: [:0]const u8, ) !void { var result: c.napi_value = undefined; // create a copy that is managed by V8. if (c.napi_create_buffer_copy(env, value.len, value.ptr, null, &result) != .napi_ok) { return throw(env, error_message ++ " Failed to allocate Buffer in V8."); } if (c.napi_set_named_property(env, object, key, result) != .napi_ok) { return throw(env, error_message); } } pub fn u128_into_object( env: c.napi_env, object: c.napi_value, comptime key: [:0]const u8, value: u128, comptime error_message: [:0]const u8, ) !void { // A BigInt's value (using ^ to mean exponent) is (words[0] * (2^64)^0 + words[1] * (2^64)^1 + ...) // V8 says that the words are little endian. If we were on a big endian machine // we would need to convert, but big endian is not supported by tigerbeetle. var bigint: c.napi_value = undefined; if (c.napi_create_bigint_words( env, 0, 2, @ptrCast(*const [2]u64, &value), &bigint, ) != .napi_ok) { return throw(env, error_message); } if (c.napi_set_named_property(env, object, key, bigint) != .napi_ok) { return throw(env, error_message); } } pub fn u64_into_object( env: c.napi_env, object: c.napi_value, comptime key: [:0]const u8, value: u64, comptime error_message: [:0]const u8, ) !void { var result: c.napi_value = undefined; if (c.napi_create_bigint_uint64(env, value, &result) != .napi_ok) { return throw(env, error_message); } if (c.napi_set_named_property(env, object, key, result) != .napi_ok) { return throw(env, error_message); } } pub fn u32_into_object( env: c.napi_env, object: c.napi_value, comptime key: [:0]const u8, value: u32, comptime error_message: [:0]const u8, ) !void { var result: c.napi_value = undefined; if (c.napi_create_uint32(env, value, &result) != .napi_ok) { return throw(env, error_message); } if (c.napi_set_named_property(env, object, key, result) != .napi_ok) { return throw(env, error_message); } } pub fn create_object(env: c.napi_env, comptime error_message: [:0]const u8) !c.napi_value { var result: c.napi_value = undefined; if (c.napi_create_object(env, &result) != .napi_ok) { return throw(env, error_message); } return result; } pub fn create_string(env: c.napi_env, value: [:0]const u8) !c.napi_value { var result: c.napi_value = undefined; if (c.napi_create_string_utf8(env, value, value.len, &result) != .napi_ok) { return throw(env, "Failed to create string"); } return result; } fn create_buffer( env: c.napi_env, value: []const u8, comptime error_message: [:0]const u8, ) !c.napi_value { var data: ?*c_void = undefined; var result: c.napi_value = undefined; if (c.napi_create_buffer(env, value.len, &data, &result) != .napi_ok) { return throw(env, error_message); } std.mem.copy(u8, @ptrCast([*]u8, data.?)[0..value.len], value[0..value.len]); return result; } pub fn create_array( env: c.napi_env, length: u32, comptime error_message: [:0]const u8, ) !c.napi_value { var result: c.napi_value = undefined; if (c.napi_create_array_with_length(env, length, &result) != .napi_ok) { return throw(env, error_message); } return result; } pub fn set_array_element( env: c.napi_env, array: c.napi_value, index: u32, value: c.napi_value, comptime error_message: [:0]const u8, ) !void { if (c.napi_set_element(env, array, index, value) != .napi_ok) { return throw(env, error_message); } } pub fn array_element(env: c.napi_env, array: c.napi_value, index: u32) !c.napi_value { var element: c.napi_value = undefined; if (c.napi_get_element(env, array, index, &element) != .napi_ok) { return throw(env, "Failed to get array element."); } return element; } pub fn array_length(env: c.napi_env, array: c.napi_value) !u32 { var is_array: bool = undefined; assert(c.napi_is_array(env, array, &is_array) == .napi_ok); if (!is_array) return throw(env, "Batch must be an Array."); var length: u32 = undefined; assert(c.napi_get_array_length(env, array, &length) == .napi_ok); return length; } pub fn delete_reference(env: c.napi_env, reference: c.napi_ref) !void { if (c.napi_delete_reference(env, reference) != .napi_ok) { return throw(env, "Failed to delete callback reference."); } } pub fn create_error( env: c.napi_env, comptime message: [:0]const u8, ) TranslationError!c.napi_value { var napi_string: c.napi_value = undefined; if (c.napi_create_string_utf8(env, message, std.mem.len(message), &napi_string) != .napi_ok) { return TranslationError.ExceptionThrown; } var napi_error: c.napi_value = undefined; if (c.napi_create_error(env, null, napi_string, &napi_error) != .napi_ok) { return TranslationError.ExceptionThrown; } return napi_error; } pub fn call_function( env: c.napi_env, this: c.napi_value, callback: c.napi_value, argc: usize, argv: [*]c.napi_value, ) !void { const result = c.napi_call_function(env, this, callback, argc, argv, null); switch (result) { .napi_ok => {}, // the user's callback may throw a JS exception or call other functions that do so. We // therefore don't throw another error. .napi_pending_exception => {}, else => return throw(env, "Failed to invoke results callback."), } } pub fn scope(env: c.napi_env, comptime error_message: [:0]const u8) !c.napi_value { var result: c.napi_value = undefined; if (c.napi_get_global(env, &result) != .napi_ok) { return throw(env, error_message); } return result; } pub fn reference_value( env: c.napi_env, callback_reference: c.napi_ref, comptime error_message: [:0]const u8, ) !c.napi_value { var result: c.napi_value = undefined; if (c.napi_get_reference_value(env, callback_reference, &result) != .napi_ok) { return throw(env, error_message); } return result; }
src/translate.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const meta = std.meta; const trait = std.meta.trait; const mustache = @import("../mustache.zig"); const Element = mustache.Element; const RenderOptions = mustache.options.RenderOptions; const Delimiters = mustache.Delimiters; const context = @import("context.zig"); const PathResolution = context.PathResolution; const Escape = context.Escape; const rendering = @import("rendering.zig"); const map = @import("partials_map.zig"); const lambda = @import("lambda.zig"); const LambdaContext = lambda.LambdaContext; const LambdaInvoker = lambda.LambdaInvoker; const testing = std.testing; const assert = std.debug.assert; pub const FlattenedType = [4]usize; pub fn Invoker(comptime Writer: type, comptime PartialsMap: type, comptime options: RenderOptions) type { const RenderEngine = rendering.RenderEngine(Writer, PartialsMap, options); const Context = RenderEngine.Context; const DataRender = RenderEngine.DataRender; return struct { fn PathInvoker(comptime TError: type, TReturn: type, comptime action_fn: anytype) type { const action_type_info = @typeInfo(@TypeOf(action_fn)); if (action_type_info != .Fn) @compileError("action_fn must be a function"); return struct { const Result = PathResolution(TReturn); const Depth = enum { Root, Leaf }; pub fn call( action_param: anytype, data: anytype, path: Element.Path, index: ?usize, ) TError!Result { return try find(.Root, action_param, data, path, index); } fn find( depth: Depth, action_param: anytype, data: anytype, path: Element.Path, index: ?usize, ) TError!Result { const Data = @TypeOf(data); if (Data == void) return .ChainBroken; const ctx = Fields.getRuntimeValue(data); if (comptime lambda.isLambdaInvoker(Data)) { return Result{ .Lambda = try action_fn(action_param, ctx) }; } else { if (path.len > 0) { return try recursiveFind(depth, Data, action_param, ctx, path[0], path[1..], index); } else if (index) |current_index| { return try iterateAt(Data, action_param, ctx, current_index); } else { return Result{ .Field = try action_fn(action_param, ctx) }; } } } fn recursiveFind( depth: Depth, comptime TValue: type, action_param: anytype, data: anytype, current_path_part: []const u8, next_path_parts: Element.Path, index: ?usize, ) TError!Result { const typeInfo = @typeInfo(TValue); switch (typeInfo) { .Struct => { return try findFieldPath(depth, TValue, action_param, data, current_path_part, next_path_parts, index); }, .Pointer => |info| switch (info.size) { .One => return try recursiveFind(depth, info.child, action_param, data, current_path_part, next_path_parts, index), .Slice => { //Slice supports the "len" field, if (next_path_parts.len == 0 and std.mem.eql(u8, "len", current_path_part)) { return try find(.Leaf, action_param, Fields.lenOf(data), next_path_parts, index); } }, .Many => @compileError("[*] pointers not supported"), .C => @compileError("[*c] pointers not supported"), }, .Optional => |info| { if (!Fields.isNull(data)) { return try recursiveFind(depth, info.child, action_param, data, current_path_part, next_path_parts, index); } }, .Array, .Vector => { //Slice supports the "len" field, if (next_path_parts.len == 0 and std.mem.eql(u8, "len", current_path_part)) { return try find(.Leaf, action_param, Fields.lenOf(data), next_path_parts, index); } }, else => {}, } return if (depth == .Root) .NotFoundInContext else .ChainBroken; } fn findFieldPath( depth: Depth, comptime TValue: type, action_param: anytype, data: anytype, current_path_part: []const u8, next_path_parts: Element.Path, index: ?usize, ) TError!Result { const fields = std.meta.fields(TValue); inline for (fields) |field| { if (std.mem.eql(u8, field.name, current_path_part)) { return try find(.Leaf, action_param, Fields.getField(data, field.name), next_path_parts, index); } } else { return try findLambdaPath(depth, TValue, action_param, data, current_path_part, next_path_parts, index); } } fn findLambdaPath( depth: Depth, comptime TValue: type, action_param: anytype, data: anytype, current_path_part: []const u8, next_path_parts: Element.Path, index: ?usize, ) TError!Result { const decls = comptime std.meta.declarations(TValue); inline for (decls) |decl| { const has_fn = comptime decl.is_pub and trait.hasFn(decl.name)(TValue); if (has_fn) { const bound_fn = @field(TValue, decl.name); const is_valid_lambda = comptime lambda.isValidLambdaFunction(TValue, @TypeOf(bound_fn)); if (std.mem.eql(u8, current_path_part, decl.name)) { if (is_valid_lambda) { return try getLambda(action_param, Fields.lhs(data), bound_fn, next_path_parts, index); } else { return .ChainBroken; } } } } else { return if (depth == .Root) .NotFoundInContext else .ChainBroken; } } fn getLambda( action_param: anytype, data: anytype, bound_fn: anytype, next_path_parts: Element.Path, index: ?usize, ) TError!Result { const TData = @TypeOf(data); const TFn = @TypeOf(bound_fn); const args_len = @typeInfo(TFn).Fn.args.len; // Lambdas cannot be used for navigation through a path // Examples: // Path: "person.lambda.address" > Returns "ChainBroken" // Path: "person.address.lambda" > "Resolved" if (next_path_parts.len == 0) { const Impl = if (args_len == 1) LambdaInvoker(void, TFn) else LambdaInvoker(TData, TFn); var impl = Impl{ .bound_fn = bound_fn, .data = if (args_len == 1) {} else data, }; return try find(.Leaf, action_param, &impl, next_path_parts, index); } else { return .ChainBroken; } } fn iterateAt( comptime TValue: type, action_param: anytype, data: anytype, index: usize, ) TError!Result { switch (@typeInfo(TValue)) { .Struct => |info| { if (info.is_tuple) { const derref = comptime trait.isSingleItemPtr(@TypeOf(data)); inline for (info.fields) |_, i| { if (index == i) { return Result{ .Field = try action_fn( action_param, Fields.getTupleElement(if (derref) data.* else data, i), ), }; } } else { return .IteratorConsumed; } } }, // Booleans are evaluated on the iterator .Bool => { return if (data == true and index == 0) Result{ .Field = try action_fn(action_param, data) } else .IteratorConsumed; }, .Pointer => |info| switch (info.size) { .One => { return try iterateAt(info.child, action_param, Fields.lhs(data), index); }, .Slice => { //Slice of u8 is always string if (info.child != u8) { return if (index < data.len) Result{ .Field = try action_fn(action_param, Fields.getElement(Fields.lhs(data), index)) } else .IteratorConsumed; } }, else => {}, }, .Array => |info| { //Array of u8 is always string if (info.child != u8) { return if (index < data.len) Result{ .Field = try action_fn(action_param, Fields.getElement(Fields.lhs(data), index)) } else .IteratorConsumed; } }, .Vector => { return if (index < data.len) Result{ .Field = try action_fn(action_param, Fields.getElement(Fields.lhs(data), index)) } else .IteratorConsumed; }, .Optional => |info| { return if (!Fields.isNull(data)) try iterateAt(info.child, action_param, Fields.lhs(data), index) else .IteratorConsumed; }, else => {}, } return if (index == 0) Result{ .Field = try action_fn(action_param, data) } else .IteratorConsumed; } }; } pub fn get( data: anytype, path: Element.Path, index: ?usize, ) PathResolution(Context) { const Get = PathInvoker(error{}, Context, getAction); return try Get.call( {}, data, path, index, ); } pub fn interpolate( data_render: *DataRender, data: anytype, path: Element.Path, escape: Escape, ) (Allocator.Error || Writer.Error)!PathResolution(void) { const Interpolate = PathInvoker(Allocator.Error || Writer.Error, void, interpolateAction); return try Interpolate.call( .{ data_render, escape }, data, path, null, ); } pub fn capacityHint( data_render: *DataRender, data: anytype, path: Element.Path, ) PathResolution(usize) { const CapacityHint = PathInvoker(error{}, usize, capacityHintAction); return try CapacityHint.call( data_render, data, path, null, ); } pub fn expandLambda( data_render: *DataRender, data: anytype, inner_text: []const u8, escape: Escape, delimiters: Delimiters, path: Element.Path, ) (Allocator.Error || Writer.Error)!PathResolution(void) { const ExpandLambdaAction = PathInvoker(Allocator.Error || Writer.Error, void, expandLambdaAction); return try ExpandLambdaAction.call( .{ data_render, inner_text, escape, delimiters }, data, path, null, ); } fn getAction(param: void, value: anytype) error{}!Context { _ = param; return context.getContext(Writer, value, PartialsMap, options); } fn interpolateAction( params: anytype, value: anytype, ) (Allocator.Error || Writer.Error)!void { if (comptime !std.meta.trait.isTuple(@TypeOf(params)) and params.len != 2) @compileError("Incorrect params " ++ @typeName(@TypeOf(params))); var data_render: *DataRender = params.@"0"; const escape: Escape = params.@"1"; _ = try data_render.write(value, escape); } fn capacityHintAction( params: anytype, value: anytype, ) error{}!usize { return params.valueCapacityHint(value); } fn expandLambdaAction( params: anytype, value: anytype, ) (Allocator.Error || Writer.Error)!void { if (comptime !std.meta.trait.isTuple(@TypeOf(params)) and params.len != 4) @compileError("Incorrect params " ++ @typeName(@TypeOf(params))); if (comptime !lambda.isLambdaInvoker(@TypeOf(value))) return; const Error = Allocator.Error || Writer.Error; const data_render: *DataRender = params.@"0"; const inner_text: []const u8 = params.@"1"; const escape: Escape = params.@"2"; const delimiters: Delimiters = params.@"3"; const Impl = lambda.LambdaContextImpl(Writer, PartialsMap, options); var impl = Impl{ .data_render = data_render, .escape = escape, .delimiters = delimiters, }; const lambda_context = impl.context(inner_text); // Errors are intentionally ignored on lambda calls, interpolating empty strings value.invoke(lambda_context) catch |e| { if (isOnErrorSet(Error, e)) { return @errSetCast(Error, e); } }; } }; } pub const Fields = struct { pub fn getField(data: anytype, comptime field_name: []const u8) field_type: { const TField = FieldType(@TypeOf(data), field_name); if (TField == comptime_int) { const comptime_value = @field(data, field_name); break :field_type RuntimeInt(comptime_value); } else if (TField == comptime_float) { const comptime_value = @field(data, field_name); break :field_type RuntimeFloat(comptime_value); } else if (TField == @Type(.Null)) { break :field_type ?u0; } else { break :field_type FieldRef(@TypeOf(data), field_name); } } { const Data = @TypeOf(data); const TField = FieldType(Data, field_name); const is_by_value = comptime byValue(TField); if (TField == comptime_int) { const comptime_value = @field(data, field_name); const runtime_value: RuntimeInt(comptime_value) = comptime_value; return runtime_value; } else if (TField == comptime_float) { const comptime_value = @field(data, field_name); const runtime_value: RuntimeFloat(comptime_value) = comptime_value; return runtime_value; } else if (TField == @TypeOf(.Null)) { const runtime_null: ?u0 = null; return runtime_null; } return if (is_by_value) @field(lhs(data), field_name) else &@field(lhs(data), field_name); } pub fn getRuntimeValue(ctx: anytype) context_type: { const TContext = @TypeOf(ctx); if (TContext == comptime_int) { const comptime_value = ctx; break :context_type RuntimeInt(comptime_value); } else if (TContext == comptime_float) { const comptime_value = ctx; break :context_type RuntimeFloat(comptime_value); } else if (TContext == @Type(.Null)) { break :context_type ?u0; } else { break :context_type TContext; } } { const TContext = @TypeOf(ctx); if (TContext == comptime_int) { const comptime_value = ctx; const runtime_value: RuntimeInt(comptime_value) = comptime_value; return runtime_value; } else if (TContext == comptime_float) { const comptime_value = ctx; const runtime_value: RuntimeFloat(comptime_value) = comptime_value; return runtime_value; } else if (TContext == @TypeOf(.Null)) { const runtime_null: ?u0 = null; return runtime_null; } else { return ctx; } } pub fn getTupleElement(ctx: anytype, comptime index: usize) element_type: { const T = @TypeOf(ctx); assert(trait.isTuple(T)); const ElementType = @TypeOf(ctx[index]); if (ElementType == comptime_int) { const comptime_value = ctx[index]; break :element_type RuntimeInt(comptime_value); } else if (ElementType == comptime_float) { const comptime_value = ctx[index]; break :element_type RuntimeFloat(comptime_value); } else if (ElementType == @Type(.Null)) { break :element_type ?u0; } else if (byValue(ElementType)) { break :element_type ElementType; } else { break :element_type @TypeOf(&ctx[index]); } } { const ElementType = @TypeOf(ctx[index]); if (ElementType == comptime_int) { const comptime_value = ctx[index]; const runtime_value: RuntimeInt(comptime_value) = comptime_value; return runtime_value; } else if (ElementType == comptime_float) { const comptime_value = ctx[index]; const runtime_value: RuntimeFloat(comptime_value) = comptime_value; return runtime_value; } else if (ElementType == @Type(.Null)) { const runtime_null: ?u0 = null; return runtime_null; } else if (comptime byValue(ElementType)) { return ctx[index]; } else { return &ctx[index]; } } pub fn getElement(ctx: anytype, index: usize) element_type: { const T = @TypeOf(ctx); const is_indexable = trait.isIndexable(T) and !trait.isTuple(T); if (!is_indexable) @compileError("Array, slice or vector expected"); const ElementType = @TypeOf(ctx[0]); if (byValue(ElementType)) { break :element_type ElementType; } else { break :element_type @TypeOf(&ctx[0]); } } { const ElementType = @TypeOf(ctx[0]); if (comptime byValue(ElementType)) { return ctx[index]; } else { return &ctx[index]; } } fn Lhs(comptime T: type) type { comptime { if (trait.is(.Optional)(T)) { return Lhs(meta.Child(T)); } else if (needsDerref(T)) { return Lhs(meta.Child(T)); } else { return T; } } } pub fn lhs(value: anytype) Lhs(@TypeOf(value)) { const T = @TypeOf(value); if (comptime trait.is(.Optional)(T)) { return lhs(value.?); } else if (comptime needsDerref(T)) { return lhs(value.*); } else { return value; } } pub fn needsDerref(comptime T: type) bool { comptime { if (trait.isSingleItemPtr(T)) { const Child = meta.Child(T); return trait.isSingleItemPtr(Child) or trait.isSlice(Child) or trait.is(.Optional)(Child); } else { return false; } } } pub fn byValue(comptime TField: type) bool { comptime { if (trait.is(.EnumLiteral)(TField)) @compileError( \\Enum literal is not supported for interpolation \\Error: ir_resolve_lazy_recurse. This is a bug in the Zig compiler \\Type: ++ @typeName(TField)); const max_size = @sizeOf(FlattenedType); const is_zero_size = @sizeOf(TField) == 0; const is_pointer = trait.isSlice(TField) or trait.isSingleItemPtr(TField); const can_embed = @sizeOf(TField) <= max_size and (trait.is(.Enum)(TField) or trait.is(.EnumLiteral)(TField) or TField == bool or trait.isIntegral(TField) or trait.isFloat(TField) or (trait.is(.Optional)(TField) and byValue(meta.Child(TField)))); return is_zero_size or is_pointer or can_embed; } } pub fn isNull(data: anytype) bool { return switch (@typeInfo(@TypeOf(data))) { .Pointer => |info| switch (info.size) { .One => return isNull(data.*), .Slice => return false, .Many => @compileError("[*] pointers not supported"), .C => @compileError("[*c] pointers not supported"), }, .Optional => return data == null, else => return false, }; } pub fn lenOf(data: anytype) ?usize { return switch (@typeInfo(@TypeOf(data))) { .Pointer => |info| switch (info.size) { .One => return null, .Slice => return data.len, .Many => @compileError("[*] pointers not supported"), .C => @compileError("[*c] pointers not supported"), }, .Array, .Vector => return data.len, .Optional => if (data) |value| return lenOf(value) else null, else => return null, }; } fn FieldRef(comptime T: type, comptime field_name: []const u8) type { comptime { const TField = FieldType(T, field_name); assert(TField != comptime_int); assert(TField != comptime_float); assert(TField != @TypeOf(.Null)); if (trait.is(.Optional)(T)) { return FieldRef(meta.Child(T), field_name); } else if (needsDerref(T)) { return FieldRef(meta.Child(T), field_name); } else { const instance: T = undefined; return @TypeOf(if (byValue(TField)) @field(instance, field_name) else &@field(instance, field_name)); } } } fn FieldType(comptime T: type, comptime field_name: []const u8) type { if (trait.is(.Optional)(T)) { const Child = meta.Child(T); return FieldType(Child, field_name); } else if (trait.isSingleItemPtr(T)) { const Child = meta.Child(T); return FieldType(Child, field_name); } else { const instance: T = undefined; return @TypeOf(@field(instance, field_name)); } } fn RuntimeInt(comptime value: comptime_int) type { return if (value > 0) std.math.IntFittingRange(0, value) else std.math.IntFittingRange(value, 0); } fn RuntimeFloat(comptime value: comptime_float) type { _ = value; return f64; } test "Needs derref" { var value: usize = 10; var ptr = &value; var const_ptr: *const usize = &value; var ptr_ptr = &ptr; var const_ptr_ptr: *const *usize = &ptr; try std.testing.expect(needsDerref(@TypeOf(value)) == false); try std.testing.expect(needsDerref(@TypeOf(ptr)) == false); try std.testing.expect(needsDerref(@TypeOf((const_ptr))) == false); try std.testing.expect(needsDerref(@TypeOf(ptr_ptr)) == true); try std.testing.expect(needsDerref(@TypeOf(const_ptr_ptr)) == true); var optional: ?usize = value; try std.testing.expect(needsDerref(@TypeOf(optional)) == false); var ptr_optional: *?usize = &optional; try std.testing.expect(needsDerref(@TypeOf(ptr_optional)) == true); var optional_ptr: ?*usize = ptr; try std.testing.expect(needsDerref(@TypeOf(optional_ptr)) == false); } test "Ref values" { const Data = struct { int: usize, level: struct { int: usize, }, }; var data = Data{ .int = 100, .level = .{ .int = 1000 } }; var field = getField(&data, "int"); try std.testing.expectEqual(field, data.int); var level = getField(&data, "level"); try std.testing.expectEqual(level.int, data.level.int); data.level.int = 1001; try std.testing.expectEqual(level.int, data.level.int); level.int = 1002; try std.testing.expectEqual(level.int, data.level.int); var level_field = getField(level, "int"); try std.testing.expectEqual(level_field, level.int); try std.testing.expectEqual(level_field, data.level.int); } test "Const ref values" { var data = .{ .int = @as(usize, 100), .level = .{ .int = @as(usize, 1000) } }; var field = getField(&data, "int"); try std.testing.expectEqual(field, data.int); var level = getField(&data, "level"); try std.testing.expectEqual(level.int, data.level.int); var level_field = getField(level, "int"); try std.testing.expectEqual(level_field, data.level.int); } test "comptime int" { var data = .{ .int = 100, .level = .{ .int = 1000 } }; var field = getField(&data, "int"); try std.testing.expectEqual(field, data.int); var level = getField(&data, "level"); try std.testing.expectEqual(level.int, data.level.int); var level_field = getField(level, "int"); try std.testing.expectEqual(level_field, data.level.int); } test "comptime floats" { var data = .{ .float = 3.14, .level = .{ .float = std.math.f128_min } }; var field = getField(&data, "float"); try std.testing.expectEqual(field, data.float); try std.testing.expect(@TypeOf(field) == f64); var level = getField(&data, "level"); try std.testing.expectEqual(level.float, data.level.float); var level_field = getField(level, "float"); try std.testing.expectEqual(level_field, data.level.float); try std.testing.expect(@TypeOf(level_field) == f128); } test "enum literal " { // Skip // ir_resolve_lazy_recurse. This is a bug in the Zig compiler if (true) return error.SkipZigTest; var data = .{ .value = .AreYouSure, .level = .{ .value = .Totally } }; var field = getField(&data, "value"); try std.testing.expectEqual(field, data.value); var level = getField(&data, "level"); try std.testing.expectEqual(level.value, data.level.int); var level_field = getField(level, "value"); try std.testing.expectEqual(level_field, data.level.int); } test "enum" { const Options = enum { AreYouSure, Totally }; var data = .{ .value = Options.AreYouSure, .level = .{ .value = Options.Totally } }; var field = getField(&data, "value"); try std.testing.expectEqual(field, data.value); var level = getField(&data, "level"); try std.testing.expectEqual(level.value, data.level.value); var level_field = getField(level, "value"); try std.testing.expectEqual(level_field, data.level.value); } test "strings" { var data = .{ .value = "hello", .level = .{ .value = "world" } }; var field = getField(&data, "value"); try std.testing.expectEqualStrings(field, data.value); var level = getField(&data, "level"); try std.testing.expectEqualStrings(level.value, data.level.value); var level_field = getField(level, "value"); try std.testing.expectEqualStrings(level_field, data.level.value); } test "slices" { const Data = struct { value: []const u8, level: struct { value: []const u8, }, }; var data = Data{ .value = "hello", .level = .{ .value = "world" } }; var field = getField(&data, "value"); try std.testing.expectEqualStrings(field, data.value); var level = getField(&data, "level"); try std.testing.expectEqualStrings(level.value, data.level.value); var level_field = getField(level, "value"); try std.testing.expectEqualStrings(level_field, data.level.value); } test "slices items" { const Item = struct { value: []const u8, }; const Data = struct { values: []Item, }; var items = [_]Item{ Item{ .value = "aaa" }, Item{ .value = "bbb" }, Item{ .value = "ccc" }, }; var data = Data{ .values = &items }; var field = getField(&data, "values"); try std.testing.expectEqual(field.len, data.values.len); var item0 = getElement(field, 0); try std.testing.expectEqual(item0.value, data.values[0].value); item0.value = "changed 0"; try std.testing.expectEqual(item0.value, data.values[0].value); var item1 = getElement(field, 1); try std.testing.expectEqual(item1.value, data.values[1].value); item1.value = "changed 1"; try std.testing.expectEqual(item1.value, data.values[1].value); var item2 = getElement(field, 2); try std.testing.expectEqual(item2.value, data.values[2].value); item2.value = "changed 2"; try std.testing.expectEqual(item2.value, data.values[2].value); } test "array items" { const Item = struct { value: []const u8, }; const Data = struct { values: [3]Item, }; var data = Data{ .values = [_]Item{ Item{ .value = "aaa" }, Item{ .value = "bbb" }, Item{ .value = "ccc" }, }, }; var field = getField(&data, "values"); try std.testing.expectEqual(field.len, data.values.len); var item0 = getElement(field, 0); try std.testing.expectEqual(item0.value, data.values[0].value); item0.value = "changed 0"; try std.testing.expectEqual(item0.value, data.values[0].value); var item1 = getElement(field, 1); try std.testing.expectEqual(item1.value, data.values[1].value); item1.value = "changed 1"; try std.testing.expectEqual(item1.value, data.values[1].value); var item2 = getElement(field, 2); try std.testing.expectEqual(item2.value, data.values[2].value); item2.value = "changed 2"; try std.testing.expectEqual(item2.value, data.values[2].value); } test "tuple items" { var data = .{ .values = .{ .{ .value = "aaa" }, .{ .value = "bbb" }, .{ .value = "ccc" }, }, }; var field = getField(&data, "values"); try std.testing.expectEqual(field.len, data.values.len); var item0 = getTupleElement(field, 0); try std.testing.expectEqual(item0.value, data.values[0].value); var item1 = getTupleElement(field, 1); try std.testing.expectEqual(item1.value, data.values[1].value); var item2 = getTupleElement(field, 2); try std.testing.expectEqual(item2.value, data.values[2].value); } test "optionals" { const Data = struct { value1: ?[]const u8, value2: ?[]const u8, level: ?struct { value1: ?[]const u8, value2: ?[]const u8, }, }; var data = Data{ .value1 = "hello", .value2 = null, .level = .{ .value1 = "world", .value2 = null } }; var field1 = getField(&data, "value1"); try std.testing.expect(field1 != null); try std.testing.expectEqualStrings(field1.?, data.value1.?); var field2 = getField(&data, "value2"); try std.testing.expect(field2 == null); var level = getField(&data, "level"); try std.testing.expect(level.*.?.value1 != null); try std.testing.expectEqualStrings(level.*.?.value1.?, data.level.?.value1.?); try std.testing.expect(level.*.?.value2 == null); var level_field1 = getField(level, "value1"); try std.testing.expect(level_field1 != null); try std.testing.expectEqualStrings(level_field1.?, data.level.?.value1.?); var level_field2 = getField(level, "value2"); try std.testing.expect(level_field2 == null); } test "optional pointers" { const SubData = struct { value: []const u8, level: ?*@This(), }; const Data = struct { value1: ?*SubData, value2: ?*const SubData, value3: ?*SubData, }; var value1 = SubData{ .value = "hello", .level = null, }; var value2 = SubData{ .value = "world", .level = &value1, }; var data = Data{ .value1 = &value1, .value2 = &value2, .value3 = null }; var field1 = getField(&data, "value1"); try std.testing.expect(field1 != null); try std.testing.expectEqualStrings(field1.?.value, data.value1.?.value); data.value1.?.value = "changed"; try std.testing.expectEqualStrings(field1.?.value, data.value1.?.value); field1.?.value = "changed again"; try std.testing.expectEqualStrings(field1.?.value, data.value1.?.value); var field1_value = getField(field1, "value"); try std.testing.expectEqualStrings(field1_value, data.value1.?.value); var field1_level = getField(field1, "level"); try std.testing.expect(field1_level == null); var field2 = getField(&data, "value2"); try std.testing.expect(field2 != null); try std.testing.expectEqualStrings(field2.?.value, data.value2.?.value); var field2_value = getField(field2, "value"); try std.testing.expectEqualStrings(field2_value, data.value2.?.value); var field2_level = getField(field2, "level"); try std.testing.expectEqualStrings(field2_level.?.value, data.value2.?.level.?.value); var field3 = getField(&data, "value3"); try std.testing.expect(field3 == null); } test "ref optionals" { const SubData = struct { value: []const u8, }; const Data = struct { value1: ?SubData, value2: ?SubData, level: struct { value1: ?SubData, value2: ?SubData, }, }; var data = Data{ .value1 = SubData{ .value = "hello" }, .value2 = null, .level = .{ .value1 = SubData{ .value = "world" }, .value2 = null } }; var field1 = getField(&data, "value1"); try std.testing.expect(field1.* != null); try std.testing.expectEqualStrings(field1.*.?.value, data.value1.?.value); var field2 = getField(&data, "value2"); try std.testing.expect(field2.* == null); data.value1.?.value = "changed"; try std.testing.expectEqualStrings(field1.*.?.value, data.value1.?.value); field1.*.?.value = "changed again"; try std.testing.expectEqualStrings(field1.*.?.value, data.value1.?.value); var level = getField(&data, "level"); try std.testing.expect(level.value1 != null); try std.testing.expectEqualStrings(level.value1.?.value, data.level.value1.?.value); try std.testing.expect(level.value2 == null); data.level.value1.?.value = "changed too"; try std.testing.expectEqualStrings(level.value1.?.value, data.level.value1.?.value); var level_field1 = getField(level, "value1"); try std.testing.expect(level_field1.* != null); try std.testing.expectEqualStrings(level_field1.*.?.value, data.level.value1.?.value); var level_field2 = getField(level, "value2"); try std.testing.expect(level_field2.* == null); data.level.value1.?.value = "changed one more time"; try std.testing.expectEqualStrings(level_field1.*.?.value, data.level.value1.?.value); level_field1.*.?.value = "changed from here"; try std.testing.expectEqualStrings(level_field1.*.?.value, data.level.value1.?.value); } test "zero size" { const Empty = struct {}; const SingleEnum = enum { OnlyOption }; const Data = struct { value1: u0, value2: []const Empty, value3: void, value4: SingleEnum, }; var data = Data{ .value1 = 0, .value2 = &.{ Empty{}, Empty{}, Empty{} }, .value3 = {}, .value4 = .OnlyOption }; var field1 = getField(&data, "value1"); try std.testing.expect(field1 == 0); try std.testing.expect(@sizeOf(@TypeOf(field1)) == 0); var field2 = getField(&data, "value2"); try std.testing.expect(field2.len == 3); try std.testing.expect(@sizeOf(@TypeOf(field2)) == @sizeOf(usize)); var field3 = getField(&data, "value3"); try std.testing.expect(field3 == {}); try std.testing.expect(@sizeOf(@TypeOf(field3)) == 0); var field4 = getField(&data, "value4"); try std.testing.expect(field4 == .OnlyOption); try std.testing.expect(@sizeOf(@TypeOf(field4)) == 0); } test "nested" { const Data = struct { value: []const u8, level: struct { value: []const u8, sub_level: struct { value: []const u8, } }, }; // Asserts that all pointers will remain valid and not ever be derrefed on the stack const Funcs = struct { fn level(data: anytype) FieldRef(@TypeOf(data), "level") { return getField(data, "level"); } fn sub_level(data: anytype) FieldRef(FieldRef(@TypeOf(data), "level"), "sub_level") { const value = getField(data, "level"); return getField(value, "sub_level"); } }; var data = Data{ .value = "hello", .level = .{ .value = "world", .sub_level = .{ .value = "from zig" } } }; var level = Funcs.level(&data); try std.testing.expectEqualStrings(level.value, data.level.value); try std.testing.expectEqualStrings(level.sub_level.value, data.level.sub_level.value); data.level.value = "changed"; try std.testing.expectEqualStrings(level.value, data.level.value); data.level.sub_level.value = "changed too"; try std.testing.expectEqualStrings(level.sub_level.value, data.level.sub_level.value); var sub_level = Funcs.sub_level(&data); try std.testing.expectEqualStrings(sub_level.value, data.level.sub_level.value); data.level.sub_level.value = "changed one more time"; try std.testing.expectEqualStrings(level.sub_level.value, data.level.sub_level.value); try std.testing.expectEqualStrings(sub_level.value, data.level.sub_level.value); level.sub_level.value = "changed from elsewhere"; try std.testing.expectEqualStrings(level.sub_level.value, data.level.sub_level.value); try std.testing.expectEqualStrings(sub_level.value, data.level.sub_level.value); sub_level.value = "changed from elsewhere again"; try std.testing.expectEqualStrings(level.sub_level.value, data.level.sub_level.value); try std.testing.expectEqualStrings(sub_level.value, data.level.sub_level.value); } }; // Check if an error is part of a error set // https://github.com/ziglang/zig/issues/2473 fn isOnErrorSet(comptime Error: type, value: anytype) bool { switch (@typeInfo(Error)) { .ErrorSet => |info| if (info) |errors| { if (@typeInfo(@TypeOf(value)) == .ErrorSet) { inline for (errors) |item| { const int_value = @errorToInt(@field(Error, item.name)); if (int_value == @errorToInt(value)) return true; } } }, else => {}, } return false; } test "isOnErrorSet" { const A = error{ a1, a2 }; const B = error{ b1, b2 }; const AB = A || B; const Mixed = error{ a1, b2 }; const Empty = error{}; try testing.expect(isOnErrorSet(A, error.a1)); try testing.expect(isOnErrorSet(A, error.a2)); try testing.expect(!isOnErrorSet(A, error.b1)); try testing.expect(!isOnErrorSet(A, error.b2)); try testing.expect(isOnErrorSet(AB, error.a1)); try testing.expect(isOnErrorSet(AB, error.a2)); try testing.expect(isOnErrorSet(AB, error.b1)); try testing.expect(isOnErrorSet(AB, error.b2)); try testing.expect(isOnErrorSet(Mixed, error.a1)); try testing.expect(!isOnErrorSet(Mixed, error.a2)); try testing.expect(!isOnErrorSet(Mixed, error.b1)); try testing.expect(isOnErrorSet(Mixed, error.b2)); try testing.expect(!isOnErrorSet(Empty, error.a1)); try testing.expect(!isOnErrorSet(Empty, error.a2)); try testing.expect(!isOnErrorSet(Empty, error.b1)); try testing.expect(!isOnErrorSet(Empty, error.b2)); } test { _ = Fields; _ = tests; } const tests = struct { const Tuple = std.meta.Tuple(&.{ u8, u32, u64 }); const Data = struct { a1: struct { b1: struct { c1: struct { d1: u0 = 0, d2: u0 = 0, d_null: ?u0 = null, d_slice: []const u0 = &.{ 0, 0, 0 }, d_array: [3]u0 = .{ 0, 0, 0 }, d_tuple: Tuple = Tuple{ 0, 0, 0 }, } = .{}, c_null: ?u0 = null, c_slice: []const u0 = &.{ 0, 0, 0 }, c_array: [3]u0 = .{ 0, 0, 0 }, c_tuple: Tuple = Tuple{ 0, 0, 0 }, } = .{}, b2: u0 = 0, b_null: ?u0 = null, b_slice: []const u0 = &.{ 0, 0, 0 }, b_array: [3]u0 = .{ 0, 0, 0 }, b_tuple: Tuple = Tuple{ 0, 0, 0 }, } = .{}, a2: u0 = 0, a_null: ?u0 = null, a_slice: []const u0 = &.{ 0, 0, 0 }, a_array: [3]u0 = .{ 0, 0, 0 }, a_tuple: Tuple = Tuple{ 0, 0, 0 }, }; const dummy_options = RenderOptions{ .Template = .{} }; const DummyParser = @import("../parsing/parser.zig").Parser(.{ .source = .{ .String = .{ .copy_strings = false } }, .output = .Render, .load_mode = .runtime_loaded }); const DummyWriter = @TypeOf(std.io.null_writer); const DummyPartialsMap = map.PartialsMap(void, dummy_options); const DummyRenderEngine = rendering.RenderEngine(DummyWriter, DummyPartialsMap, dummy_options); const DummyInvoker = DummyRenderEngine.Invoker; const DummyCaller = DummyInvoker.PathInvoker(error{}, bool, dummyAction); fn dummyAction(comptime TExpected: type, value: anytype) error{}!bool { const TValue = @TypeOf(value); const expected = comptime (TExpected == TValue) or (trait.isSingleItemPtr(TValue) and meta.Child(TValue) == TExpected); if (!expected) { std.log.err( \\ Invalid iterator type \\ Expected \"{s}\" \\ Found \"{s}\" , .{ @typeName(TExpected), @typeName(TValue) }); } return expected; } fn dummySeek(comptime TExpected: type, data: anytype, identifier: []const u8, index: ?usize) !DummyCaller.Result { var parser = try DummyParser.init(testing.allocator, "", .{}); defer parser.deinit(); var path = try parser.parsePath(identifier); defer Element.destroyPath(testing.allocator, false, path); return try DummyCaller.call(TExpected, &data, path, index); } fn expectFound(comptime TExpected: type, data: anytype, path: []const u8) !void { const value = try dummySeek(TExpected, data, path, null); try testing.expect(value == .Field); try testing.expect(value.Field == true); } fn expectNotFound(data: anytype, path: []const u8) !void { const value = try dummySeek(void, data, path, null); try testing.expect(value != .Field); } fn expectIterFound(comptime TExpected: type, data: anytype, path: []const u8, index: usize) !void { const value = try dummySeek(TExpected, data, path, index); try testing.expect(value == .Field); try testing.expect(value.Field == true); } fn expectIterNotFound(data: anytype, path: []const u8, index: usize) !void { const value = try dummySeek(void, data, path, index); try testing.expect(value != .Field); } test "Comptime seek - self" { var data = Data{}; try expectFound(Data, data, ""); } test "Comptime seek - dot" { var data = Data{}; try expectFound(Data, data, "."); } test "Comptime seek - not found" { var data = Data{}; try expectNotFound(data, "wrong"); } test "Comptime seek - found" { var data = Data{}; try expectFound(@TypeOf(data.a1), data, "a1"); try expectFound(@TypeOf(data.a2), data, "a2"); } test "Comptime seek - self null" { var data: ?Data = null; try expectFound(?Data, data, ""); } test "Comptime seek - self dot" { var data: ?Data = null; try expectFound(?Data, data, "."); } test "Comptime seek - found nested" { var data = Data{}; try expectFound(@TypeOf(data.a1.b1), data, "a1.b1"); try expectFound(@TypeOf(data.a1.b2), data, "a1.b2"); try expectFound(@TypeOf(data.a1.b1.c1), data, "a1.b1.c1"); try expectFound(@TypeOf(data.a1.b1.c1.d1), data, "a1.b1.c1.d1"); try expectFound(@TypeOf(data.a1.b1.c1.d2), data, "a1.b1.c1.d2"); } test "Comptime seek - not found nested" { var data = Data{}; try expectNotFound(data, "a1.wong"); try expectNotFound(data, "a1.b1.wong"); try expectNotFound(data, "a1.b2.wrong"); try expectNotFound(data, "a1.b1.c1.wrong"); try expectNotFound(data, "a1.b1.c1.d1.wrong"); try expectNotFound(data, "a1.b1.c1.d2.wrong"); } test "Comptime seek - null nested" { var data = Data{}; try expectFound(@TypeOf(data.a_null), data, "a_null"); try expectFound(@TypeOf(data.a1.b_null), data, "a1.b_null"); try expectFound(@TypeOf(data.a1.b1.c_null), data, "a1.b1.c_null"); try expectFound(@TypeOf(data.a1.b1.c1.d_null), data, "a1.b1.c1.d_null"); } test "Comptime iter - self" { var data = Data{}; try expectIterFound(Data, data, "", 0); } test "Comptime iter consumed - self" { var data = Data{}; try expectIterNotFound(data, "", 1); } test "Comptime iter - dot" { var data = Data{}; try expectIterFound(Data, data, ".", 0); } test "Comptime iter consumed - dot" { var data = Data{}; try expectIterNotFound(data, ".", 1); } test "Comptime seek - not found" { var data = Data{}; try expectIterNotFound(data, "wrong", 0); try expectIterNotFound(data, "wrong", 1); } test "Comptime iter - found" { var data = Data{}; try expectIterFound(@TypeOf(data.a1), data, "a1", 0); try expectIterFound(@TypeOf(data.a2), data, "a2", 0); } test "Comptime iter consumed - found" { var data = Data{}; try expectIterNotFound(data, "a1", 1); try expectIterNotFound(data, "a2", 1); } test "Comptime iter - found nested" { var data = Data{}; try expectIterFound(@TypeOf(data.a1.b1), data, "a1.b1", 0); try expectIterFound(@TypeOf(data.a1.b2), data, "a1.b2", 0); try expectIterFound(@TypeOf(data.a1.b1.c1), data, "a1.b1.c1", 0); try expectIterFound(@TypeOf(data.a1.b1.c1.d1), data, "a1.b1.c1.d1", 0); try expectIterFound(@TypeOf(data.a1.b1.c1.d2), data, "a1.b1.c1.d2", 0); } test "Comptime iter consumed - found nested" { var data = Data{}; try expectIterNotFound(data, "a1.b1", 1); try expectIterNotFound(data, "a1.b2", 1); try expectIterNotFound(data, "a1.b1.c1", 1); try expectIterNotFound(data, "a1.b1.c1.d1", 1); try expectIterNotFound(data, "a1.b1.c1.d2", 1); } test "Comptime iter - not found nested" { var data = Data{}; try expectIterNotFound(data, "a1.wong", 0); try expectIterNotFound(data, "a1.b1.wong", 0); try expectIterNotFound(data, "a1.b2.wrong", 0); try expectIterNotFound(data, "a1.b1.c1.wrong", 0); try expectIterNotFound(data, "a1.b1.c1.d1.wrong", 0); try expectIterNotFound(data, "a1.b1.c1.d2.wrong", 0); try expectIterNotFound(data, "a1.wong", 1); try expectIterNotFound(data, "a1.b1.wong", 1); try expectIterNotFound(data, "a1.b2.wrong", 1); try expectIterNotFound(data, "a1.b1.c1.wrong", 1); try expectIterNotFound(data, "a1.b1.c1.d1.wrong", 1); try expectIterNotFound(data, "a1.b1.c1.d2.wrong", 1); } test "Comptime iter - slice" { var data = Data{}; try expectIterFound(@TypeOf(data.a_slice[0]), data, "a_slice", 0); try expectIterFound(@TypeOf(data.a_slice[1]), data, "a_slice", 1); try expectIterFound(@TypeOf(data.a_slice[2]), data, "a_slice", 2); try expectIterNotFound(data, "a_slice", 3); } test "Comptime iter - array" { var data = Data{}; try expectIterFound(@TypeOf(data.a_array[0]), data, "a_array", 0); try expectIterFound(@TypeOf(data.a_array[1]), data, "a_array", 1); try expectIterFound(@TypeOf(data.a_array[2]), data, "a_array", 2); try expectIterNotFound(data, "a_array", 3); } test "Comptime iter - tuple" { var data = Data{}; try expectIterFound(@TypeOf(data.a_tuple[0]), data, "a_tuple", 0); try expectIterFound(@TypeOf(data.a_tuple[1]), data, "a_tuple", 1); try expectIterFound(@TypeOf(data.a_tuple[2]), data, "a_tuple", 2); try expectIterNotFound(data, "a_tuple", 3); } test "Comptime iter - nested slice" { var data = Data{}; try expectIterFound(@TypeOf(data.a_slice[0]), data, "a_slice", 0); try expectIterFound(@TypeOf(data.a1.b_slice[0]), data, "a1.b_slice", 0); try expectIterFound(@TypeOf(data.a1.b1.c_slice[0]), data, "a1.b1.c_slice", 0); try expectIterFound(@TypeOf(data.a1.b1.c1.d_slice[0]), data, "a1.b1.c1.d_slice", 0); try expectIterFound(@TypeOf(data.a_slice[1]), data, "a_slice", 1); try expectIterFound(@TypeOf(data.a1.b_slice[1]), data, "a1.b_slice", 1); try expectIterFound(@TypeOf(data.a1.b1.c_slice[1]), data, "a1.b1.c_slice", 1); try expectIterFound(@TypeOf(data.a1.b1.c1.d_slice[1]), data, "a1.b1.c1.d_slice", 1); try expectIterFound(@TypeOf(data.a_slice[2]), data, "a_slice", 2); try expectIterFound(@TypeOf(data.a1.b_slice[2]), data, "a1.b_slice", 2); try expectIterFound(@TypeOf(data.a1.b1.c_slice[2]), data, "a1.b1.c_slice", 2); try expectIterFound(@TypeOf(data.a1.b1.c1.d_slice[2]), data, "a1.b1.c1.d_slice", 2); try expectIterNotFound(data, "a_slice", 3); try expectIterNotFound(data, "a1.b_slice", 3); try expectIterNotFound(data, "a1.b1.c_slice", 3); try expectIterNotFound(data, "a1.b1.c1.d_slice", 3); } test "Comptime iter - nested array" { var data = Data{}; try expectIterFound(@TypeOf(data.a_tuple[0]), data, "a_tuple", 0); try expectIterFound(@TypeOf(data.a1.b_tuple[0]), data, "a1.b_tuple", 0); try expectIterFound(@TypeOf(data.a1.b1.c_tuple[0]), data, "a1.b1.c_tuple", 0); try expectIterFound(@TypeOf(data.a1.b1.c1.d_tuple[0]), data, "a1.b1.c1.d_tuple", 0); try expectIterFound(@TypeOf(data.a_tuple[1]), data, "a_tuple", 1); try expectIterFound(@TypeOf(data.a1.b_tuple[1]), data, "a1.b_tuple", 1); try expectIterFound(@TypeOf(data.a1.b1.c_tuple[1]), data, "a1.b1.c_tuple", 1); try expectIterFound(@TypeOf(data.a1.b1.c1.d_tuple[1]), data, "a1.b1.c1.d_tuple", 1); try expectIterFound(@TypeOf(data.a_tuple[2]), data, "a_tuple", 2); try expectIterFound(@TypeOf(data.a1.b_tuple[2]), data, "a1.b_tuple", 2); try expectIterFound(@TypeOf(data.a1.b1.c_tuple[2]), data, "a1.b1.c_tuple", 2); try expectIterFound(@TypeOf(data.a1.b1.c1.d_tuple[2]), data, "a1.b1.c1.d_tuple", 2); try expectIterNotFound(data, "a_tuple", 3); try expectIterNotFound(data, "a1.b_tuple", 3); try expectIterNotFound(data, "a1.b1.c_tuple", 3); try expectIterNotFound(data, "a1.b1.c1.d_tuple", 3); } test "Comptime iter - nested tuple" { var data = Data{}; try expectIterFound(@TypeOf(data.a_array[0]), data, "a_array", 0); try expectIterFound(@TypeOf(data.a1.b_array[0]), data, "a1.b_array", 0); try expectIterFound(@TypeOf(data.a1.b1.c_array[0]), data, "a1.b1.c_array", 0); try expectIterFound(@TypeOf(data.a1.b1.c1.d_array[0]), data, "a1.b1.c1.d_array", 0); try expectIterFound(@TypeOf(data.a_array[1]), data, "a_array", 1); try expectIterFound(@TypeOf(data.a1.b_array[1]), data, "a1.b_array", 1); try expectIterFound(@TypeOf(data.a1.b1.c_array[1]), data, "a1.b1.c_array", 1); try expectIterFound(@TypeOf(data.a1.b1.c1.d_array[1]), data, "a1.b1.c1.d_array", 1); try expectIterFound(@TypeOf(data.a_array[2]), data, "a_array", 2); try expectIterFound(@TypeOf(data.a1.b_array[2]), data, "a1.b_array", 2); try expectIterFound(@TypeOf(data.a1.b1.c_array[2]), data, "a1.b1.c_array", 2); try expectIterFound(@TypeOf(data.a1.b1.c1.d_array[2]), data, "a1.b1.c1.d_array", 2); try expectIterNotFound(data, "a_array", 3); try expectIterNotFound(data, "a1.b_array", 3); try expectIterNotFound(data, "a1.b1.c_array", 3); try expectIterNotFound(data, "a1.b1.c1.d_array", 3); } };
src/rendering/invoker.zig
const std = @import("std"); const str = []const u8; const builtin = @import("builtin"); const util = @import("../`util.zig"); const compile = @import("./compile.zig"); const help = @import("./help.zig"); const json = std.json; const Dir = std.fs.Dir; const fmt = std.fmt; const process = std.process; const ChildProcess = std.ChildProcess; const Thread = std.Thread; const eq = util.eq; const readFile = util.readFile; const eql = std.mem.eql; const Allocator = std.mem.Allocator; const stderr = std.io.getStdErr; const stdin = std.io.getStdIn(); const stdout = std.io.getStdOut(); pub const ProjectConfigExt = Project.Config.Ext; pub const ProjectType = Project.Type; pub const ProjectConfig = Project.Config; pub const Context = struct { const Self = @This(); allocator: Allocator, step: std.atomic.Atomic(usize).init(0), recv: Thread.AutoResetEvent = Thread.AutoResetEvent{}, send: Thread.AutoResetEvent = Thread.AutoResetEvent{}, thread: Thread = undefined, pub const ProjectSetupSteps = enum(u8) { setup = 0, files = 1, compile = 2, install = 3 }; pub fn sender(self: *@This()) !void { std.debug.print("Context value (0): {d}", .{self.step}); self.step = 1; self.send.set(); self.recv.wait(); std.debug.print("Context value (2): {d}", .{self.step}); self.step = 3; self.send.set(); self.recv.wait(); std.debug.print("Context value (4): {d}", .{self.step}); } pub fn receiver(self: *@This()) !void { self.recv.wait(); } pub fn create() Context { return Context{}; } pub fn init(a: Allocator) Context { return Context{ .allocator = a }; } pub fn run(self: *@This()) !void { try self.sender(); } }; /// NOTE: Struct representing full idleset project, /// encapsulated with an optionally provided dir pub const Project = struct { const Self = @This(); cfg_format: Project.Config.Format = .json, dir: Dir = std.fs.cwd(), allocator: Allocator, project_type: Project.Type = Project.Type.bin, templ_dir_path: []const u8 = "../../res/ptmpl/", config: Project.Config, relative_src_dir: []const u8 = "src", relative_out_dir: []const u8 = "out", config_templ_name: str = Config.Ext.json.toTemplate(Project.Type.json), hash: std.array_hash_map.hashString(Self.name), pub const base_files = Project.baseFiles; pub const src_files = Project.Config.srcFiles; pub const tmpl_dir = "../../res/ptmpl/"; pub fn init(a: Allocator, name: ?str, ty: ?Project.Type) @This() { const dir = if (name) |n| { const cwd = std.fs.cwd(); try cwd.makeDir(n); try cwd.openDir(n, .{ .iterate = true }) orelse cwd; } else std.fs.cwd(); if (try isProjectDir(dir)) { stderr().write("\x1b;33;1mProject exists!\x1b[0m"); return Project.fromConfig(dir); } return Project{ .title = name orelse util.promptLn(), .allocator = a, .dir = dir, .project_type = ty orelse .hybrid, }; } pub fn isProjectDir(dir: Dir) !bool { const project_file = std.fs.path.join(.{ dir, "idle.toml" }); var wdir = dir.walk(); while (try wdir.next()) |p| rdir: { std.debug.print("{s}\n", .{p.name}); if (std.mem.eql(u8, p, project_file)) { break :rdir true; } } return false; } pub fn setupGit(self: Self) !void { const giti = [_][]const u8{ "git", "init " }; const gcmd = try std.ChildProcess.init(giti, self.allocator); errdefer gcmd.deinit(); try gcmd.spawnAndWait(); } /// NOTE: Simply isProjectDir but with added terminal output pub fn checkProjectDir(dir: Dir) !bool { const isp = try Project.isProjectDir(dir); if (isp) stderr().write("\x1b;33;1mYou've already set up a project in this directory!\x1b[0m"); return isp; } /// NOTE: Creates full project structure in current working directory pub fn createBaseFiles(self: Project) anyerror!void { var src_files = self.baseFiles(); var files: [4]std.fs.File = .{}; for (src_files) |fname, i| { const tmpl_path = std.path.join(self.allocator, self.templ_dir_path, files[i]); const tmpl = @embedFile(tmpl_path); files[i] = try self.dir.createFile("{s}", .{fname}); try files[i].writeAll(tmpl); } try self.createSrcFiles(std.fs.cwd()); try self.createOutFiles(std.fs.cwd()); } /// pub fn createSrcFiles(self: Project) anyerror!void { const src_files = self.project_type.srcFiles(self.config_templ_name); const src_dir = try self.dir.makeOpenPath("src", .{}); var files: [src_files.len]std.fs.File = .{}; for (src_files) |fname, i| { const tmpl_path = std.fs.path.join(self.allocator, self.templ_dir_path, fname); const templ = @embedFile(tmpl_path); files[i] = try src_dir.writeFile(self.config_templ_name, templ); } } pub fn createOutFiles(self: Project, dir: Dir) anyerror!void { const rel_dir = try dir.makeOpenPath("release", .{}); const dbg_dir = try dir.makeOpenPath("debug", .{}); const pkg_dir = try dir.makeOpenPath("pkg", .{}); const cached = try dir.makeOpenPath("cache", .{}); } pub fn createInDir(self: Project) !void { const defaults_path = "../../res/new/"; const base_files = .{ "Idle.toml", ".gitignore", "README.md", "build.is" }; //Plus out dir var files: [4]std.fs.File = .{}; for (base_files) |fname| { const file: std.fs.File = try di.createFile("{s}", .{fname}); file.writeAll(@embedFile(std.fs.path.join(self.allocator, default_path, fname))); files[0] = file; } _ = try files[0].writeAll(@embedFile("../../res/new/Idle.toml")); _ = try files[1].writeAll(@embedFile("../../res/new/.gitignore")); _ = try files[2].writeAll(@embedFile("../../res/new/README.md")); _ = try files[3].writeAll(@embedFile("../../res/new/build.is")); _ = try di.makeDir("src"); _ = try di.makeDir("out"); _ = try di.writeFile(".gitignore", gignore_dft()); _ = try di.writeFile("build.is", build_dft()); try di.openDir("src", .{}); _ = try di.writeFile("main.is", main_default()); _ = try di.writeFile("lib.is", lib_default()); } pub fn baseFiles(self: Project) []str { return self.config_templ_name ++ .{ ".gitignore", "README.md", "build.is" }; //Plus out dir } pub const TemplateDir = union(Project.Type) { lib: str = "../res/templ/" }; pub const Type = enum(u8) { lib, bin, hybrid, exelib, pub fn toStr(self: @This()) str { return @tagName(self); } pub fn srcFiles(self: @This(), config: str) []str { return config ++ switch (self) { .hybrid => .{ "main.is", "lib.is" }, .bin => .{"main.is"}, .lib, .exelib => .{"lib.is"}, }; } }; // NOTE: Corresponds to the idle.json/idle.toml file at project root pub const Config = struct { const Self = @This(); name: []const u8, ftype: .json, author: str = "You", version: str = "0.1.0", edition: str = "2022", lib_name: str = "lib", bin_name: str = "main", bin_path: str = "./src/bin/main.rs", name: str = "example_mod", public: str = false, compile: str = false, pub const Ext = enum(u2) { json, toml, idconf, }; pub fn toJson(self: Project.Config) !str { return ""; } pub fn path(self: Ftype, a: Allocator) std.fs.File { const fstr: []const u8 = std.meta.tagName(self); const path = std.fs.path.join(a, [_]u8{ "../../res/", "" }); return path; } pub const Ftype = enum(u2) { const Self = @This(); json, yaml, toml, }; }; pub const Uid = struct { uid: str = gen: { const uid: str = undefined; std.rand.Random.bytes(&uid); break :gen uid; }, uid: [16]u8 = generator: { var uid: [16]u8 = undefined; std.rand.DefaultPrng.init(0).fill(&uid); break :generator uid; }, repo_id: ?[]const u8 = null, pub fn init() Project.Id { const uid: str = undefined; std.rand.Random.bytes(&uid); } }; /// Attempts to fetch a local handle to a project, knowing its /// uid, from the local package registry pub fn fromUid(uid: str) ?Project { return LocalRegistry.findUid(uid); } }; pub fn init_project(a: Allocator, dir: ?[]const u8) ![]const u8 { const di = try std.fs.cwd().openDir(path, .{ .iterate = true }); var walkdir = di.iterate(); const project_file = std.fs.path.join(.{ path, "idle.toml" }); while (try walkdir.next()) |p| rdir: { std.debug.print("{s}\n", .{p.name}); if (std.mem.eql(u8, p, project_file)) { std.io.getStdErr().write("\x1b;33;1mYou've already set up a project in this directory!\x1b[0m"); break :rdir project_file; } else { // const name = try std.io.getStdIn().reader().readUntilDelimiterOrEofAlloc(a, "\n", 2048); const proj = Project.init(a, null); // const giti = [_][]const u8{ "git", "init " }; // const gitg = [_][]const u8{ "touch", "./res/new/.gitignore" }; // const cpif = [_][]const u8{ "cp", "-r", "" }; // var proc = try std.ChildProcess.init(.{""}); std.io.getStdErr().write("\x1b;33;1mYou've already set up a project in this directory!\x1b[0m"); } } } pub fn init_workspace(a: Allocator, dir: ?[]const u8) ![]const u8 { const path = if (dir) |c| c else "."; const di = try std.fs.cwd().openDir(path, .{ .iterate = true }); var walkdir = di.iterate(); while (try walkdir.next()) |p| { std.debug.print("{s}\n", .{p.name}); } } pub fn gitignore_default() []u8 { const df = \\ **out \\ **Idle.lock \\ **.idle-cache \\ \\ **.env \\ **.prod.env \\ **.local.env ; } // A user's local, central repository for packages // downloaded from an online repository pub const LocalRegistry = struct { const Self = @This(); allocator: Allocator, dir: []const u8 = std.fs.getAppDataDir("idle") catch "~/.idle", projects: std.StringArrayHashMap(Project), len: usize = Self.dir.walk().len, pub fn default(a: Allocator) LocalRegistry { return LocalRegistry{ .allocator = allocator }; } pub fn find(uid: Project.Id) ?Project {} /// Contains pertinent meta info about projects locally downloaded /// or otherwise created in the local registry pub const Entry = struct { uid: PkgId, project: Project, source_repository: []const u8, }; pub const Error = error{ NoProjectWithId, AlreadyExists, InvalidDir, }; }; pub fn main() anyerror!void { std.log.info("All your codebase are belong to us.", .{}); } const expect = std.testing.expectEqual; test "Project.ConfigExt.toTemplate" { const pt: Project.Type = Project.Type.bin; const cf: Project.Config = Project.Config{}; try expect("idle.json.toml", try cf.ftype.toTemplate()); }
lib/idpm/src/main.zig
const builtin = @import("builtin"); const std = @import("../index.zig"); const math = std.math; const assert = std.debug.assert; pub fn tan(x: var) @typeOf(x) { const T = @typeOf(x); return switch (T) { f32 => tan32(x), f64 => tan64(x), else => @compileError("tan not implemented for " ++ @typeName(T)), }; } const Tp0 = -1.30936939181383777646E4; const Tp1 = 1.15351664838587416140E6; const Tp2 = -1.79565251976484877988E7; const Tq1 = 1.36812963470692954678E4; const Tq2 = -1.32089234440210967447E6; const Tq3 = 2.50083801823357915839E7; const Tq4 = -5.38695755929454629881E7; // NOTE: This is taken from the go stdlib. The musl implementation is much more complex. // // This may have slight differences on some edge cases and may need to replaced if so. fn tan32(x_: f32) f32 { @setFloatMode(this, @import("builtin").FloatMode.Strict); const pi4a = 7.85398125648498535156e-1; const pi4b = 3.77489470793079817668E-8; const pi4c = 2.69515142907905952645E-15; const m4pi = 1.273239544735162542821171882678754627704620361328125; var x = x_; if (x == 0 or math.isNan(x)) { return x; } if (math.isInf(x)) { return math.nan(f32); } var sign = false; if (x < 0) { x = -x; sign = true; } var y = math.floor(x * m4pi); var j = @floatToInt(i64, y); if (j & 1 == 1) { j += 1; y += 1; } const z = ((x - y * pi4a) - y * pi4b) - y * pi4c; const w = z * z; var r = r: { if (w > 1e-14) { break :r z + z * (w * ((Tp0 * w + Tp1) * w + Tp2) / ((((w + Tq1) * w + Tq2) * w + Tq3) * w + Tq4)); } else { break :r z; } }; if (j & 2 == 2) { r = -1 / r; } if (sign) { r = -r; } return r; } fn tan64(x_: f64) f64 { const pi4a = 7.85398125648498535156e-1; const pi4b = 3.77489470793079817668E-8; const pi4c = 2.69515142907905952645E-15; const m4pi = 1.273239544735162542821171882678754627704620361328125; var x = x_; if (x == 0 or math.isNan(x)) { return x; } if (math.isInf(x)) { return math.nan(f64); } var sign = false; if (x < 0) { x = -x; sign = true; } var y = math.floor(x * m4pi); var j = @floatToInt(i64, y); if (j & 1 == 1) { j += 1; y += 1; } const z = ((x - y * pi4a) - y * pi4b) - y * pi4c; const w = z * z; var r = r: { if (w > 1e-14) { break :r z + z * (w * ((Tp0 * w + Tp1) * w + Tp2) / ((((w + Tq1) * w + Tq2) * w + Tq3) * w + Tq4)); } else { break :r z; } }; if (j & 2 == 2) { r = -1 / r; } if (sign) { r = -r; } return r; } test "math.tan" { assert(tan(f32(0.0)) == tan32(0.0)); assert(tan(f64(0.0)) == tan64(0.0)); } test "math.tan32" { const epsilon = 0.000001; assert(math.approxEq(f32, tan32(0.0), 0.0, epsilon)); assert(math.approxEq(f32, tan32(0.2), 0.202710, epsilon)); assert(math.approxEq(f32, tan32(0.8923), 1.240422, epsilon)); assert(math.approxEq(f32, tan32(1.5), 14.101420, epsilon)); assert(math.approxEq(f32, tan32(37.45), -0.254397, epsilon)); assert(math.approxEq(f32, tan32(89.123), 2.285852, epsilon)); } test "math.tan64" { const epsilon = 0.000001; assert(math.approxEq(f64, tan64(0.0), 0.0, epsilon)); assert(math.approxEq(f64, tan64(0.2), 0.202710, epsilon)); assert(math.approxEq(f64, tan64(0.8923), 1.240422, epsilon)); assert(math.approxEq(f64, tan64(1.5), 14.101420, epsilon)); assert(math.approxEq(f64, tan64(37.45), -0.254397, epsilon)); assert(math.approxEq(f64, tan64(89.123), 2.2858376, epsilon)); } test "math.tan32.special" { assert(tan32(0.0) == 0.0); assert(tan32(-0.0) == -0.0); assert(math.isNan(tan32(math.inf(f32)))); assert(math.isNan(tan32(-math.inf(f32)))); assert(math.isNan(tan32(math.nan(f32)))); } test "math.tan64.special" { assert(tan64(0.0) == 0.0); assert(tan64(-0.0) == -0.0); assert(math.isNan(tan64(math.inf(f64)))); assert(math.isNan(tan64(-math.inf(f64)))); assert(math.isNan(tan64(math.nan(f64)))); }
std/math/tan.zig
const aoc = @import("../aoc.zig"); const std = @import("std"); const Allocator = std.mem.Allocator; const BOARD_SIZE = 5; const Board = struct { numbers: std.AutoHashMap(u8, aoc.Coord), markings: std.AutoHashMap(aoc.Coord, void), fn init(allocator: Allocator) Board { return .{ .numbers = std.AutoHashMap(u8, aoc.Coord).init(allocator), .markings = std.AutoHashMap(aoc.Coord, void).init(allocator), }; } fn loadLine(self: *Board, line: []const u8, row: u8) !void { var tokens = std.mem.tokenize(u8, line, " "); var col: u8 = 0; while (tokens.next()) |token| { try self.numbers.put(try std.fmt.parseInt(u8, token, 10), .{ .row = row, .col = col }); col += 1; } } fn markAndCheckWin(self: *Board, number: u8) !bool { if (self.numbers.get(number)) |coord| { try self.markings.putNoClobber(coord, {}); blk: { var idx: u8 = 0; while (idx < BOARD_SIZE) : (idx += 1) { if (!self.markings.contains(.{ .row = coord.row, .col = idx })) { break :blk; } } return true; } blk: { var idx: u8 = 0; while (idx < BOARD_SIZE) : (idx += 1) { if (!self.markings.contains(.{ .row = idx, .col = coord.col })) { break :blk; } } return true; } } return false; } fn sumUnmarked(self: *const Board) usize { var sum: usize = 0; var iter = self.numbers.iterator(); while (iter.next()) |kv| { if (!self.markings.contains(kv.value_ptr.*)) { sum += kv.key_ptr.*; } } return sum; } }; pub fn run(problem: *aoc.Problem) !aoc.Solution { var arena = std.heap.ArenaAllocator.init(problem.allocator); defer arena.deinit(); const numbers = problem.line().?; var boards = std.AutoHashMap(*Board, void).init(arena.allocator()); while (problem.line()) |line| { var kv = try boards.getOrPutValue(try arena.allocator().create(Board), {}); kv.key_ptr.*.* = Board.init(arena.allocator()); try kv.key_ptr.*.loadLine(line, 0); var line_num: u8 = 1; while (line_num < BOARD_SIZE) : (line_num += 1) { try kv.key_ptr.*.loadLine(problem.line().?, line_num); } } var s1: ?usize = null; var s2 = blk: { var tokens = std.mem.tokenize(u8, numbers, ","); while (tokens.next()) |token| { const last_called = try std.fmt.parseInt(u8, token, 10); const winning_boards = try getWinningBoards(arena.allocator(), boards.keyIterator(), last_called); for (winning_boards) |wb| { _ = boards.remove(wb); } if (winning_boards.len == 1 and s1 == null) { s1 = winning_boards[0].sumUnmarked() * last_called; } else if (boards.count() == 0) { break :blk winning_boards[0].sumUnmarked() * last_called; } } std.debug.print("s1 = {}, boards remain = {}\n", .{s1, boards.count()}); unreachable; }; return problem.solution(s1.?, s2); } fn getWinningBoards(allocator: Allocator, board_iter_const: std.AutoHashMap(*Board, void).KeyIterator, last_called: u8) ![]*Board { var winning_boards = std.ArrayList(*Board).init(allocator); var board_iter = board_iter_const; while (board_iter.next()) |board| { if (try board.*.markAndCheckWin(last_called)) { try winning_boards.append(board.*); } } return winning_boards.items; }
src/main/zig/2021/day04.zig
const std = @import("std"); const concepts = @import("../../lib.zig").concepts; const concept = "getty.de.dbt"; pub fn @"getty.de.dbt"(comptime dbt: anytype) void { const T = if (@TypeOf(dbt) == type) dbt else @TypeOf(dbt); const info = @typeInfo(T); comptime { if (info == .Struct and info.Struct.is_tuple) { inline for (std.meta.fields(T)) |field| { const db = @field(dbt, field.name); if (@TypeOf(db) != type) { concepts.err(concept, "found non-namespace Deserialization Block"); } switch (@typeInfo(db)) { .Struct => |db_info| { if (db_info.is_tuple) { concepts.err(concept, "found non-namespace Deserialization Block"); } if (db_info.fields.len != 0) { concepts.err(concept, "found field in Deserialization Block"); } inline for (.{ "is", "deserialize", "Visitor" }) |func| { if (!std.meta.trait.hasFunctions(db, .{func})) { concepts.err(concept, "missing `" ++ func ++ "` function in Deserialization Block"); } } }, else => concepts.err(concept, "found non-namespace Deserialization Block"), } } } else { if (info != .Struct or info.Struct.is_tuple) { concepts.err(concept, "found non-namespace Deserialization Block"); } if (info.Struct.fields.len != 0) { concepts.err(concept, "found field in Deserialization Block"); } inline for (.{ "is", "deserialize", "Visitor" }) |func| { if (!std.meta.trait.hasFunctions(T, .{func})) { concepts.err(concept, "missing `" ++ func ++ "` function in Deserialization Block"); } } } } }
src/de/concept/dbt.zig
const std = @import("std"); const input = @import("input.zig"); pub fn run(allocator: std.mem.Allocator, stdout: anytype) anyerror!void { { var input_ = try input.readFile("inputs/day21"); defer input_.deinit(); const result = try part1(&input_); try stdout.print("21a: {}\n", .{ result }); std.debug.assert(result == 864900); } { var input_ = try input.readFile("inputs/day21"); defer input_.deinit(); const result = try part2(allocator, &input_); try stdout.print("21b: {}\n", .{ result }); std.debug.assert(result == 575111835924670); } } const max_position = 10; const Position = std.math.IntFittingRange(1, max_position); const num_dice_rolled_per_turn = 3; fn Score(comptime max_score: comptime_int) type { return std.math.IntFittingRange(0, max_score + max_position); } fn part1(input_: anytype) !u64 { const max_dice_roll = 100; const max_score = 1000; var player1_pos: Position = player1_pos: { const line = (try input_.next()) orelse return error.InvalidInput; break :player1_pos try std.fmt.parseInt(Position, &[_]u8 { line[line.len - 1] }, 10); }; var player1_score: Score(max_score) = 0; var player2_pos: Position = player2_pos: { const line = (try input_.next()) orelse return error.InvalidInput; break :player2_pos try std.fmt.parseInt(Position, &[_]u8 { line[line.len - 1] }, 10); }; var player2_score: Score(max_score) = 0; var num_dice_rolls: usize = 0; const losing_player_score = losing_player_score: while (true) { { var roll_i: usize = 0; while (roll_i < num_dice_rolled_per_turn) : (roll_i += 1) { const roll = part1_roll_dice(max_dice_roll, &num_dice_rolls); player1_pos = movePlayer(max_dice_roll, player1_pos, roll); } } player1_score += player1_pos; if (player1_score >= max_score) { break :losing_player_score player2_score; } { var roll_i: usize = 0; while (roll_i < num_dice_rolled_per_turn) : (roll_i += 1) { const roll = part1_roll_dice(max_dice_roll, &num_dice_rolls); player2_pos = movePlayer(max_dice_roll, player2_pos, roll); } } player2_score += player2_pos; if (player2_score >= max_score) { break :losing_player_score player1_score; } } else { unreachable; }; return num_dice_rolls * losing_player_score; } fn part1_roll_dice( comptime max_dice_roll: comptime_int, num_rolls: *usize, ) std.math.IntFittingRange(1, max_dice_roll) { const roll = num_rolls.* % max_dice_roll + 1; num_rolls.* += 1; return @intCast(std.math.IntFittingRange(1, max_dice_roll), roll); } fn part2(allocator: std.mem.Allocator, input_: anytype) !usize { const max_dice_roll = 3; const max_score = 21; var player1_pos: Position = player1_pos: { const line = (try input_.next()) orelse return error.InvalidInput; break :player1_pos try std.fmt.parseInt(Position, &[_]u8 { line[line.len - 1] }, 10); }; var player1_score: Score(max_score) = 0; var player2_pos: Position = player2_pos: { const line = (try input_.next()) orelse return error.InvalidInput; break :player2_pos try std.fmt.parseInt(Position, &[_]u8 { line[line.len - 1] }, 10); }; var player2_score: Score(max_score) = 0; var universes = Universes(max_score).init(allocator); defer universes.deinit(); const num_victories = try part2_inner( max_dice_roll, max_score, .{ .player1_pos = player1_pos, .player1_score = player1_score, .player2_pos = player2_pos, .player2_score = player2_score, }, &universes, ); return std.math.max(num_victories.player1, num_victories.player2); } fn Universe(comptime max_score: comptime_int) type { return struct { player1_pos: Position, player1_score: Score(max_score), player2_pos: Position, player2_score: Score(max_score), }; } const NumVictories = struct { player1: usize, player2: usize, }; fn Universes(comptime max_score: comptime_int) type { return std.AutoHashMap(Universe(max_score), NumVictories); } fn part2_dice_rolls(comptime max_dice_roll: comptime_int) [1 + max_dice_roll * num_dice_rolled_per_turn]usize { var result = [_]usize { 0 } ** (1 + max_dice_roll * num_dice_rolled_per_turn); result[0] = 1; comptime var roll_i = 1; inline while (roll_i <= num_dice_rolled_per_turn) : (roll_i += 1) { var new_result = [_]usize { 0 } ** (1 + max_dice_roll * num_dice_rolled_per_turn); comptime var roll_j = 1; inline while (roll_j <= max_dice_roll) : (roll_j += 1) { comptime var prev_i = 0; inline while (prev_i <= max_dice_roll * (roll_i - 1)) : (prev_i += 1) { new_result[prev_i + roll_j] += result[prev_i]; } } result = new_result; } return result; } fn part2_inner( comptime max_dice_roll: comptime_int, comptime max_score: comptime_int, universe: Universe(max_score), universes: *Universes(max_score), ) @TypeOf(universes.allocator).Error!NumVictories { const DiceRoll = std.math.IntFittingRange(1 * num_dice_rolled_per_turn, max_dice_roll * num_dice_rolled_per_turn); if (universes.get(universe)) |num_victories| { return num_victories; } var num_victories = NumVictories { .player1 = 0, .player2 = 0, }; for (part2_dice_rolls(max_dice_roll)) |dice1_count, dice1_roll_| { if (dice1_count == 0) { continue; } const dice1_roll = @intCast(DiceRoll, dice1_roll_); var player1_pos_new = movePlayer(max_dice_roll * num_dice_rolled_per_turn, universe.player1_pos, dice1_roll); var player1_score_new = universe.player1_score + player1_pos_new; if (player1_score_new >= max_score) { num_victories.player1 += dice1_count; continue; } for (part2_dice_rolls(max_dice_roll)) |dice2_count, dice2_roll_| { if (dice2_count == 0) { continue; } const dice2_roll = @intCast(DiceRoll, dice2_roll_); var player2_pos_new = movePlayer(max_dice_roll * num_dice_rolled_per_turn, universe.player2_pos, dice2_roll); var player2_score_new = universe.player2_score + player2_pos_new; if (player2_score_new >= max_score) { num_victories.player2 += dice2_count; continue; } const sub_num_victories = try part2_inner( max_dice_roll, max_score, .{ .player1_pos = player1_pos_new, .player1_score = player1_score_new, .player2_pos = player2_pos_new, .player2_score = player2_score_new, }, universes, ); num_victories.player1 += sub_num_victories.player1 * dice1_count * dice2_count; num_victories.player2 += sub_num_victories.player2 * dice1_count * dice2_count; } } const entry = try universes.getOrPutValue(universe, .{ .player1 = 0, .player2 = 0 }); entry.value_ptr.player1 += num_victories.player1; entry.value_ptr.player2 += num_victories.player2; return num_victories; } fn movePlayer( comptime max_dice_roll: comptime_int, pos: Position, roll: std.math.IntFittingRange(1, max_dice_roll), ) Position { const TempPosition = std.math.IntFittingRange(0, std.math.max(max_position, max_position - 1 + max_dice_roll)); const temp_pos: TempPosition = pos - 1; const new_temp_pos: TempPosition = ((temp_pos + roll) % max_position) + 1; return @intCast(Position, new_temp_pos); } test "day 21 example 1" { const input_ = \\Player 1 starting position: 4 \\Player 2 starting position: 8 ; try std.testing.expectEqual(@as(u64, 745 * 993), try part1(&input.readString(input_))); try std.testing.expectEqual(@as(usize, std.math.max(444356092776315, 341960390180808)), try part2(std.testing.allocator, &input.readString(input_))); }
src/day21.zig
const m = @import("bits.zig"); const std = @import("std"); const c = @cImport({ @cInclude("lib/zig_ssl_config.h"); @cInclude("mbedtls/entropy.h"); @cInclude("mbedtls/ctr_drbg.h"); @cInclude("mbedtls/net_sockets.h"); @cInclude("mbedtls/ssl.h"); @cInclude("mbedtls/x509.h"); @cInclude("mbedtls/debug.h"); }); const os = std.os; const io = std.io; const Allocator = std.mem.Allocator; const expectEqual = std.testing.expectEqual; const expectError = std.testing.expectError; const expect = std.testing.expect; const assert = std.debug.assert; pub const mbedTLS = struct { server_fd: *c.mbedtls_net_context, ssl_conf: *c.mbedtls_ssl_config, ssl: *c.mbedtls_ssl_context, entropy: *c.mbedtls_entropy_context, drbg: *c.mbedtls_ctr_drbg_context, ca_chain: *c.mbedtls_x509_crt, entropyfn: @TypeOf(c.mbedtls_entropy_func), allocator: Allocator, pub fn init(allocator: Allocator) !mbedTLS { var net_ctx = try allocator.create(c.mbedtls_net_context); var entropy_ctx = try allocator.create(c.mbedtls_entropy_context); var ssl_config = c.zmbedtls_ssl_config_alloc(); var ssl_ctx = try allocator.create(c.mbedtls_ssl_context); var drbg_ctx = try allocator.create(c.mbedtls_ctr_drbg_context); var ca_chain = try allocator.create(c.mbedtls_x509_crt); c.mbedtls_net_init(net_ctx); c.mbedtls_entropy_init(entropy_ctx); c.mbedtls_ssl_init(ssl_ctx); c.zmbedtls_ssl_config_init(ssl_config); c.mbedtls_ctr_drbg_init(drbg_ctx); c.mbedtls_x509_crt_init(ca_chain); return mbedTLS{ .server_fd = net_ctx, .entropy = entropy_ctx, .ssl = ssl_ctx, .ssl_conf = @ptrCast(*c.mbedtls_ssl_config, ssl_config), .drbg = drbg_ctx, .ca_chain = ca_chain, .entropyfn = c.mbedtls_entropy_func, .allocator = allocator }; } const X509Error = error{ AllocationFailed, BadInputData, FileIoError, OutOfMemory, }; pub fn x509CrtParseFile(self: *mbedTLS, cafile: []const u8) X509Error!void { const rc = c.mbedtls_x509_crt_parse_file(self.ca_chain, &cafile[0]); switch (rc) { 0 => {}, m.MBEDTLS_ERR_PK_ALLOC_FAILED => return error.AllocationFailed, m.MBEDTLS_ERR_PK_BAD_INPUT_DATA => return error.BadInputData, m.MBEDTLS_ERR_PK_FILE_IO_ERROR => return error.FileIoError, else => unreachable, } } pub const Proto = enum(u2) { TCP, UDP }; const ConnError = error{ Corruption, UnknownHost, SocketFailed, ConnectionFailed, OutOfMemory }; pub fn netConnect(self: *mbedTLS, host: [*]const u8, port: [*]const u8, proto: Proto) ConnError!void { const rc = c.mbedtls_net_connect(self.server_fd, host, port, @enumToInt(proto)); switch (rc) { 0 => {}, m.MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED => return error.Corruption, m.MBEDTLS_ERR_NET_UNKNOWN_HOST => return error.UnknownHost, m.MBEDTLS_ERR_NET_SOCKET_FAILED => return error.SocketFailed, m.MBEDTLS_ERR_NET_CONNECT_FAILED => return error.ConnectionFailed, else => unreachable, } } pub const SSLEndpoint = enum(u2) { IS_CLIENT, IS_SERVER }; pub const SSLPreset = enum(u2) { DEFAULT, SUITEB }; const SSLConfigError = error{ Corruption, BadInputData }; pub fn sslConfDefaults(self: *mbedTLS, ep: SSLEndpoint, pro: Proto, pre: SSLPreset) SSLConfigError!void { const rc = switch (pre) { .SUITEB => c.mbedtls_ssl_config_defaults(self.ssl_conf, @enumToInt(ep), @enumToInt(pro), m.MBEDTLS_SSL_PRESET_SUITEB), .DEFAULT => c.mbedtls_ssl_config_defaults(self.ssl_conf, @enumToInt(ep), @enumToInt(pro), m.MBEDTLS_SSL_PRESET_DEFAULT), }; switch (rc) { 0 => {}, m.MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED => return error.Corruption, m.MBEDTLS_ERR_MPI_BAD_INPUT_DATA => return error.BadInputData, else => unreachable, } } pub const SSLVerify = enum(u2) { NONE, OPTIONAL, REQUIRED }; pub fn sslConfAuthmode(self: *mbedTLS, verify: SSLVerify) void { c.mbedtls_ssl_conf_authmode(self.ssl_conf, @enumToInt(verify)); } const rng_cb = fn (?*anyopaque, [*c]u8, usize) callconv(.C) c_int; pub fn sslConfRng(self: *mbedTLS, f_rng: ?rng_cb) void { if (f_rng) |cb| { c.mbedtls_ssl_conf_rng(self.ssl_conf, cb, self.drbg); } else { c.mbedtls_ssl_conf_rng(self.ssl_conf, c.mbedtls_ctr_drbg_random, self.drbg); } } fn dbgfn(ctx: ?*anyopaque, level: c_int, file: [*c]const u8, line: c_int, str: [*c]const u8) callconv(.C) void { _ = ctx; _ = level; std.debug.print("{s}:{}: {s}", .{ file, line, str }); } const debug_fn = fn (?*anyopaque, c_int, [*c]const u8, c_int, [*c]const u8) callconv(.C) void; pub fn setConfDebug(self: *mbedTLS, debug: ?debug_fn) void { var stdout = io.getStdOut().handle; if (debug) |dbg| { c.mbedtls_ssl_conf_dbg(self.ssl_conf, dbg, &stdout); } else { c.mbedtls_ssl_conf_dbg(self.ssl_conf, dbgfn, &stdout); } } pub fn sslConfCaChain(self: *mbedTLS, ca_chain: ?*c.mbedtls_x509_crt) void { // TODO: Add CRL support if (ca_chain) |ca| { c.mbedtls_ssl_conf_ca_chain(self.ssl_conf, ca, 0); } else { c.mbedtls_ssl_conf_ca_chain(self.ssl_conf, self.ca_chain, 0); } } const SSLSetupError = error{ OutOfMemory, Corruption }; pub fn sslSetup(self: *mbedTLS) SSLSetupError!void { const rc = c.mbedtls_ssl_setup(self.ssl, self.ssl_conf); switch (rc) { 0 => {}, m.MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED => return error.Corruption, m.MBEDTLS_ERR_SSL_ALLOC_FAILED => return error.OutOfMemory, else => unreachable, } } pub fn sslSetBIO(self: *mbedTLS) void { c.mbedtls_ssl_set_bio(self.ssl, self.server_fd, c.mbedtls_net_send, c.mbedtls_net_recv, null); } const SSLHandshakeError = error{ Success, WantWrite, WantRead, Corruption, BadInputData, FeatureUnavailable, CipherBadInputData, CipherHardwareAccelFailed, CipherFeatureUnavailable, CipherInvalidContext, InvalidContext, ConnectionReset, SendFailed, HardwareAccelFailed, CompressionFailed, BufferTooSmall }; pub fn sslHandshake(self: *mbedTLS) SSLHandshakeError!bool { const rc = c.mbedtls_ssl_handshake(self.ssl); return switch (rc) { m.MBEDTLS_ERR_SSL_WANT_WRITE => error.WantWrite, m.MBEDTLS_ERR_SSL_WANT_READ => error.WantRead, m.MBEDTLS_ERR_SSL_BAD_INPUT_DATA => error.BadInputData, m.MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE => error.FeatureUnavailable, m.MBEDTLS_ERR_NET_INVALID_CONTEXT => error.InvalidContext, m.MBEDTLS_ERR_NET_CONN_RESET => error.ConnectionReset, m.MBEDTLS_ERR_NET_SEND_FAILED => error.SendFailed, m.MBEDTLS_ERR_SSL_HW_ACCEL_FAILED => error.HardwareAccelFailed, m.MBEDTLS_ERR_SSL_COMPRESSION_FAILED => error.CompressionFailed, m.MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL => error.BufferTooSmall, else => return true, }; } const SSLHostnameError = error{ BadInputData, OutOfMemory }; pub fn setHostname(self: *mbedTLS, hostname: []const u8) SSLHostnameError!void { const rc = c.mbedtls_ssl_set_hostname(self.ssl, hostname.ptr); switch (rc) { 0 => {}, m.MBEDTLS_ERR_SSL_BAD_INPUT_DATA => return error.BadInputData, m.MBEDTLS_ERR_SSL_ALLOC_FAILED => return error.OutOfMemory, else => unreachable, } } const SeedError = error{ GenericError, Corruption, BadInputData, InvalidKeyLength, InvalidInputLength, OutOfMemory }; pub fn ctrDrbgSeed(self: *mbedTLS, additional: ?[]const u8) SeedError!void { var rc: c_int = 1; if (additional) |str| { rc = c.mbedtls_ctr_drbg_seed(self.drbg, self.entropyfn, self.entropy, str.ptr, str.len); } else { rc = c.mbedtls_ctr_drbg_seed(self.drbg, self.entropyfn, self.entropy, 0x0, 0x0); } switch (rc) { 0 => {}, m.MBEDTLS_ERR_ERROR_GENERIC_ERROR => return error.GenericError, m.MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED => return error.Corruption, m.MBEDTLS_ERR_AES_BAD_INPUT_DATA => return error.BadInputData, m.MBEDTLS_ERR_AES_INVALID_KEY_LENGTH => return error.InvalidKeyLength, m.MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH => return error.InvalidInputLength, else => unreachable, } } pub const SSLWriteError = error{ Corruption, BadInputData, FeatureUnavailable, WantWrite, WantRead }; pub fn sslWrite(self: *mbedTLS, str: []const u8) SSLWriteError!i32 { const rc = c.mbedtls_ssl_write(self.ssl, str.ptr, str.len); return switch (rc) { m.MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED => error.Corruption, m.MBEDTLS_ERR_SSL_BAD_INPUT_DATA => error.BadInputData, m.MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE => error.FeatureUnavailable, m.MBEDTLS_ERR_SSL_WANT_WRITE => error.WantWrite, m.MBEDTLS_ERR_SSL_WANT_READ => error.WantRead, else => rc, }; } pub const SSLReadError = error{ Corruption, BadInputData, FeatureUnavailable, WantWrite, WantRead, PeerCloseNotify }; pub fn sslRead(self: *mbedTLS, buffer: []u8) SSLReadError!i32 { const rc = c.mbedtls_ssl_read(self.ssl, buffer.ptr, buffer.len); return switch (rc) { m.MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED => error.Corruption, m.MBEDTLS_ERR_SSL_BAD_INPUT_DATA => error.BadInputData, m.MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE => error.FeatureUnavailable, m.MBEDTLS_ERR_SSL_WANT_WRITE => error.WantWrite, m.MBEDTLS_ERR_SSL_WANT_READ => error.WantRead, m.MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY => error.PeerCloseNotify, else => rc, }; } pub fn deinit(self: *mbedTLS) void { c.mbedtls_net_close(self.server_fd); c.zmbedtls_ssl_config_free(self.ssl_conf); self.allocator.destroy(self.server_fd); self.allocator.destroy(self.entropy); self.allocator.destroy(self.ssl); self.allocator.destroy(self.drbg); self.allocator.destroy(self.ca_chain); self.* = undefined; } }; const ArenaAllocator = std.heap.ArenaAllocator; const PageAllocator = std.heap.page_allocator; var arena = ArenaAllocator.init(PageAllocator); test "initialize mbedtls" { var mbed = try mbedTLS.init(&arena.allocator); defer mbed.deinit(); expectEqual(@as(c_int, -1), mbed.server_fd.fd); } test "load certificate file" { const cafile = "cacert.pem"; var mbed = try mbedTLS.init(&arena.allocator); defer mbed.deinit(); expectEqual(@as(c_int, 0), mbed.ca_chain.*.version); try mbed.x509CrtParseFile(cafile); expectEqual(@as(c_int, 3), mbed.ca_chain.*.version); } test "run seed function" { var mbed = try mbedTLS.init(&arena.allocator); defer mbed.deinit(); expectEqual(mbed.drbg.entropy_len, 0); // Check that it works with additional data and without try mbed.ctrDrbgSeed(null); try mbed.ctrDrbgSeed("SampleDevice"); expectEqual(mbed.drbg.entropy_len, 48); } test "connect to host" { const cafile = "cacert.pem"; var mbed = try mbedTLS.init(&arena.allocator); defer mbed.deinit(); try mbed.x509CrtParseFile(cafile); try mbed.ctrDrbgSeed("SampleDevice"); expectError(error.UnknownHost, mbed.netConnect("google.zom", "443", mbedTLS.Proto.TCP)); expectEqual(mbed.server_fd.fd, -1); try mbed.netConnect("google.com", "443", mbedTLS.Proto.TCP); expect(mbed.server_fd.fd > -1); } test "set hostname" { var mbed = try mbedTLS.init(&arena.allocator); defer mbed.deinit(); const excessive = \\ qiqQuz2BRgENxEBUhbMTp0bimui7axuo7jy4WNbopNrNnWSkypugXLNFeionxlwAUhSxlMkVsyc6VGmRTz0gUG \\ A3KRDbPCUBPiM7JsdgpI7rLP8EakT5cok2gF6KkAeVr7gfHNdg4auaEDHQfcp5OcLPIQnlVzt4OWSvRl2cOX3G \\ V8haOdljSwnmptEWSwFWe2FVsj0s8orr5JGNi91kLrTTpPzaXSoClrGTuireAlLaGExuer1Ue7LAAypC2FWV" ; expectError(error.BadInputData, mbed.setHostname(excessive)); } test "can write a request" { const cafile = "cacert.pem"; var mbed = try mbedTLS.init(&arena.allocator); defer mbed.deinit(); try mbed.x509CrtParseFile(cafile); try mbed.ctrDrbgSeed("SampleDevice"); try mbed.netConnect("google.com", "443", mbedTLS.Proto.TCP); try mbed.setHostname("zig-mbedtls"); const req = "GET / HTTP/1.1\r\nHost: google.com\r\nConnection: close\r\n\r\n"; const ret = try mbed.sslWrite(req); expect(ret > 0); } // This test is very sketchy and will break on any ssl_conf struct changes in // mbedTLS. Disable if too much hassle too maintain test "set ssl defaults and presets" { const Preset = mbedTLS.SSLPreset; const Endpoint = mbedTLS.SSLEndpoint; const Proto = mbedTLS.Proto; var mbed = try mbedTLS.init(&arena.allocator); defer mbed.deinit(); // We cant access these by field since the struct is opaque // These entries in the struct is on memory address 0x170 after base // If 0x00500000 is the base address, then: // 0x100500170: 3 == unsigned char max_major_ver; // 0x100500171: 3 == unsigned char max_minor_ver; // 0x100500172: 3 == unsigned char min_major_ver; // 0x100500173: 1 == unsigned char min_minor_ver; const memaddr: usize = @ptrToInt(mbed.ssl_conf); const max_major_ver: *u2 = @intToPtr(*align(1) u2, memaddr + 0x170); const max_minor_ver: *u2 = @intToPtr(*align(1) u2, memaddr + 0x171); const min_major_ver: *u2 = @intToPtr(*align(1) u2, memaddr + 0x172); const min_minor_ver: *u2 = @intToPtr(*align(1) u2, memaddr + 0x173); expect(0 == max_major_ver.*); expect(0 == max_minor_ver.*); expect(0 == min_major_ver.*); expect(0 == min_minor_ver.*); try mbed.sslConfDefaults(Endpoint.IS_CLIENT, Proto.TCP, Preset.DEFAULT); expect(3 == max_major_ver.*); expect(3 == max_minor_ver.*); expect(3 == min_major_ver.*); expect(1 == min_minor_ver.*); } test "can do mbedtls_ssl_config workaround" { var a = c.zmbedtls_ssl_config_alloc(); c.zmbedtls_ssl_config_init(a); var b = c.zmbedtls_ssl_config_defaults(a, 0, 0, 0); expectEqual(@as(c_int, 0), b); c.zmbedtls_ssl_config_free(a); }
src/main.zig
const std = @import("std"); const testing = std.testing; pub const YieldResultTag = enum { result, end, }; pub fn YieldResult(comptime T: type) type { return union(YieldResultTag) { result: T, end, }; } pub const GeneratorYieldErrorset = error { EndOfIteration, }; /// An implementation of python style generators pub fn Generator(comptime Yield: type, comptime State: type) type { return struct { const Self = @This(); const GeneratorFunction = fn (*State) ?Yield; const Result = YieldResult(Yield); const Return = Yield; const UnderlyingState = State; /// The current state of the generator state: State, /// The function that transforms the state and returns the yield generationFunction: fn (*State) ?Yield, fn init(initialState: State, function: GeneratorFunction) Self { return Self { .state = initialState, .generationFunction = function, }; } fn deinit(self: *Self) void { self.state.deinit(); } fn next(self: *Self) Result { if (self.generationFunction(&self.state)) |value| { return Result {.result = value}; } else { return Result.end; } } fn nextValue(self: *Self) GeneratorYieldErrorset!Yield { if (self.generationFunction(&self.state)) |value| { return value; } else { return GeneratorYieldErrorset.EndOfIteration; } } fn nextOptional(self: *Self) ?Yield { return self.generationFunction(&self.state); } }; } fn returns_five(_: *void) ?i32 { return 5; } test "A simple generator" { const IntGenerator = Generator(i32, void); var theGenerator = IntGenerator.init({}, returns_five); var counter: i32 = 0; while (counter < 100) : (counter += 1) { switch (theGenerator.next()) { IntGenerator.Result.result => |yield| testing.expect(yield == 5), IntGenerator.Result.end => testing.expect(false), } } } test "A simple generator via nextValue" { const IntGenerator = Generator(i32, void); var theGenerator = IntGenerator.init({}, returns_five); var counter: i32 = 0; while (counter < 100) : (counter += 1) { var nextValue = try theGenerator.nextValue(); testing.expect(nextValue == 5); } } fn justReturnsNull(_: *void) ?i32 { return null; } test "A terminating generator" { const IntGenerator = Generator(i32, void); var theGenerator = IntGenerator.init({}, justReturnsNull); testing.expect( theGenerator.next() == IntGenerator.Result.end ); } test "A terminating generator" { const IntGenerator = Generator(i32, void); var theGenerator = IntGenerator.init({}, justReturnsNull); testing.expectError(GeneratorYieldErrorset.EndOfIteration, theGenerator.nextValue() ); } const SimpleState = struct { cur_value: i32, max_value: i32, fn next(self: *SimpleState) ?i32 { if (self.cur_value < self.max_value) { defer self.cur_value += 1; return self.cur_value; } else { return null; } } }; test "A generator with state" { const SimpleGenerator = Generator(i32,SimpleState); var initState = SimpleState { .cur_value = 0, .max_value = 3, }; var theGenerator = SimpleGenerator.init(initState, SimpleState.next); switch (theGenerator.next()) { SimpleGenerator.Result.result => |yield| testing.expect(yield == 0), SimpleGenerator.Result.end => testing.expect(false), } switch (theGenerator.next()) { SimpleGenerator.Result.result => |yield| testing.expect(yield == 1), SimpleGenerator.Result.end => testing.expect(false), } switch (theGenerator.next()) { SimpleGenerator.Result.result => |yield| testing.expect(yield == 2), SimpleGenerator.Result.end => testing.expect(false), } testing.expect( theGenerator.next() == SimpleGenerator.Result.end ); } fn CounterState(comptime T: type) type { return struct { const Self = @This(); current: T, step: T, fn init(start: T, step: T) Self { return Self { .current = start, .step = step, }; } fn next(self: *Self) ?T { defer self.current+=self.step; return self.current; } }; } fn Counter(comptime T: type) type { return Generator(T, CounterState(T)); } /// Creates a generator that returns evenly spaced values starting at /// `start` and increasing each return by `step` /// /// For example count(i32, 0, 1) would yield 0, 1, 2, 3, 4, 5, ... /// and count(i32, 10, 5) would yield 10, 15, 20, ... /// /// Note that this class will not provide any protection from overflow /// or underflow pub fn count(comptime T: type, start: T, step: T) Counter(T) { return Counter(T).init( CounterState(T).init(start, step), CounterState(T).next ); } test "Count no step" { var counter = count(u32, 0, 1); var cur: i32 = 0; while (cur < 100) : (cur += 1) { switch (counter.next()) { YieldResult(u32).result => |value| testing.expect(value == cur), else => testing.expect(false), } } } test "Counter with step" { var counter = count(u32, 0, 17); var cur: i32 = 0; while (cur < 100) : (cur += 1) { switch (counter.next()) { YieldResult(u32).result => |value| testing.expect(value == cur*17), else => testing.expect(false), } } } fn RepeaterState(comptime T: type) type { return struct { const Self = @This(); value: T, fn init(val: T) Self { return Self { .value = val, }; } fn next(self: *Self) ?T { return self.value; } }; } fn Repeater(comptime T: type) type { return Generator(T, RepeaterState(T)); } /// Returns a generator that will infinitely repeast the value `val` /// /// For example repeat(i32, 7) will yield 7, 7, 7, 7, ... fn repeat(comptime T: type, val: T) Repeater(T) { const repeaterState = RepeaterState(T).init(val); return Repeater(T).init(repeaterState, RepeaterState(T).next); } test "Repeater" { var theGenerator = repeat(i32, 7); var cur: i32 = 0; while (cur < 100) : (cur += 1) { var cur_value = try theGenerator.nextValue(); testing.expect(cur_value == 7); } } fn CyclerState(comptime T: type) type { return struct { const Self = @This(); data: []const T, curIndex: usize, fn init(data: []const T) Self { return Self { .data = data, .curIndex = 0, }; } fn next(self: *Self) ?T { defer self.curIndex += 1; return self.data[self.curIndex % self.data.len]; } }; } fn Cycler(comptime T: type) type { return Generator(T, CyclerState(T)); } /// This function does not take ownership over the passed arraylist /// for example cycle(u8, "abc") would yield 'a', 'b', 'c', 'a', 'b', 'c' pub fn cycle(comptime T: type, items: []const T) Cycler(T) { std.debug.assert(items.len > 0); return Cycler(T).init( CyclerState(T).init(items), CyclerState(T).next ); } test "Cycle" { const cycleItems = [_]i32{1, 2}; var theGenerator = cycle(i32, cycleItems[0..]); var cur: i32 = 0; while (cur < 100) : (cur += 1) { const firstValue = try theGenerator.nextValue(); testing.expect(firstValue == 1); const secondValue = try theGenerator.nextValue(); testing.expect(secondValue == 2); } } test "Cycle with string literal" { const cycleItems = "abc"; var theGenerator = cycle(u8, "abc"); var cur: i32 = 0; while (cur < 100) : (cur += 1) { const firstValue = try theGenerator.nextValue(); testing.expect(firstValue == 'a'); const secondValue = try theGenerator.nextValue(); testing.expect(secondValue == 'b'); const thirdValue = try theGenerator.nextValue(); testing.expect(thirdValue == 'c'); } } fn AccumulatorState(comptime T: type, comptime GenState: type) type { return struct { const Self = @This(); data: Generator(T, GenState), accumulatedTotal: ?T, /// Initialization can fail due to data being an empty generator fn init(data: Generator(T, GenState)) Self { return Self { .data = data, .accumulatedTotal = null, }; } fn next(self: *Self) ?T { var nextItemToSum = self.data.nextOptional(); if (nextItemToSum == null) return null; if (self.accumulatedTotal == null) { self.accumulatedTotal = nextItemToSum; } else { self.accumulatedTotal = self.accumulatedTotal.? + nextItemToSum.?; } return self.accumulatedTotal; } }; } fn Accumulator(comptime T: type, comptime GenState: type) type { return Generator(T, AccumulatorState(T, GenState)); } /// Yields the accumulation of a generator, the only requirement is that /// T supports operator +, note that this is a more specialized version /// of a `fold` operation /// /// example: /// var generator = repeat(i32, 2); /// var accumulator = /// accumulate(generator.Return, generator.UnderlyingState, generator); /// 2 == try accumulator.nextValue(); /// 4 == try accumulator.nextValue(); /// 6 == try accumulator.nextValue(); pub fn accumulate(comptime T: type, comptime GenState: type, data: Generator(T, GenState)) Accumulator(T, GenState) { return Accumulator(T, GenState).init( AccumulatorState(T, GenState).init(data), AccumulatorState(T, GenState).next ); } test "Accumulator sum 0 to 2" { var state = SimpleState { .cur_value = 0, .max_value = 3, }; var theGenerator = Generator(i32, SimpleState).init(state, SimpleState.next); var theAccumulator = accumulate(i32, SimpleState, theGenerator); var first = try theAccumulator.nextValue(); testing.expect(first == 0); var second = try theAccumulator.nextValue(); testing.expect(second == 1); var third = try theAccumulator.nextValue(); testing.expect(third == 3); var final = theAccumulator.next(); testing.expect(final == YieldResult(i32).end); }
src/itertools.zig
const xcb = @import("../xcb.zig"); pub const id = xcb.Extension{ .name = "Present", .global_id = 0 }; pub const Event = extern enum(c_uint) { @"ConfigureNotify" = 0, @"CompleteNotify" = 1, @"IdleNotify" = 2, @"RedirectNotify" = 3, }; pub const EventMask = extern enum(c_uint) { @"NoEvent" = 0, @"ConfigureNotify" = 1, @"CompleteNotify" = 2, @"IdleNotify" = 4, @"RedirectNotify" = 8, }; pub const Option = extern enum(c_uint) { @"None" = 0, @"Async" = 1, @"Copy" = 2, @"UST" = 4, }; pub const Capability = extern enum(c_uint) { @"None" = 0, @"Async" = 1, @"Fence" = 2, @"UST" = 4, }; pub const CompleteKind = extern enum(c_uint) { @"Pixmap" = 0, @"NotifyMSC" = 1, }; pub const CompleteMode = extern enum(c_uint) { @"Copy" = 0, @"Flip" = 1, @"Skip" = 2, }; /// @brief Notify pub const Notify = struct { @"window": xcb.WINDOW, @"serial": u32, }; /// @brief QueryVersioncookie pub const QueryVersioncookie = struct { sequence: c_uint, }; /// @brief QueryVersionRequest pub const QueryVersionRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 0, @"length": u16, @"major_version": u32, @"minor_version": u32, }; /// @brief QueryVersionReply pub const QueryVersionReply = struct { @"response_type": u8, @"pad0": u8, @"sequence": u16, @"length": u32, @"major_version": u32, @"minor_version": u32, }; /// @brief PixmapRequest pub const PixmapRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 1, @"length": u16, @"window": xcb.WINDOW, @"pixmap": xcb.PIXMAP, @"serial": u32, @"valid": xcb.xfixes.REGION, @"update": xcb.xfixes.REGION, @"x_off": i16, @"y_off": i16, @"target_crtc": xcb.randr.CRTC, @"wait_fence": xcb.sync.FENCE, @"idle_fence": xcb.sync.FENCE, @"options": u32, @"pad0": [4]u8, @"target_msc": u64, @"divisor": u64, @"remainder": u64, @"notifies": []const xcb.present.Notify, }; /// @brief NotifyMSCRequest pub const NotifyMSCRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 2, @"length": u16, @"window": xcb.WINDOW, @"serial": u32, @"pad0": [4]u8, @"target_msc": u64, @"divisor": u64, @"remainder": u64, }; pub const EVENT = u32; /// @brief SelectInputRequest pub const SelectInputRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 3, @"length": u16, @"eid": xcb.present.EVENT, @"window": xcb.WINDOW, @"event_mask": u32, }; /// @brief QueryCapabilitiescookie pub const QueryCapabilitiescookie = struct { sequence: c_uint, }; /// @brief QueryCapabilitiesRequest pub const QueryCapabilitiesRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 4, @"length": u16, @"target": u32, }; /// @brief QueryCapabilitiesReply pub const QueryCapabilitiesReply = struct { @"response_type": u8, @"pad0": u8, @"sequence": u16, @"length": u32, @"capabilities": u32, }; /// Opcode for Generic. pub const GenericOpcode = 0; /// @brief GenericEvent pub const GenericEvent = struct { @"response_type": u8, @"extension": u8, @"sequence": u16, @"length": u32, @"evtype": u16, @"pad0": [2]u8, @"event": xcb.present.EVENT, }; /// Opcode for ConfigureNotify. pub const ConfigureNotifyOpcode = 0; /// @brief ConfigureNotifyEvent pub const ConfigureNotifyEvent = struct { @"response_type": u8, @"extension": u8, @"sequence": u16, @"length": u32, @"event_type": u16, @"pad0": [2]u8, @"event": xcb.present.EVENT, @"window": xcb.WINDOW, @"x": i16, @"y": i16, @"width": u16, @"height": u16, @"off_x": i16, @"off_y": i16, @"full_sequence": u32, @"pixmap_width": u16, @"pixmap_height": u16, @"pixmap_flags": u32, }; /// Opcode for CompleteNotify. pub const CompleteNotifyOpcode = 1; /// @brief CompleteNotifyEvent pub const CompleteNotifyEvent = struct { @"response_type": u8, @"extension": u8, @"sequence": u16, @"length": u32, @"event_type": u16, @"kind": u8, @"mode": u8, @"event": xcb.present.EVENT, @"window": xcb.WINDOW, @"serial": u32, @"ust": u64, @"full_sequence": u32, @"msc": u64, }; /// Opcode for IdleNotify. pub const IdleNotifyOpcode = 2; /// @brief IdleNotifyEvent pub const IdleNotifyEvent = struct { @"response_type": u8, @"extension": u8, @"sequence": u16, @"length": u32, @"event_type": u16, @"pad0": [2]u8, @"event": xcb.present.EVENT, @"window": xcb.WINDOW, @"serial": u32, @"pixmap": xcb.PIXMAP, @"idle_fence": xcb.sync.FENCE, @"full_sequence": u32, }; /// Opcode for RedirectNotify. pub const RedirectNotifyOpcode = 3; /// @brief RedirectNotifyEvent pub const RedirectNotifyEvent = struct { @"response_type": u8, @"extension": u8, @"sequence": u16, @"length": u32, @"event_type": u16, @"update_window": u8, @"pad0": u8, @"event": xcb.present.EVENT, @"event_window": xcb.WINDOW, @"window": xcb.WINDOW, @"pixmap": xcb.PIXMAP, @"serial": u32, @"full_sequence": u32, @"valid_region": xcb.xfixes.REGION, @"update_region": xcb.xfixes.REGION, @"valid_rect": xcb.RECTANGLE, @"update_rect": xcb.RECTANGLE, @"x_off": i16, @"y_off": i16, @"target_crtc": xcb.randr.CRTC, @"wait_fence": xcb.sync.FENCE, @"idle_fence": xcb.sync.FENCE, @"options": u32, @"pad1": [4]u8, @"target_msc": u64, @"divisor": u64, @"remainder": u64, @"notifies": []xcb.present.Notify, }; test "" { @import("std").testing.refAllDecls(@This()); }
src/auto/present.zig
const std = @import("std"); const mem = std.mem; const net = std.net; const os = std.os; const IO = @import("tigerbeetle-io").IO; fn IoOpContext(comptime ResultType: type) type { return struct { frame: anyframe = undefined, result: ResultType = undefined, }; } const ClientHandler = struct { io: *IO, sock: os.socket_t, recv_buf: []u8, allocator: mem.Allocator, fn init(allocator: mem.Allocator, io: *IO, sock: os.socket_t) !*ClientHandler { var buf = try allocator.alloc(u8, 1024); var self = try allocator.create(ClientHandler); self.* = ClientHandler{ .io = io, .sock = sock, .recv_buf = buf, .allocator = allocator, }; return self; } fn deinit(self: *ClientHandler) !void { try close(self.io, self.sock); self.allocator.free(self.recv_buf); self.allocator.destroy(self); } fn start(self: *ClientHandler) !void { defer self.deinit() catch unreachable; // TODO: log error while (true) { const received = try recv(self.io, self.sock, self.recv_buf); if (received == 0) { return; } _ = try send(self.io, self.sock, self.recv_buf[0..received]); } } const SendContext = IoOpContext(IO.SendError!usize); fn send(io: *IO, sock: os.socket_t, buffer: []const u8) IO.SendError!usize { var ctx: IoOpContext(IO.SendError!usize) = undefined; var completion: IO.Completion = undefined; io.send( *SendContext, &ctx, sendCallback, &completion, sock, buffer, if (std.Target.current.os.tag == .linux) os.MSG_NOSIGNAL else 0, ); suspend { ctx.frame = @frame(); } return ctx.result; } fn sendCallback( ctx: *SendContext, completion: *IO.Completion, result: IO.SendError!usize, ) void { ctx.result = result; resume ctx.frame; } const RecvContext = IoOpContext(IO.RecvError!usize); fn recv(io: *IO, sock: os.socket_t, buffer: []u8) IO.RecvError!usize { var ctx: RecvContext = undefined; var completion: IO.Completion = undefined; io.recv( *RecvContext, &ctx, recvCallback, &completion, sock, buffer, if (std.Target.current.os.tag == .linux) os.MSG_NOSIGNAL else 0, ); suspend { ctx.frame = @frame(); } return ctx.result; } fn recvCallback( ctx: *RecvContext, completion: *IO.Completion, result: IO.RecvError!usize, ) void { ctx.result = result; resume ctx.frame; } const CloseContext = IoOpContext(IO.CloseError!void); fn close(io: *IO, sock: os.socket_t) IO.CloseError!void { var ctx: CloseContext = undefined; var completion: IO.Completion = undefined; io.close( *CloseContext, &ctx, closeCallback, &completion, sock, ); suspend { ctx.frame = @frame(); } return ctx.result; } fn closeCallback( ctx: *CloseContext, completion: *IO.Completion, result: IO.CloseError!void, ) void { ctx.result = result; resume ctx.frame; } }; const Server = struct { io: IO, server: os.socket_t, allocator: mem.Allocator, fn init(allocator: mem.Allocator, address: std.net.Address) !Server { const kernel_backlog = 1; const server = try os.socket(address.any.family, os.SOCK_STREAM | os.SOCK_CLOEXEC, 0); 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: Server = .{ .io = try IO.init(32, 0), .server = server, .allocator = allocator, }; return self; } pub fn deinit(self: *Server) void { os.close(self.server); self.io.deinit(); } pub fn start(self: *Server) !void { while (true) { const client_sock = try accept(&self.io, self.server, 0); var handler = try ClientHandler.init(self.allocator, &self.io, client_sock); try handler.start(); } } pub fn run(self: *Server) !void { while (true) try self.io.tick(); } const AcceptContext = IoOpContext(IO.AcceptError!os.socket_t); fn accept(io: *IO, server_sock: os.socket_t, flags: u32) IO.AcceptError!os.socket_t { var ctx: AcceptContext = undefined; var completion: IO.Completion = undefined; io.accept(*AcceptContext, &ctx, acceptCallback, &completion, server_sock, flags); suspend { ctx.frame = @frame(); } return ctx.result; } fn acceptCallback( ctx: *AcceptContext, completion: *IO.Completion, result: IO.AcceptError!os.socket_t, ) void { ctx.result = result; resume ctx.frame; } }; pub fn main() anyerror!void { const allocator = std.heap.page_allocator; const address = try std.net.Address.parseIp4("127.0.0.1", 3131); var server = try Server.init(allocator, address); defer server.deinit(); _ = async server.start(); try server.run(); }
examples/async_tcp_echo_server.zig
const std = @import("std"); const debug = std.debug; const allocator = std.heap.page_allocator; const Shader = @import("Shader.zig").Shader; const Mesh = @import("Mesh.zig").Mesh; const assimp = @import("AssImpInterface.zig"); const Camera = @import("Camera.zig").Camera; const mat4x4 = @import("../math/Mat4x4.zig"); const game = @import("../game/GameWorld.zig"); const GameWorld = @import("../game/GameWorld.zig").GameWorld; const filePathUtils = @import("../coreutil/FilePathUtils.zig"); usingnamespace @import("../c.zig"); var curShader: ?Shader = null; var curMesh: ?Mesh = null; var curMesh2: ?Mesh = null; var curCamera = Camera{}; var curTime: f32 = 0.0; var circleTime: f32 = 1.0 / (2.0 * std.math.pi); const circleRadius: f32 = 0.5; var imguiIO: ?*ImGuiIO = null; pub fn Initialize(renderer: *SDL_Renderer) void { glClearColor(0.1, 0.1, 0.2, 1.0); curShader = Shader.init("src\\shaders\\basic_mesh.vert", "src\\shaders\\basic_mesh.frag"); const meshPath = filePathUtils.CwdToAbsolute(allocator, "test-assets\\test.obj") catch |err| { @panic("!"); }; defer allocator.free(meshPath); if (assimp.ImportMesh(meshPath)) |mesh| { curMesh = mesh; } else |meshErr| { debug.warn("Error importing mesh: {}\n", .{meshErr}); } if (curMesh != null) { curMesh.?.PushDataToBuffers(); } else { debug.warn("No mesh, no data pushed to buffers!\n", .{}); } curMesh2 = curMesh; if (curMesh2 != null) { curMesh2.?.PushDataToBuffers(); } else { debug.warn("No mesh, no data pushed to buffers!\n", .{}); } curCamera.m_pos.z -= 2.0; const modelMat = mat4x4.identity; const viewMat = curCamera.GetViewMatrix(); const projectionMat = curCamera.GetProjectionMatrix(); debug.warn("Model matrix:\n", .{}); mat4x4.DebugLogMat4x4(&modelMat); debug.warn("View matrix:\n", .{}); mat4x4.DebugLogMat4x4(&viewMat); debug.warn("Projection matrix:\n", .{}); mat4x4.DebugLogMat4x4(&projectionMat); // imgui init imguiIO = igGetIO(); if (imguiIO) |io| { var text_pixels: [*c]u8 = undefined; var text_w: i32 = undefined; var text_h: i32 = undefined; ImFontAtlas_GetTexDataAsRGBA32(io.Fonts, &text_pixels, &text_w, &text_h, null); } else { @panic("imguiIO is null"); } } pub fn RenderFrame(renderer: *SDL_Renderer, screen: *SDL_Window, gameWorld: *const GameWorld) void { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); curTime += game.deltaTime; curCamera.m_pos.x = circleRadius * std.math.cos(curTime / (std.math.tau * circleTime)); curCamera.m_pos.y = circleRadius * std.math.sin(curTime / (std.math.tau * circleTime)); if (curMesh) |m| { if (curShader) |s| { m.Draw(&curCamera, s.gl_id); } } if (curMesh2) |m| { if (curShader) |s| { m.Draw(&curCamera, s.gl_id); } } //imgui update var window_w: i32 = undefined; var window_h: i32 = undefined; SDL_GetWindowSize(screen, &window_w, &window_h); if (imguiIO) |io| { io.DisplaySize.x = @intToFloat(f32, window_w); io.DisplaySize.y = @intToFloat(f32, window_h); io.DeltaTime = 1.0 / 60.0; } else { @panic("imguiIO is null"); } ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplSDL2_NewFrame(screen); igNewFrame(); igShowDemoWindow(null); igRender(); ImGui_ImplOpenGL3_RenderDrawData(igGetDrawData()); SDL_GL_SwapWindow(screen); }
src/presentation/Presentation.zig
const std = @import("std"); const c = @import("internal/c.zig"); const internal = @import("internal/internal.zig"); const log = std.log.scoped(.git); const git = @import("git.zig"); /// This type bundles all functionality that does not act on an instance of an object pub const Handle = struct { /// De-initialize the libraries global state. /// *NOTE*: should be called as many times as `init` was called. pub fn deinit(self: Handle) void { _ = self; log.debug("Handle.deinit called", .{}); const number = internal.wrapCallWithReturn("git_libgit2_shutdown", .{}) catch unreachable; if (number == 0) { log.debug("libgit2 shutdown successful", .{}); } else { log.debug("{} initializations have not been shutdown (after this one)", .{number}); } } /// Create a new bare Git index object as a memory representation of the Git index file in `path`, without a repository to /// back it. /// /// ## Parameters /// * `path` - The path to the index pub fn indexOpen(self: Handle, path: [:0]const u8) !*git.Index { _ = self; log.debug("Handle.indexOpen called, path: {s}", .{path}); var index: *git.Index = undefined; try internal.wrapCall("git_index_open", .{ @ptrCast(*?*c.git_index, &index), path.ptr, }); log.debug("index opened successfully", .{}); return index; } /// Create an in-memory index object. /// /// This index object cannot be read/written to the filesystem, but may be used to perform in-memory index operations. pub fn indexNew(self: Handle) !*git.Index { _ = self; log.debug("Handle.indexInit called", .{}); var index: *git.Index = undefined; try internal.wrapCall("git_index_new", .{ @ptrCast(*?*c.git_index, &index), }); log.debug("index created successfully", .{}); return index; } /// Create a new repository in the given directory. /// /// ## Parameters /// * `path` - The path to the repository /// * `is_bare` - If true, a Git repository without a working directory is created at the pointed path. /// If false, provided path will be considered as the working directory into which the .git directory will be /// created. pub fn repositoryInit(self: Handle, path: [:0]const u8, is_bare: bool) !*git.Repository { _ = self; log.debug("Handle.repositoryInit called, path: {s}, is_bare: {}", .{ path, is_bare }); var repo: *git.Repository = undefined; try internal.wrapCall("git_repository_init", .{ @ptrCast(*?*c.git_repository, &repo), path.ptr, @boolToInt(is_bare), }); log.debug("repository created successfully", .{}); return repo; } /// Create a new repository in the given directory with extended options. /// /// ## Parameters /// * `path` - The path to the repository /// * `options` - The options to use during the creation of the repository pub fn repositoryInitExtended(self: Handle, path: [:0]const u8, options: git.RepositoryInitOptions) !*git.Repository { _ = self; log.debug("Handle.repositoryInitExtended called, path: {s}, options: {}", .{ path, options }); var repo: *git.Repository = undefined; var c_options = internal.make_c_option.repositoryInitOptions(options); try internal.wrapCall("git_repository_init_ext", .{ @ptrCast(*?*c.git_repository, &repo), path.ptr, &c_options, }); log.debug("repository created successfully", .{}); return repo; } /// Open a repository. /// /// ## Parameters /// * `path` - The path to the repository pub fn repositoryOpen(self: Handle, path: [:0]const u8) !*git.Repository { _ = self; log.debug("Handle.repositoryOpen called, path: {s}", .{path}); var repo: *git.Repository = undefined; try internal.wrapCall("git_repository_open", .{ @ptrCast(*?*c.git_repository, &repo), path.ptr, }); log.debug("repository opened successfully", .{}); return repo; } /// Find and open a repository with extended options. /// /// *NOTE*: `path` can only be null if the `open_from_env` option is used. /// /// ## Parameters /// * `path` - The path to the repository /// * `flags` - Options controlling how the repository is opened /// * `ceiling_dirs` - A `path_list_separator` delimited list of path prefixes at which the search for a containing /// repository should terminate. pub fn repositoryOpenExtended( self: Handle, path: ?[:0]const u8, flags: git.RepositoryOpenOptions, ceiling_dirs: ?[:0]const u8, ) !*git.Repository { _ = self; log.debug("Handle.repositoryOpenExtended called, path: {s}, flags: {}, ceiling_dirs: {s}", .{ path, flags, ceiling_dirs }); var repo: *git.Repository = undefined; const path_temp = if (path) |slice| slice.ptr else null; const ceiling_dirs_temp = if (ceiling_dirs) |slice| slice.ptr else null; try internal.wrapCall("git_repository_open_ext", .{ @ptrCast(*?*c.git_repository, &repo), path_temp, flags.toInt(), ceiling_dirs_temp, }); log.debug("repository opened successfully", .{}); return repo; } /// Open a bare repository. /// /// ## Parameters /// * `path` - The path to the repository pub fn repositoryOpenBare(self: Handle, path: [:0]const u8) !*git.Repository { _ = self; log.debug("Handle.repositoryOpenBare called, path: {s}", .{path}); var repo: *git.Repository = undefined; try internal.wrapCall("git_repository_open_bare", .{ @ptrCast(*?*c.git_repository, &repo), path.ptr, }); log.debug("repository opened successfully", .{}); return repo; } /// Look for a git repository and return its path. /// /// The lookup starts from `start_path` and walks the directory tree until the first repository is found, or when reaching a /// directory referenced in `ceiling_dirs` or when the filesystem changes (when `across_fs` is false). /// /// ## Parameters /// * `start_path` - The path where the lookup starts. /// * `across_fs` - If true, then the lookup will not stop when a filesystem device change is encountered. /// * `ceiling_dirs` - A `path_list_separator` separated list of absolute symbolic link free paths. The lookup will stop /// when any of this paths is reached. pub fn repositoryDiscover(self: Handle, start_path: [:0]const u8, across_fs: bool, ceiling_dirs: ?[:0]const u8) !git.Buf { _ = self; log.debug( "Handle.repositoryDiscover called, start_path: {s}, across_fs: {}, ceiling_dirs: {s}", .{ start_path, across_fs, ceiling_dirs }, ); var buf: git.Buf = .{}; const ceiling_dirs_temp = if (ceiling_dirs) |slice| slice.ptr else null; try internal.wrapCall("git_repository_discover", .{ @ptrCast(*c.git_buf, &buf), start_path.ptr, @boolToInt(across_fs), ceiling_dirs_temp, }); log.debug("repository discovered - {s}", .{buf.toSlice()}); return buf; } /// Clone a remote repository. /// /// By default this creates its repository and initial remote to match git's defaults. /// You can use the options in the callback to customize how these are created. /// /// ## Parameters /// * `url` - URL of the remote repository to clone. /// * `local_path` - Directory to clone the repository into. /// * `options` - Customize how the repository is created. pub fn clone(self: Handle, url: [:0]const u8, local_path: [:0]const u8, options: CloneOptions) !*git.Repository { _ = self; log.debug("Handle.clone called, url: {s}, local_path: {s}", .{ url, local_path }); var repo: *git.Repository = undefined; const c_options = internal.make_c_option.cloneOptions(options); try internal.wrapCall("git_clone", .{ @ptrCast(*?*c.git_repository, &repo), url.ptr, local_path.ptr, &c_options, }); log.debug("repository cloned successfully", .{}); return repo; } pub fn optionGetMaximumMmapWindowSize(self: Handle) !usize { _ = self; log.debug("Handle.optionGetMmapWindowSize called", .{}); var result: usize = undefined; try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_GET_MWINDOW_SIZE, &result }); log.debug("maximum mmap window size: {}", .{result}); return result; } pub fn optionSetMaximumMmapWindowSize(self: Handle, value: usize) !void { _ = self; log.debug("Handle.optionSetMaximumMmapWindowSize called, value: {}", .{value}); try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_SET_MWINDOW_SIZE, value }); log.debug("successfully set maximum mmap window size", .{}); } pub fn optionGetMaximumMmapLimit(self: Handle) !usize { _ = self; log.debug("Handle.optionGetMaximumMmapLimit called", .{}); var result: usize = undefined; try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_GET_MWINDOW_MAPPED_LIMIT, &result }); log.debug("maximum mmap limit: {}", .{result}); return result; } pub fn optionSetMaximumMmapLimit(self: Handle, value: usize) !void { _ = self; log.debug("Handle.optionSetMaximumMmapLimit called, value: {}", .{value}); try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_SET_MWINDOW_MAPPED_LIMIT, value }); log.debug("successfully set maximum mmap limit", .{}); } /// zero means unlimited pub fn optionGetMaximumMappedFiles(self: Handle) !usize { _ = self; log.debug("Handle.optionGetMaximumMappedFiles called", .{}); var result: usize = undefined; try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_GET_MWINDOW_FILE_LIMIT, &result }); log.debug("maximum mapped files: {}", .{result}); return result; } /// zero means unlimited pub fn optionSetMaximumMmapFiles(self: Handle, value: usize) !void { _ = self; log.debug("Handle.optionSetMaximumMmapFiles called, value: {}", .{value}); try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_SET_MWINDOW_FILE_LIMIT, value }); log.debug("successfully set maximum mapped files", .{}); } pub fn optionGetSearchPath(self: Handle, level: git.ConfigLevel) !git.Buf { _ = self; log.debug("Handle.optionGetSearchPath called, level: {s}", .{@tagName(level)}); var buf: git.Buf = .{}; try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_GET_SEARCH_PATH, @enumToInt(level), @ptrCast(*c.git_buf, &buf), }); log.debug("got search path: {s}", .{buf.toSlice()}); return buf; } /// `path` should be a list of directories delimited by path_list_separator. /// Pass `null` to reset to the default (generally based on environment variables). Use magic path `$PATH` to include the old /// value of the path (if you want to prepend or append, for instance). pub fn optionSetSearchPath(self: Handle, level: git.ConfigLevel, path: ?[:0]const u8) !void { _ = self; log.debug("Handle.optionSetSearchPath called, path: {s}", .{path}); const path_c = if (path) |slice| slice.ptr else null; try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_SET_SEARCH_PATH, @enumToInt(level), path_c }); log.debug("successfully set search path", .{}); } pub fn optionSetCacheObjectLimit(self: Handle, object_type: git.ObjectType, value: usize) !void { _ = self; log.debug("Handle.optionSetCacheObjectLimit called, object_type: {s}, value: {}", .{ @tagName(object_type), value }); try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_SET_CACHE_OBJECT_LIMIT, @enumToInt(object_type), value }); log.debug("successfully set cache object limit", .{}); } pub fn optionSetMaximumCacheSize(self: Handle, value: usize) !void { _ = self; log.debug("Handle.optionSetCacheMaximumSize called, value: {}", .{value}); try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_SET_CACHE_MAX_SIZE, value }); log.debug("successfully set maximum cache size", .{}); } pub fn optionSetCaching(self: Handle, enabled: bool) !void { _ = self; log.debug("Handle.optionSetCaching called, enabled: {}", .{enabled}); try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_ENABLE_CACHING, enabled }); log.debug("successfully set caching status", .{}); } pub fn optionGetCachedMemory(self: Handle) !CachedMemory { _ = self; log.debug("Handle.optionGetCachedMemory called", .{}); var result: CachedMemory = undefined; try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_GET_CACHED_MEMORY, &result.current, &result.allowed }); log.debug("cached memory: {}", .{result}); return result; } pub const CachedMemory = struct { current: usize, allowed: usize, }; pub fn optionGetTemplatePath(self: Handle) !git.Buf { _ = self; log.debug("Handle.optionGetTemplatePath called", .{}); var result: git.Buf = .{}; try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_GET_TEMPLATE_PATH, @ptrCast(*c.git_buf, &result), }); log.debug("got template path: {s}", .{result.toSlice()}); return result; } pub fn optionSetTemplatePath(self: Handle, path: [:0]const u8) !void { _ = self; log.debug("Handle.optionSetTemplatePath called, path: {s}", .{path}); try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_SET_TEMPLATE_PATH, path.ptr }); log.debug("successfully set template path", .{}); } /// Either parameter may be `null`, but not both. pub fn optionSetSslCertLocations(self: Handle, file: ?[:0]const u8, path: ?[:0]const u8) !void { _ = self; log.debug("Handle.optionSetSslCertLocations called, file: {s}, path: {s}", .{ file, path }); const file_c = if (file) |ptr| ptr.ptr else null; const path_c = if (path) |ptr| ptr.ptr else null; try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_SET_SSL_CERT_LOCATIONS, file_c, path_c }); log.debug("successfully set ssl certificate location", .{}); } pub fn optionSetUserAgent(self: Handle, user_agent: [:0]const u8) !void { _ = self; log.debug("Handle.optionSetUserAgent called, user_agent: {s}", .{user_agent}); try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_SET_USER_AGENT, user_agent.ptr }); log.debug("successfully set user agent", .{}); } pub fn optionGetUserAgent(self: Handle) !git.Buf { _ = self; log.debug("Handle.optionGetUserAgent called", .{}); var result: git.Buf = .{}; try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_GET_USER_AGENT, @ptrCast(*c.git_buf, &result), }); log.debug("got user agent: {s}", .{result.toSlice()}); return result; } pub fn optionSetWindowsSharemode(self: Handle, value: c_uint) !void { _ = self; log.debug("Handle.optionSetWindowsSharemode called, value: {}", .{value}); try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_SET_WINDOWS_SHAREMODE, value }); log.debug("successfully set windows share mode", .{}); } pub fn optionGetWindowSharemode(self: Handle) !c_uint { _ = self; log.debug("Handle.optionGetWindowSharemode called", .{}); var result: c_uint = undefined; try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_GET_WINDOWS_SHAREMODE, &result }); log.debug("got windows share mode: {}", .{result}); return result; } pub fn optionSetStrictObjectCreation(self: Handle, enabled: bool) !void { _ = self; log.debug("Handle.optionSetStrictObjectCreation called, enabled: {}", .{enabled}); try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_ENABLE_STRICT_OBJECT_CREATION, @boolToInt(enabled) }); log.debug("successfully set strict object creation mode", .{}); } pub fn optionSetStrictSymbolicRefCreations(self: Handle, enabled: bool) !void { _ = self; log.debug("Handle.optionSetStrictSymbolicRefCreations called, enabled: {}", .{enabled}); try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_ENABLE_STRICT_SYMBOLIC_REF_CREATION, @boolToInt(enabled) }); log.debug("successfully set strict symbolic ref creation mode", .{}); } pub fn optionSetSslCiphers(self: Handle, ciphers: [:0]const u8) !void { _ = self; log.debug("Handle.optionSetSslCiphers called, ciphers: {s}", .{ciphers}); try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_SET_SSL_CIPHERS, ciphers.ptr }); log.debug("successfully set SSL ciphers", .{}); } pub fn optionSetOffsetDeltas(self: Handle, enabled: bool) !void { _ = self; log.debug("Handle.optionSetOffsetDeltas called, enabled: {}", .{enabled}); try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_ENABLE_OFS_DELTA, @boolToInt(enabled) }); log.debug("successfully set offset deltas mode", .{}); } pub fn optionSetFsyncDir(self: Handle, enabled: bool) !void { _ = self; log.debug("Handle.optionSetFsyncDir called, enabled: {}", .{enabled}); try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_ENABLE_FSYNC_GITDIR, @boolToInt(enabled) }); log.debug("successfully set fsync dir mode", .{}); } pub fn optionSetStrictHashVerification(self: Handle, enabled: bool) !void { _ = self; log.debug("Handle.optionSetStrictHashVerification called, enabled: {}", .{enabled}); try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_ENABLE_STRICT_HASH_VERIFICATION, @boolToInt(enabled) }); log.debug("successfully set strict hash verification mode", .{}); } /// If the given `allocator` is `null`, then the system default will be restored. pub fn optionSetAllocator(self: Handle, allocator: ?*git.GitAllocator) !void { _ = self; log.debug("Handle.optionSetAllocator called, allocator: {*}", .{allocator}); try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_SET_ALLOCATOR, allocator }); log.debug("successfully set allocator", .{}); } pub fn optionSetUnsafedIndexSafety(self: Handle, enabled: bool) !void { _ = self; log.debug("Handle.optionSetUnsafedIndexSafety called, enabled: {}", .{enabled}); try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_ENABLE_UNSAVED_INDEX_SAFETY, @boolToInt(enabled) }); log.debug("successfully set unsaved index safety mode", .{}); } pub fn optionGetMaximumPackObjects(self: Handle) !usize { _ = self; log.debug("Handle.optionGetMaximumPackObjects called", .{}); var result: usize = undefined; try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_GET_PACK_MAX_OBJECTS, &result }); log.debug("maximum pack objects: {}", .{result}); return result; } pub fn optionSetMaximumPackObjects(self: Handle, value: usize) !void { _ = self; log.debug("Handle.optionSetMaximumPackObjects called, value: {}", .{value}); try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_SET_PACK_MAX_OBJECTS, value }); log.debug("successfully set maximum pack objects", .{}); } pub fn optionSetDisablePackKeepFileChecks(self: Handle, enabled: bool) !void { _ = self; log.debug("Handle.optionSetDisablePackKeepFileChecks called, enabled: {}", .{enabled}); try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_DISABLE_PACK_KEEP_FILE_CHECKS, @boolToInt(enabled) }); log.debug("successfully set unsaved index safety mode", .{}); } pub fn optionSetHTTPExpectContinue(self: Handle, enabled: bool) !void { _ = self; log.debug("Handle.optionSetHTTPExpectContinue called, enabled: {}", .{enabled}); try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_ENABLE_HTTP_EXPECT_CONTINUE, @boolToInt(enabled) }); log.debug("successfully set HTTP expect continue mode", .{}); } pub fn branchNameIsValid(self: Handle, name: [:0]const u8) !bool { _ = self; log.debug("Handle.branchNameIsValid, name: {s}", .{name}); var valid: c_int = undefined; try internal.wrapCall("git_branch_name_is_valid", .{ &valid, name.ptr }); const ret = valid == 1; log.debug("branch name valid: {}", .{ret}); return ret; } pub fn optionSetOdbPackedPriority(self: Handle, value: usize) !void { _ = self; log.debug("Handle.optionSetOdbPackedPriority called, value: {}", .{value}); try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_SET_ODB_PACKED_PRIORITY, value }); log.debug("successfully set odb packed priority", .{}); } pub fn optionSetOdbLoosePriority(self: Handle, value: usize) !void { _ = self; log.debug("Handle.optionSetOdbLoosePriority called, value: {}", .{value}); try internal.wrapCall("git_libgit2_opts", .{ c.GIT_OPT_SET_ODB_LOOSE_PRIORITY, value }); log.debug("successfully set odb loose priority", .{}); } /// Clean up excess whitespace and make sure there is a trailing newline in the message. /// /// Optionally, it can remove lines which start with the comment character. /// /// ## Parameters /// * `message` - The message to be prettified. /// * `strip_comment_char` - If non-`null` lines starting with this character are considered to be comments and removed pub fn messagePrettify(self: Handle, message: [:0]const u8, strip_comment_char: ?u8) !git.Buf { _ = self; log.debug("Handle.messagePrettify called, message: {s}, strip_comment_char: {}", .{ message, strip_comment_char }); var ret: git.Buf = .{}; if (strip_comment_char) |char| { try internal.wrapCall("git_message_prettify", .{ @ptrCast(*c.git_buf, &ret), message.ptr, 1, char, }); } else { try internal.wrapCall("git_message_prettify", .{ @ptrCast(*c.git_buf, &ret), message.ptr, 0, 0, }); } log.debug("prettified message: {s}", .{ret.toSlice()}); return ret; } /// Parse trailers out of a message /// /// Trailers are key/value pairs in the last paragraph of a message, not including any patches or conflicts that may /// be present. pub fn messageParseTrailers(self: Handle, message: [:0]const u8) !git.MessageTrailerArray { _ = self; log.debug("Handle.messageParseTrailers called, message: {s}", .{message}); var ret: git.MessageTrailerArray = undefined; try internal.wrapCall("git_message_trailers", .{ @ptrCast(*c.git_message_trailer_array, &ret), message.ptr, }); log.debug("successfully parsed {} message trailers", .{ret.count}); return ret; } /// Available tracing levels. /// When tracing is set to a particular level, callers will be provided tracing at the given level and all lower levels. pub const TraceLevel = enum(c_uint) { /// No tracing will be performed. none = 0, /// Severe errors that may impact the program's execution fatal = 1, /// Errors that do not impact the program's execution err = 2, /// Warnings that suggest abnormal data warn = 3, /// Informational messages about program execution info = 4, /// Detailed data that allows for debugging debug = 5, /// Exceptionally detailed debugging data trace = 6, }; /// Sets the system tracing configuration to the specified level with the specified callback. /// When system events occur at a level equal to, or lower than, the given level they will be reported to the given callback. /// /// ## Parameters /// * `level` - Level to set tracing to /// * `callback_fn` - The callback function to call with trace data /// /// ## Callback Parameters /// * `level` - The trace level /// * `message` - The message pub fn traceSet( self: Handle, level: TraceLevel, comptime callback_fn: fn (level: TraceLevel, message: [:0]const u8) void, ) !void { _ = self; log.debug("Handle.traceSet called, level: {}", .{level}); const cb = struct { pub fn cb( c_level: c.git_trace_level_t, msg: ?[*:0]const u8, ) callconv(.C) void { callback_fn( @intToEnum(TraceLevel, c_level), std.mem.sliceTo(msg.?, 0), ); } }.cb; try internal.wrapCall("git_trace_set", .{ @enumToInt(level), cb, }); log.debug("successfully enabled tracing", .{}); } /// The kinds of git-specific files we know about. pub const GitFile = enum(c_uint) { /// Check for the .gitignore file gitignore = 0, /// Check for the .gitmodules file gitmodules, /// Check for the .gitattributes file gitattributes, }; /// The kinds of checks to perform according to which filesystem we are trying to protect. pub const FileSystem = enum(c_uint) { /// Do both NTFS- and HFS-specific checks generic = 0, /// Do NTFS-specific checks only ntfs, /// Do HFS-specific checks only hfs, }; /// Check whether a path component corresponds to a .git$SUFFIX file. /// /// As some filesystems do special things to filenames when writing files to disk, you cannot always do a plain string /// comparison to verify whether a file name matches an expected path or not. This function can do the comparison for you, /// depending on the filesystem you're on. /// /// ## Parameters /// * `path` - The path to check /// * `gitfile` - Which file to check against /// * `fs` - Which filesystem-specific checks to use pub fn pathIsGitfile(self: Handle, path: []const u8, gitfile: GitFile, fs: FileSystem) !bool { _ = self; log.debug("Handle.pathIsGitfile called, path: {s}, gitfile: {}, fs: {}", .{ path, gitfile, fs }); const ret = (try internal.wrapCallWithReturn("git_path_is_gitfile", .{ path.ptr, path.len, @enumToInt(gitfile), @enumToInt(fs), })) != 0; log.debug("is git file: {}", .{ret}); return ret; } pub fn configNew(self: Handle) !*git.Config { _ = self; log.debug("Handle.configNew called", .{}); var config: *git.Config = undefined; try internal.wrapCall("git_config_new", .{ @ptrCast(*?*c.git_config, &config), }); log.debug("created new config", .{}); return config; } pub fn configOpenOnDisk(self: Handle, path: [:0]const u8) !*git.Config { _ = self; log.debug("Handle.configOpenOnDisk called, path: {s}", .{path}); var config: *git.Config = undefined; try internal.wrapCall("git_config_open_ondisk", .{ @ptrCast(*?*c.git_config, &config), path.ptr, }); log.debug("opened config from file", .{}); return config; } pub fn configOpenDefault(self: Handle) !*git.Config { _ = self; log.debug("Handle.configOpenDefault called", .{}); var config: *git.Config = undefined; try internal.wrapCall("git_config_open_default", .{ @ptrCast(*?*c.git_config, &config), }); log.debug("opened default config", .{}); return config; } pub fn configFindGlobal(self: Handle) ?git.Buf { _ = self; log.debug("Handle.configFindGlobal called", .{}); var buf: git.Buf = .{}; if (c.git_config_find_global(@ptrCast(*c.git_buf, &buf)) == 0) return null; log.debug("global config path: {s}", .{buf.toSlice()}); return buf; } pub fn configFindXdg(self: Handle) ?git.Buf { _ = self; log.debug("Handle.configFindXdg called", .{}); var buf: git.Buf = .{}; if (c.git_config_find_xdg(@ptrCast(*c.git_buf, &buf)) == 0) return null; log.debug("xdg config path: {s}", .{buf.toSlice()}); return buf; } pub fn configFindSystem(self: Handle) ?git.Buf { _ = self; log.debug("Handle.configFindSystem called", .{}); var buf: git.Buf = .{}; if (c.git_config_find_system(@ptrCast(*c.git_buf, &buf)) == 0) return null; log.debug("system config path: {s}", .{buf.toSlice()}); return buf; } pub fn configFindProgramdata(self: Handle) ?git.Buf { _ = self; log.debug("Handle.configFindProgramdata called", .{}); var buf: git.Buf = .{}; if (c.git_config_find_programdata(@ptrCast(*c.git_buf, &buf)) == 0) return null; log.debug("programdata config path: {s}", .{buf.toSlice()}); return buf; } pub fn credentialInitUserPassPlaintext(self: Handle, username: [:0]const u8, password: [:0]const u8) !*git.Credential { _ = self; log.debug("Handle.credentialInitUserPassPlaintext called, username: {s}, password: {s}", .{ username, password }); var cred: *git.Credential = undefined; if (internal.has_credential) { try internal.wrapCall("git_credential_userpass_plaintext_new", .{ @ptrCast(*?*internal.RawCredentialType, &cred), username.ptr, password.ptr, }); } else { try internal.wrapCall("git_cred_userpass_plaintext_new", .{ @ptrCast(*?*internal.RawCredentialType, &cred), username.ptr, password.ptr, }); } log.debug("created new credential {*}", .{cred}); return cred; } /// Create a "default" credential usable for Negotiate mechanisms like NTLM or Kerberos authentication. pub fn credentialInitDefault(self: Handle) !*git.Credential { _ = self; log.debug("Handle.credentialInitDefault", .{}); var cred: *git.Credential = undefined; if (internal.has_credential) { try internal.wrapCall("git_credential_default_new", .{ @ptrCast(*?*internal.RawCredentialType, &cred), }); } else { try internal.wrapCall("git_cred_default_new", .{ @ptrCast(*?*internal.RawCredentialType, &cred), }); } log.debug("created new credential {*}", .{cred}); return cred; } /// Create a credential to specify a username. /// /// This is used with ssh authentication to query for the username if none is specified in the url. pub fn credentialInitUsername(self: Handle, username: [:0]const u8) !*git.Credential { _ = self; log.debug("Handle.credentialInitUsername called, username: {s}", .{username}); var cred: *git.Credential = undefined; if (internal.has_credential) { try internal.wrapCall("git_credential_username_new", .{ @ptrCast(*?*internal.RawCredentialType, &cred), username.ptr, }); } else { try internal.wrapCall("git_cred_username_new", .{ @ptrCast(*?*internal.RawCredentialType, &cred), username.ptr, }); } log.debug("created new credential {*}", .{cred}); return cred; } /// Create a new passphrase-protected ssh key credential object. /// /// ## Parameters /// * `username` - Username to use to authenticate /// * `publickey` - The path to the public key of the credential. /// * `privatekey` - The path to the private key of the credential. /// * `passphrase` - The passphrase of the credential. pub fn credentialInitSshKey( self: Handle, username: [:0]const u8, publickey: ?[:0]const u8, privatekey: [:0]const u8, passphrase: ?[:0]const u8, ) !*git.Credential { _ = self; log.debug( "Handle.credentialInitSshKey called, username: {s}, publickey: {s}, privatekey: {s}, passphrase: {s}", .{ username, publickey, privatekey, passphrase }, ); var cred: *git.Credential = undefined; const publickey_c = if (publickey) |str| str.ptr else null; const passphrase_c = if (passphrase) |str| str.ptr else null; if (internal.has_credential) { try internal.wrapCall("git_credential_ssh_key_new", .{ @ptrCast(*?*internal.RawCredentialType, &cred), username.ptr, publickey_c, privatekey.ptr, passphrase_c, }); } else { try internal.wrapCall("git_cred_ssh_key_new", .{ @ptrCast(*?*internal.RawCredentialType, &cred), username.ptr, publickey_c, privatekey.ptr, passphrase_c, }); } log.debug("created new credential {*}", .{cred}); return cred; } /// Create a new ssh key credential object reading the keys from memory. /// /// ## Parameters /// * `username` - Username to use to authenticate /// * `publickey` - The public key of the credential. /// * `privatekey` - The private key of the credential. /// * `passphrase` - The passphrase of the credential. pub fn credentialInitSshKeyMemory( self: Handle, username: [:0]const u8, publickey: ?[:0]const u8, privatekey: [:0]const u8, passphrase: ?[:0]const u8, ) !*git.Credential { _ = self; log.debug("Handle.credentialInitSshKeyMemory called", .{}); var cred: *git.Credential = undefined; const publickey_c = if (publickey) |str| str.ptr else null; const passphrase_c = if (passphrase) |str| str.ptr else null; if (internal.has_credential) { try internal.wrapCall("git_credential_ssh_key_memory_new", .{ @ptrCast(*?*internal.RawCredentialType, &cred), username.ptr, publickey_c, privatekey.ptr, passphrase_c, }); } else { try internal.wrapCall("git_cred_ssh_key_memory_new", .{ @ptrCast(*?*internal.RawCredentialType, &cred), username.ptr, publickey_c, privatekey.ptr, passphrase_c, }); } log.debug("created new credential {*}", .{cred}); return cred; } /// Create a new ssh keyboard-interactive based credential object. /// /// ## Parameters /// * `username` - Username to use to authenticate. /// * `user_data` - Pointer to user data to be passed to the callback /// * `callback_fn` - The callback function pub fn credentialInitSshKeyInteractive( self: Handle, username: [:0]const u8, user_data: anytype, comptime callback_fn: fn ( name: []const u8, instruction: []const u8, prompts: []*const c.LIBSSH2_USERAUTH_KBDINT_PROMPT, responses: []*c.LIBSSH2_USERAUTH_KBDINT_RESPONSE, abstract: ?*?*anyopaque, ) void, ) !*git.Credential { _ = self; // TODO: This callback needs to be massively cleaned up const cb = struct { pub fn cb( name: [*]const u8, name_len: c_int, instruction: [*]const u8, instruction_len: c_int, num_prompts: c_int, prompts: ?*const c.LIBSSH2_USERAUTH_KBDINT_PROMPT, responses: ?*c.LIBSSH2_USERAUTH_KBDINT_RESPONSE, abstract: ?*?*anyopaque, ) callconv(.C) void { callback_fn( name[0..name_len], instruction[0..instruction_len], prompts[0..num_prompts], responses[0..num_prompts], abstract, ); } }.cb; log.debug("Handle.credentialInitSshKeyInteractive called, username: {s}", .{username}); var cred: *git.Credential = undefined; if (internal.has_credential) { try internal.wrapCall("git_credential_ssh_interactive_new", .{ @ptrCast(*?*internal.RawCredentialType, &cred), username.ptr, cb, user_data, }); } else { try internal.wrapCall("git_cred_ssh_interactive_new", .{ @ptrCast(*?*internal.RawCredentialType, &cred), username.ptr, cb, user_data, }); } log.debug("created new credential {*}", .{cred}); return cred; } pub fn credentialInitSshKeyFromAgent(self: Handle, username: [:0]const u8) !*git.Credential { _ = self; log.debug("Handle.credentialInitSshKeyFromAgent called, username: {s}", .{username}); var cred: *git.Credential = undefined; if (internal.has_credential) { try internal.wrapCall("git_credential_ssh_key_from_agent", .{ @ptrCast(*?*internal.RawCredentialType, &cred), username.ptr, }); } else { try internal.wrapCall("git_cred_ssh_key_from_agent", .{ @ptrCast(*?*internal.RawCredentialType, &cred), username.ptr, }); } log.debug("created new credential {*}", .{cred}); return cred; } pub fn credentialInitSshKeyCustom( self: Handle, username: [:0]const u8, publickey: []const u8, user_data: anytype, comptime callback_fn: fn ( session: *c.LIBSSH2_SESSION, out_signature: *[]const u8, data: []const u8, abstract: ?*?*anyopaque, ) c_int, ) !*git.Credential { _ = self; const cb = struct { pub fn cb( session: ?*c.LIBSSH2_SESSION, sig: *[*:0]u8, sig_len: *usize, data: [*]const u8, data_len: usize, abstract: ?*?*anyopaque, ) callconv(.C) c_int { var out_sig: []const u8 = undefined; const result = callback_fn( session, &out_sig, data[0..data_len], abstract, ); sig.* = out_sig.ptr; sig_len.* = out_sig.len; return result; } }.cb; log.debug("Handle.credentialInitSshKeyCustom called, username: {s}", .{username}); var cred: *git.Credential = undefined; if (internal.has_credential) { try internal.wrapCall("git_credential_ssh_custom_new", .{ @ptrCast(*?*internal.RawCredentialType, &cred), username.ptr, publickey.ptr, publickey.len, cb, user_data, }); } else { try internal.wrapCall("git_cred_ssh_custom_new", .{ @ptrCast(*?*internal.RawCredentialType, &cred), username.ptr, publickey.ptr, publickey.len, cb, user_data, }); } log.debug("created new credential {*}", .{cred}); return cred; } /// Get detailed information regarding the last error that occured on *this* thread. pub fn getDetailedLastError(self: Handle) ?*const git.DetailedError { _ = self; return @ptrCast(?*const git.DetailedError, c.git_error_last()); } /// Clear the last error that occured on *this* thread. pub fn clearLastError(self: Handle) void { _ = self; c.git_error_clear(); } /// Create a new indexer instance /// /// ## Parameters /// * `path` - To the directory where the packfile should be stored /// * `odb` - Object database from which to read base objects when fixing thin packs. Pass `null` if no thin pack is expected /// (an error will be returned if there are bases missing) /// * `options` - Options /// * `callback_fn` - The callback function; a value less than zero to cancel the indexing or download /// /// ## Callback Parameters /// * `stats` - State of the transfer pub fn indexerInit( self: Handle, path: [:0]const u8, odb: ?*git.Odb, options: git.IndexerOptions, comptime callback_fn: fn (stats: *const git.IndexerProgress) c_int, ) !*git.Indexer { const cb = struct { pub fn cb( stats: *const git.IndexerProgress, _: *u8, ) c_int { return callback_fn(stats); } }.cb; var dummy_data: u8 = undefined; return self.indexerInitWithUserData(path, odb, options, &dummy_data, cb); } /// Create a new indexer instance /// /// ## Parameters /// * `path` - To the directory where the packfile should be stored /// * `odb` - Object database from which to read base objects when fixing thin packs. Pass `null` if no thin pack is expected /// (an error will be returned if there are bases missing) /// * `options` - Options /// * `user_data` - Pointer to user data to be passed to the callback /// * `callback_fn` - The callback function; a value less than zero to cancel the indexing or download /// /// ## Callback Parameters /// * `stats` - State of the transfer /// * `user_data_ptr` - The user data pub fn indexerInitWithUserData( self: Handle, path: [:0]const u8, odb: ?*git.Odb, options: git.IndexerOptions, user_data: anytype, comptime callback_fn: fn ( stats: *const git.IndexerProgress, user_data_ptr: @TypeOf(user_data), ) c_int, ) !*git.Indexer { _ = self; const UserDataType = @TypeOf(user_data); const cb = struct { pub fn cb( stats: *const c.git_indexer_progress, payload: ?*anyopaque, ) callconv(.C) c_int { return callback_fn(@ptrCast(*const git.IndexerProgress, stats), @ptrCast(UserDataType, payload)); } }.cb; log.debug("Handle.indexerInitWithUserData called, path: {s}, odb: {*}, options: {}", .{ path, odb, options }); var c_opts = c.git_indexer_options{ .version = c.GIT_INDEXER_OPTIONS_VERSION, .progress_cb = cb, .progress_cb_payload = user_data, .verify = @boolToInt(options.verify), }; var ret: *git.Indexer = undefined; try internal.wrapCall("git_indexer_new", .{ @ptrCast(*c.git_indexer, &ret), path.ptr, options.mode, @ptrCast(?*c.git_oid, odb), &c_opts, }); log.debug("successfully initalized Indexer", .{}); return ret; } /// Allocate a new mailmap object. /// /// This object is empty, so you'll have to add a mailmap file before you can do anything with it. /// The mailmap must be freed with 'deinit'. pub fn mailmapInit(self: Handle) !*git.Mailmap { _ = self; log.debug("Handle.mailmapInit called", .{}); var mailmap: *git.Mailmap = undefined; try internal.wrapCall("git_mailmap_new", .{ @ptrCast(*?*c.git_mailmap, &mailmap), }); log.debug("successfully initalized mailmap {*}", .{mailmap}); return mailmap; } /// Compile a pathspec /// /// ## Parameters /// * `pathspec` - A `git.StrArray` of the paths to match pub fn pathspecInit(self: Handle, pathspec: git.StrArray) !*git.Pathspec { _ = self; log.debug("Handle.pathspecInit called", .{}); var ret: *git.Pathspec = undefined; try internal.wrapCall("git_pathspec_new", .{ @ptrCast(*?*c.git_pathspec, &ret), @ptrCast(*const c.git_strarray, &pathspec), }); log.debug("successfully created pathspec: {*}", .{ret}); return ret; } /// Parse a given refspec string. /// /// ## Parameters /// * `input` - The refspec string /// * `is_fetch` - Is this a refspec for a fetch pub fn refspecParse(self: Handle, input: [:0]const u8, is_fetch: bool) !*git.Refspec { _ = self; log.debug("Handle.refspecParse called, input: {s}, is_fetch: {}", .{ input, is_fetch }); var ret: *git.Refspec = undefined; try internal.wrapCall("git_refspec_parse", .{ @ptrCast(*?*c.git_refspec, &ret), input.ptr, @boolToInt(is_fetch), }); log.debug("successfully parsed refspec: {*}", .{ret}); return ret; } /// Create a remote, with options. /// /// This function allows more fine-grained control over the remote creation. /// /// ## Parameters /// * `url` - The remote's url. /// * `options` - The remote creation options. pub fn remoteCreateWithOptions(self: Handle, url: [:0]const u8, options: git.RemoteCreateOptions) !*git.Remote { _ = self; log.debug("Handle.remoteCreateWithOptions called, url: {s}, options: {}", .{ url, options }); var remote: *git.Remote = undefined; const c_opts = internal.make_c_option.createOptions(options); try internal.wrapCall("git_remote_create_with_opts", .{ @ptrCast(*?*c.git_remote, &remote), url.ptr, &c_opts, }); log.debug("successfully created remote: {*}", .{remote}); return remote; } /// Create a remote without a connected local repo. /// /// Create a remote with the given url in-memory. You can use this when you have a URL instead of a remote's name. /// /// Contrasted with `Repository.remoteCreateAnonymous`, a detached remote will not consider any repo configuration values /// (such as insteadof url substitutions). /// /// ## Parameters /// * `url` - The remote's url. pub fn remoreCreateDetached(self: Handle, url: [:0]const u8) !*git.Remote { _ = self; log.debug("Handle.remoreCreateDetached called, url: {s}", .{url}); var remote: *git.Remote = undefined; try internal.wrapCall("git_remote_create_detached", .{ @ptrCast(*?*c.git_remote, &remote), url.ptr, }); log.debug("successfully created remote: {*}", .{remote}); return remote; } /// `min_length` is the minimal length for all identifiers, which will be used even if shorter OIDs would still be unique. pub fn oidShortenerInit(self: Handle, min_length: usize) !*git.OidShortener { _ = self; log.debug("Handle.oidShortenerInit called, min_length: {}", .{min_length}); if (c.git_oid_shorten_new(min_length)) |ret| { log.debug("Oid shortener created successfully", .{}); return @ptrCast(*git.OidShortener, ret); } return error.OutOfMemory; } pub fn oidTryParse(self: Handle, str: [:0]const u8) ?git.Oid { return self.oidTryParsePtr(str.ptr); } pub fn oidTryParsePtr(self: Handle, str: [*:0]const u8) ?git.Oid { _ = self; var result: git.Oid = undefined; internal.wrapCall("git_oid_fromstrp", .{ @ptrCast(*c.git_oid, &result), str }) catch { return null; }; return result; } /// Parse `length` characters of a hex formatted object id into a `Oid` /// /// If `length` is odd, the last byte's high nibble will be read in and the low nibble set to zero. pub fn oidParseCount(self: Handle, buf: []const u8, length: usize) !git.Oid { _ = self; if (buf.len < length) return error.BufferTooShort; var result: git.Oid = undefined; try internal.wrapCall("git_oid_fromstrn", .{ @ptrCast(*c.git_oid, &result), buf.ptr, length }); return result; } /// Create a new action signature. /// /// Note: angle brackets ('<' and '>') characters are not allowed to be used in either the `name` or the `email` parameter. /// /// ## Parameters /// * `name` - Name of the person /// * `email` - Email of the person /// * `time` - Time (in seconds from epoch) when the action happened /// * `offset` - Timezone offset (in minutes) for the time pub fn signatureInit( self: Handle, name: [:0]const u8, email: [:0]const u8, time: git.Time.SystemTime, offset: c_int, ) !*git.Signature { _ = self; log.debug("Handle.signatureInit called, name: {s}, email: {s}, time: {}, offset: {}", .{ name, email, time, offset, }); var ret: *git.Signature = undefined; try internal.wrapCall("git_signature_new", .{ @ptrCast(*?*c.git_signature, &ret), name.ptr, email.ptr, time, offset, }); log.debug("successfully initalized signature: {*}", .{ret}); return ret; } /// Create a new action signature with a timestamp of 'now'. /// /// Note: angle brackets ('<' and '>') characters are not allowed to be used in either the `name` or the `email` parameter. /// /// ## Parameters /// * `name` - Name of the person /// * `email` - Email of the person pub fn signatureInitNow( self: Handle, name: [:0]const u8, email: [:0]const u8, ) !*git.Signature { _ = self; log.debug("Handle.signatureInitNow called, name: {s}, email: {s}", .{ name, email }); var ret: *git.Signature = undefined; try internal.wrapCall("git_signature_now", .{ @ptrCast(*?*c.git_signature, &ret), name.ptr, email.ptr, }); log.debug("successfully initalized signature: {*}", .{ret}); return ret; } /// Compute a similarity signature for a text buffer /// /// If you have passed the option `ignore_whitespace`, then the whitespace will be removed from the buffer while it is being /// processed, modifying the buffer in place. Sorry about that! /// /// ## Parameters /// * `buf` - The input buffer. /// * `options` - The signature computation options pub fn hashsigInit(self: Handle, buf: []u8, options: git.HashsigOptions) !*git.Hashsig { _ = self; log.debug("Handle.hashsigInit called, options: {}", .{options}); var ret: *git.Hashsig = undefined; try internal.wrapCall("git_hashsig_create", .{ @ptrCast(*?*c.git_hashsig, &ret), buf.ptr, buf.len, internal.make_c_option.hashsigOptions(options), }); log.debug("successfully initalized hashsig: {*}", .{ret}); return ret; } /// Compute a similarity signature for a text file /// /// This walks through the file, only loading a maximum of 4K of file data at a time. Otherwise, it acts just like /// `Handle.hashsigInit`. /// /// ## Parameters /// * `buf` - The input buffer. /// * `options` - The signature computation options pub fn hashsigInitFromFile(self: Handle, path: [:0]const u8, options: git.HashsigOptions) !*git.Hashsig { _ = self; log.debug("Handle.hashsigInitFromFile called, file: {s}, options: {}", .{ path, options }); var ret: *git.Hashsig = undefined; try internal.wrapCall("git_hashsig_create_fromfile", .{ @ptrCast(*?*c.git_hashsig, &ret), path.ptr, internal.make_c_option.hashsigOptions(options), }); log.debug("successfully initalized hashsig: {*}", .{ret}); return ret; } comptime { std.testing.refAllDecls(@This()); } }; pub const CloneOptions = struct { /// Options to pass to the checkout step. checkout_options: git.CheckoutOptions = .{}, // Options which control the fetch, including callbacks. Callbacks are for reporting fetch progress, and for // acquiring credentials in the event they are needed. fetch_options: git.FetchOptions = .{}, /// Set false (default) to create a standard repo or true for a bare repo. bare: bool = false, /// Whether to use a fetch or a copy of the object database. local: LocalType = .local_auto, /// Branch of the remote repository to checkout. `null` means the default. checkout_branch: ?[:0]const u8 = null, /// A callback used to create the new repository into which to clone. If `null` the `bare` field will be used to /// determine whether to create a bare repository. /// /// Return 0, or a negative value to indicate error /// /// ## Parameters /// * `out` - The resulting repository /// * `path` - Path in which to create the repository /// * `bare` - Whether the repository is bare. This is the value from the clone options /// * `payload` - Payload specified by the options repository_cb: ?fn ( out: **git.Repository, path: [*:0]const u8, bare: bool, payload: *anyopaque, ) callconv(.C) void = null, /// An opaque payload to pass to the `repository_cb` creation callback. /// This parameter is ignored unless repository_cb is non-`null`. repository_cb_payload: ?*anyopaque = null, /// A callback used to create the git remote, prior to its being used to perform the clone option. /// This parameter may be `null`, indicating that `Handle.clone` should provide default behavior. /// /// Return 0, or an error code /// /// ## Parameters /// * `out` - The resulting remote /// * `repo` - The repository in which to create the remote /// * `name` - The remote's name /// * `url` - The remote's url /// * `payload` - An opaque payload remote_cb: ?fn ( out: **git.Remote, repo: *git.Repository, name: [*:0]const u8, url: [*:0]const u8, payload: ?*anyopaque, ) callconv(.C) void = null, remote_cb_payload: ?*anyopaque = null, /// Options for bypassing the git-aware transport on clone. Bypassing it means that instead of a fetch, /// libgit2 will copy the object database directory instead of figuring out what it needs, which is faster. pub const LocalType = enum(c_uint) { /// Auto-detect (default), libgit2 will bypass the git-aware transport for local paths, but use a normal fetch for /// `file://` urls. local_auto, /// Bypass the git-aware transport even for a `file://` url. local, /// Do no bypass the git-aware transport no_local, /// Bypass the git-aware transport, but do not try to use hardlinks. local_no_links, }; }; comptime { std.testing.refAllDecls(@This()); }
src/handle.zig
pub const PspUmdInfo = extern struct { size: c_uint, typec: c_uint, }; pub const PspUmdTypes = extern enum(c_int) { Game = 16, Video = 32, Audio = 64, }; pub const PspUmdState = extern enum(c_int) { NotPresent = 1, Present = 2, Changed = 4, Initing = 8, Inited = 16, Ready = 32, }; pub const UmdDriveStat = extern enum(c_int) { WaitForDISC = 2, WaitForINIT = 32, }; pub const UmdCallback = ?fn (c_int, c_int) callconv(.C) c_int; // Check whether there is a disc in the UMD drive // // @return 0 if no disc present, anything else indicates a disc is inserted. pub extern fn sceUmdCheckMedium() c_int; // Get the disc info // // @param info - A pointer to a ::pspUmdInfo struct // // @return < 0 on error pub extern fn sceUmdGetDiscInfo(info: *PspUmdInfo) c_int; pub fn umdGetDiscInfo(info: *PspUmdInfo) !i32 { var res = sceUmdGetDiscInfo(info); if (res < 0) { return error.Unexpected; } return res; } // Activates the UMD drive // // @param unit - The unit to initialise (probably). Should be set to 1. // // @param drive - A prefix string for the fs device to mount the UMD on (e.g. "disc0:") // // @return < 0 on error // // @par Example: // @code // // Wait for disc and mount to filesystem // int i; // i = sceUmdCheckMedium(); // if(i == 0) // { // sceUmdWaitDriveStat(PSP_UMD_PRESENT); // } // sceUmdActivate(1, "disc0:"); // Mount UMD to disc0: file system // sceUmdWaitDriveStat(PSP_UMD_READY); // // Now you can access the UMD using standard sceIo functions // @endcode pub extern fn sceUmdActivate(unit: c_int, drive: []const u8) c_int; pub fn umdActivate(unit: c_int, drive: []const u8) !i32 { var res = sceUmdActivate(unit, drive); if (res < 0) { return error.Unexpected; } return res; } // Deativates the UMD drive // // @param unit - The unit to initialise (probably). Should be set to 1. // // @param drive - A prefix string for the fs device to mount the UMD on (e.g. "disc0:") // // @return < 0 on error pub extern fn sceUmdDeactivate(unit: c_int, drive: []const u8) c_int; pub fn umdDeactivate(unit: c_int, drive: []const u8) !i32 { var res = sceUmdDeactivate(unit, drive); if (res < 0) { return error.Unexpected; } return res; } // Wait for the UMD drive to reach a certain state // // @param stat - One or more of ::pspUmdState // // @return < 0 on error pub extern fn sceUmdWaitDriveStat(stat: c_int) c_int; pub fn umdWaitDriveStat(stat: c_int) !i32 { var res = sceUmdWaitDriveStat(stat); if (res < 0) { return error.Unexpected; } return res; } // Wait for the UMD drive to reach a certain state // // @param stat - One or more of ::pspUmdState // // @param timeout - Timeout value in microseconds // // @return < 0 on error pub extern fn sceUmdWaitDriveStatWithTimer(stat: c_int, timeout: c_uint) c_int; pub fn umdWaitDriveStatWithTimer(stat: c_int, timeout: c_uint) !i32 { var res = umdWaitDriveStatWithTimer(stat, timeout); if (res < 0) { return error.Unexpected; } return res; } // Wait for the UMD drive to reach a certain state (plus callback) // // @param stat - One or more of ::pspUmdState // // @param timeout - Timeout value in microseconds // // @return < 0 on error pub extern fn sceUmdWaitDriveStatCB(stat: c_int, timeout: c_uint) c_int; pub fn umdWaitDriveStatCB(stat: c_int, timeout: c_uint) !i32 { var res = sceUmdWaitDriveStatCB(stat, timeout); if (res < 0) { return error.Unexpected; } return res; } //Cancel a sceUmdWait* call // //@return < 0 on error pub extern fn sceUmdCancelWaitDriveStat() c_int; pub fn umdCancelWaitDriveStat() !i32 { var res = sceUmdCancelWaitDriveStat(); if (res < 0) { return error.Unexpected; } return res; } // Get (poll) the current state of the UMD drive // // @return < 0 on error, one or more of ::pspUmdState on success pub extern fn sceUmdGetDriveStat() c_int; pub fn umdGetDriveStat() !i32 { var res = sceUmdGetDriveStat(); if (res < 0) { return error.Unexpected; } return res; } // Get the error code associated with a failed event // // @return < 0 on error, the error code on success pub extern fn sceUmdGetErrorStat() c_int; // Register a callback for the UMD drive // @note Callback is of type UmdCallback // // @param cbid - A callback ID created from sceKernelCreateCallback // @return < 0 on error // @par Example: // @code // int umd_callback(int unknown, int event) // { // //do something // } // int cbid = sceKernelCreateCallback("UMD Callback", umd_callback, NULL); // sceUmdRegisterUMDCallBack(cbid); // @endcode pub extern fn sceUmdRegisterUMDCallBack(cbid: c_int) c_int; pub fn umdRegisterUMDCallBack(cbid: c_int) !i32 { var res = sceUmdRegisterUMDCallBack(cbid); if (res < 0) { return error.Unexpected; } return res; } // Un-register a callback for the UMD drive // // @param cbid - A callback ID created from sceKernelCreateCallback // // @return < 0 on error pub extern fn sceUmdUnRegisterUMDCallBack(cbid: c_int) c_int; pub fn umdUnRegisterUMDCallBack(cbid: c_int) !i32 { var res = sceUmdUnRegisterUMDCallBack(cbid); if (res < 0) { return error.Unexpected; } return res; } // Permit UMD disc being replaced // // @return < 0 on error pub extern fn sceUmdReplacePermit() c_int; pub fn umdReplacePermit() !i32 { var res = sceUmdReplacePermit(); if (res < 0) { return error.Unexpected; } return res; } // Prohibit UMD disc being replaced // // @return < 0 on error pub extern fn sceUmdReplaceProhibit() c_int; pub fn umdReplaceProhibit() !i32 { var res = sceUmdReplaceProhibit(); if (res < 0) { return error.Unexpected; } return res; }
src/psp/sdk/pspumd.zig
const std = @import("std"); const Hash = std.crypto.hash.Md5; const HashVal = [Hash.digest_length]u8; const Header = packed struct { magic : u64 = 0xBF00, // same magic for all bin files, mostly just as format version or for future changes that could potentally keep backwards compatibility if needed type_hash : HashVal = undefined, // hashes comptime type info as validation to check if input/output types match payload_size : u64 = 0, fn fromType(comptime t : type) Header { return Header{ .type_hash = comptime structHash(t), .payload_size = @sizeOf(t), }; } fn matches(self : *@This(), expected: @This()) bool { return self.magic == expected.magic and std.mem.eql(u8, self.type_hash[0..], expected.type_hash[0..]) and self.payload_size == expected.payload_size; } }; fn structHash(comptime t : type) HashVal { var h = Hash.init(.{}); @setEvalBranchQuota(10000); comptime for (@typeInfo(t).Struct.fields) |f| { if (f.is_comptime) continue; h.update(f.name); const alignment : usize = f.alignment; h.update(std.mem.asBytes(&alignment)); const size : usize = @sizeOf(f.field_type); h.update(std.mem.asBytes(&size)); // TODO: more fancy validations, recursively iterate fields, assert on pointers etc. //const fti = @typeInfo(f.field_type); }; var ret : HashVal = undefined; h.final(&ret); return ret; } pub fn writeFile(comptime t : type, v : *t, f : *std.fs.File) !void { const h = Header.fromType(t); try f.*.writeAll(std.mem.asBytes(&h)); try f.*.writeAll(std.mem.asBytes(v)); } pub fn readFile(comptime t : type, v : *t, f : *std.fs.File) !void { var h = Header{}; const h_expected = Header.fromType(t); if ((try f.*.readAll(std.mem.asBytes(&h))) != std.mem.asBytes(&h).len) return error.FileTooShort; if (!h.matches(h_expected)) return error.TypeMismatch; if ((try f.*.readAll(std.mem.asBytes(v))) != std.mem.asBytes(v).len) return error.FileTooShort; }
src/bin_file.zig
const std = @import("std"); const _ast = @import("ast.zig"); const Node = _ast.Node; const Tag = _ast.Node.Tag; const NodeList = _ast.NodeList; const RefList = _ast.RefList; const lexer = @import("lexer.zig"); const Lexer = lexer.Lexer; const Token = lexer.Token; const TokenId = lexer.TokenId; pub const Error = error{ NotImplemented, UnexpectedToken, RedundantToken, UnmatchedParenthesis, InvalidConstExpr, ExpectedExpression, ExpectedParenthesis, ExpectedBrace, ExpectedFnDecl, ExpectedIdentifier, ExpectedVarDefn, ExpectedSemicolon, ExpectedColon, ExpectedBlock, ExpectedStatement, UnknownError, } || _ast.Error; const log = std.log.scoped(.parser); const Scanner = struct { tokens: []Token, token_i: usize, allocator: std.mem.Allocator, ast: _ast.Ast, _lcstr: [512]u8 = undefined, fn linecol(self: *Scanner) []const u8 { const t = self.tokens[self.token_i]; _ = std.fmt.bufPrint(self._lcstr[0..], "{}:{}", .{ t.line, t.col }) catch unreachable; return self._lcstr[0..]; } fn log_error(self: *Scanner, comptime fmt: []const u8, args: anytype) void { var msg: [1024:0]u8 = undefined; _ = std.fmt.bufPrint(msg[0..], fmt, args) catch unreachable; _ = std.fmt.bufPrint(msg[0..], "{s}: error: {s}", .{ self.linecol(), msg }) catch unreachable; log.err("{s}", .{msg}); } pub fn init(allocator: std.mem.Allocator, tokens: []Token) Scanner { return Scanner{ .tokens = tokens, .token_i = 0, .allocator = allocator, .ast = _ast.Ast.init(allocator), }; } pub fn deinit(self: *Scanner) void { self.ast.deinit(); } fn eat(p: *Scanner) Token { const t = p.tokens[p.token_i]; if (p.token_i < p.tokens.len - 1) p.token_i += 1; return t; } fn match(p: *Scanner, tags: []const TokenId) bool { for (tags) |t| { if (t == p.peek(0).tag) { return true; } } return false; } fn consume(p: *Scanner, tag: TokenId, err: Error) !Token { if (p.peek(0).tag != tag) { return err; } return p.eat(); } fn peek(p: *Scanner, offset: usize) Token { return p.tokens[if (p.token_i + offset < p.tokens.len - 1) p.token_i + offset else p.tokens.len - 1]; } fn match_sequence(p: *Scanner, tags: []TokenId) bool { for (tags) |t, i| { if (p.token_i + i > p.tokens.len or t != p.tokens[p.token_i + i].tag) { return false; } } return true; } fn parse_primary(p: *Scanner) Error!Node.Index { const t = p.peek(0); switch (t.tag) { .kwd_false, .kwd_true, .kwd_null, .literal_char, .literal_uint, .literal_int, .literal_float, .literal_string, .literal_hex, .literal_oct, .literal_bin, => { _ = p.eat(); return try p.ast.add_literal(t); }, .identifier => { _ = p.eat(); return try p.ast.add_identifier(t); }, .sep_paren_l => { _ = p.eat(); var expr = try p.parse_expr(); _ = try p.consume(.sep_paren_r, Error.UnmatchedParenthesis); return expr; }, else => return Error.UnexpectedToken, } } fn parse_call(p: *Scanner) Error!Node.Index { var expr = try p.parse_primary(); var t = p.peek(0); while (true) : (t = p.peek(0)) { if (t.tag == .sep_paren_l) { t = p.eat(); var args = std.ArrayList(Node.Index).init(p.allocator); if (t.tag != .sep_paren_r) { try args.append(try p.parse_expr()); t = p.peek(0); while (t.tag == .sep_comma) { t = p.eat(); try args.append(try p.parse_expr()); } _ = try p.consume(.sep_paren_r, Error.ExpectedParenthesis); } expr = try p.ast.add_func_call(expr, args.items); } else if (t.tag == .sep_dot) { t = p.eat(); const id = try p.consume(.identifier, Error.ExpectedIdentifier); expr = try p.ast.add_member_access(expr, id); } else { break; } } return expr; } fn parse_unary(p: *Scanner) Error!Node.Index { const tags = &[3]TokenId{ .op_cond_not, .op_sub, .op_bit_not }; if (p.match(tags[0..])) { const op = p.eat(); var rexpr = try p.parse_unary(); return try p.ast.add_unary_op(op, rexpr); } return p.parse_call(); } fn parse_factor(p: *Scanner) Error!Node.Index { var expr = try p.parse_unary(); const tags = &[4]TokenId{ .op_div, .op_mul, .op_mod, .op_at }; while (p.match(tags[0..])) { const op = p.eat(); var rexpr = try p.parse_unary(); expr = try p.ast.add_binary_op(op, expr, rexpr); } return expr; } fn parse_term(p: *Scanner) Error!Node.Index { var expr = try p.parse_factor(); const tags = &[2]TokenId{ .op_sub, .op_add }; while (p.match(tags[0..])) { const op = p.eat(); var rexpr = try p.parse_factor(); expr = try p.ast.add_binary_op(op, expr, rexpr); } return expr; } fn parse_bitshift(p: *Scanner) Error!Node.Index { var expr = try p.parse_term(); const tags = &[2]TokenId{ .op_bit_lshift, .op_bit_rshift }; while (p.match(tags[0..])) { const op = p.eat(); var rexpr = try p.parse_term(); expr = try p.ast.add_binary_op(op, expr, rexpr); } return expr; } fn parse_bitwise_comparison(p: *Scanner) Error!Node.Index { var expr = try p.parse_bitshift(); const tags = &[3]TokenId{ .op_bit_or, .op_bit_xor, .op_ampersand }; while (p.match(tags[0..])) { const op = p.eat(); var rexpr = try p.parse_bitshift(); expr = try p.ast.add_binary_op(op, expr, rexpr); } return expr; } fn parse_comparison(p: *Scanner) Error!Node.Index { var expr = try p.parse_bitwise_comparison(); while (p.match(&[4]TokenId{ .op_cond_lt, .op_cond_leq, .op_cond_gt, .op_cond_geq })) { const op = p.eat(); var rexpr = try p.parse_bitwise_comparison(); expr = try p.ast.add_binary_op(op, expr, rexpr); } return expr; } fn parse_equality(p: *Scanner) Error!Node.Index { var expr = try p.parse_comparison(); while (p.match(&[2]TokenId{ .op_cond_neq, .op_cond_eq })) { const op = p.eat(); var rexpr = try p.parse_comparison(); expr = try p.ast.add_binary_op(op, expr, rexpr); } return expr; } fn parse_or(p: *Scanner) Error!Node.Index { var expr = try p.parse_and(); while (p.peek(0).tag == .kwd_or) { const op = p.eat(); const rexpr = try p.parse_and(); expr = try p.ast.add_binary_op(op, expr, rexpr); } return expr; } fn parse_and(p: *Scanner) Error!Node.Index { var expr = try p.parse_equality(); while (p.peek(0).tag == .kwd_and) { const op = p.eat(); const rexpr = try p.parse_equality(); expr = try p.ast.add_binary_op(op, expr, rexpr); } return expr; } fn parse_assignment(p: *Scanner) Error!Node.Index { var expr = try p.parse_or(); switch (p.peek(0).tag) { .op_assign, .op_add_inline, .op_sub_inline, .op_mul_inline, .op_div_inline, .op_mod_inline, .op_at_inline, .op_bit_and_inline, .op_bit_or_inline, .op_bit_xor_inline, .op_bit_lshift_inline, .op_bit_rshift_inline, => { const op = p.eat(); const value = try p.parse_or(); // if (p.ast.nodes[expr].tag != .uhh) return Error.Wtf; return try p.ast.add_binary_op(op, expr, value); }, else => return expr, } } fn parse_expr(p: *Scanner) Error!Node.Index { return try p.parse_assignment(); } fn parse_func_decl(p: *Scanner, id: Token) Error!Node.Index { var t = p.peek(0); var is_extern: bool = false; var is_inline: bool = false; switch (t.tag) { .kwd_inline, .kwd_extern, => { const tags = &[2]TokenId{ .kwd_inline, .kwd_extern }; while (p.match(tags[0..])) { if ((is_extern and p.peek(0).tag == .kwd_extern) or (is_inline and p.peek(0).tag == .kwd_inline)) { return Error.RedundantToken; } is_extern = is_extern or p.peek(0).tag == .kwd_extern; is_inline = is_inline or p.peek(0).tag == .kwd_inline; _ = p.eat(); } }, .sep_paren_l => {}, else => return Error.ExpectedFnDecl, } _ = try p.consume(TokenId.sep_paren_l, Error.ExpectedParenthesis); var params = std.ArrayList(Node.Index).init(p.allocator); defer params.deinit(); t = p.eat(); while (t.tag != .sep_paren_r) { if (t.tag == .identifier) { const param_id = t; _ = try p.consume(TokenId.sep_colon, Error.ExpectedColon); var ptr: usize = 0; while (p.peek(0).tag == .op_mul) : (t = p.eat()) ptr += 1; const param_type = try p.consume(.identifier, Error.ExpectedIdentifier); const param = try p.ast.add_func_param( param_id, try p.ast.add_identifier(param_type), ptr, ); try params.append(param); if (p.peek(0).tag == .sep_comma) _ = p.eat(); } else return Error.ExpectedIdentifier; t = p.eat(); } var return_type: ?Node.Index = null; if (p.peek(0).tag == .sep_arrow) { _ = p.eat(); const type_id = try p.consume(.identifier, Error.ExpectedIdentifier); return_type = try p.ast.add_identifier(type_id); } const fn_body = try p.parse_compound_statement(); return try p.ast.add_func_decl( id, params.items, return_type, fn_body, is_extern, is_inline, ); } fn parse_structured_decl(p: *Scanner, id: Token) Error!Node.Index { const is_union = p.peek(0).tag == .kwd_union; if (!is_union and p.peek(0).tag != .kwd_struct) { p.log_error("expected \"struct\" or \"union\"; got {}", .{p.peek(0)}); return Error.UnexpectedToken; } _ = p.eat(); _ = try p.consume(TokenId.sep_brace_l, Error.ExpectedBrace); var members = std.ArrayList(Node.Index).init(p.allocator); defer members.deinit(); var t = p.peek(0); while (t.tag != .sep_brace_r) { const member = try p.parse_decl(true); try members.append(member); t = p.peek(0); } _ = p.eat(); return try p.ast.add_struct_decl(id, members.items, is_union); } /// parse a declaration /// /// <declaration> ::= <identifier> ( ( "::" ( <struct_decl> | <union_decl> | <func_decl> | <expression> ";" ) /// | ( ":=" <expression> ";" ) /// | ( ":" <identifier> ( ( "=" | ":" ) <expression> )? ";" ) ) ) fn parse_decl(p: *Scanner, is_root: bool) Error!Node.Index { const id = p.peek(0); //try p.consume(.identifier, Error.ExpectedIdentifier); var t = p.peek(1); switch (t.tag) { .sep_colon => { // expect identifier then optional ( ( EQUALS | COLON ) Expr) _ = p.eat(); _ = p.eat(); t = p.eat(); var ptr: usize = 0; while (t.tag == .op_mul) { ptr += 1; t = p.eat(); } if (t.tag != .identifier) return Error.ExpectedIdentifier; var type_ = try p.ast.add_identifier(t); var expr: ?Node.Index = null; t = p.eat(); if (is_root and t.tag == .sep_comma) { return try p.ast.add_struct_member(id, type_, null); } const is_const = t.tag == .sep_colon; if (t.tag == .op_assign or t.tag == .sep_colon) { _ = p.eat(); expr = try p.parse_expr(); } else { return Error.ExpectedVarDefn; } t = p.eat(); if (t.tag == .sep_comma) { if (is_const) return Error.InvalidConstExpr; return try p.ast.add_struct_member(id, type_, expr); } if (t.tag != .sep_semicolon) { return Error.ExpectedSemicolon; } return try p.ast.add_var_decl(id, type_, expr, is_const); }, .sep_double_colon => { // could be a type-inferred const decl, func decl, struct, or union _ = p.eat(); _ = p.eat(); t = p.peek(0); switch (t.tag) { .kwd_struct, .kwd_union => { return try p.parse_structured_decl(id); }, .kwd_inline, .kwd_extern => { // function decl return try p.parse_func_decl(id); }, .sep_paren_l => { // could be an Expr or ParamList if ((p.peek(1).tag == .sep_paren_r and (p.peek(2).tag == .sep_arrow or p.peek(2).tag == .sep_brace_l)) or (p.peek(1).tag == .identifier and p.peek(2).tag == .sep_colon)) { return try p.parse_func_decl(id); } var expr = try p.parse_expr(); return try p.ast.add_auto_var_decl(id, expr, false); }, else => { // type-inferred const decl var expr = try p.parse_expr(); t = p.eat(); if (t.tag != .sep_semicolon) { return Error.ExpectedSemicolon; } return try p.ast.add_auto_var_decl(id, expr, true); }, } }, .sep_colon_equals => { // expect Expr _ = p.eat(); _ = p.eat(); var expr = try p.parse_expr(); t = p.eat(); if (t.tag != .sep_semicolon) { return Error.ExpectedSemicolon; } return try p.ast.add_auto_var_decl(id, expr, false); }, else => return Error.ExpectedVarDefn, } } /// parse a block of code /// /// <block> ::= "{" <statement>* "}" fn parse_compound_statement(p: *Scanner) Error!Node.Index { var t = try p.consume(.sep_brace_l, Error.ExpectedBrace); var statements = std.ArrayList(Node.Index).init(p.allocator); defer statements.deinit(); while (t.tag != .sep_brace_r) { const statement = try p.parse_statement(); try statements.append(statement); t = p.peek(0); } _ = p.eat(); return p.ast.add_block(statements.items); } /// parse an if statement /// /// <if_statement> ::= "if" "(" <expression> ")" ( <statement> ( "else" <statement> )? ";" /// | <block> ( "else" ( <if_statement> | <block> | <statement> ";" ) )? ) /// /// TODO(mia): support if statements as expressions? fn parse_if_statement(p: *Scanner) Error!Node.Index { _ = try p.consume(.kwd_if, Error.UnexpectedToken); _ = try p.consume(.sep_paren_l, Error.ExpectedParenthesis); const condition = try p.parse_expr(); _ = try p.consume(.sep_paren_r, Error.ExpectedParenthesis); // TODO(mia): this could just be a line statement const true_block = try p.parse_compound_statement(); var false_block: ?Node.Index = null; if (p.peek(0).tag == .kwd_else) { _ = p.eat(); if (p.peek(0).tag == .kwd_if) { false_block = try p.parse_if_statement(); } else if (p.peek(0).tag == .sep_brace_l) { false_block = try p.parse_compound_statement(); } else { return Error.UnexpectedToken; } } return try p.ast.add_if_block(condition, true_block, false_block); } /// parse a while loop /// /// <while_loop> ::= "while" "(" <expression> ")" ( ":" "(" <expression> ")" )? ( <statement> | <block> ) fn parse_while_statement(p: *Scanner) Error!Node.Index { _ = try p.consume(.kwd_while, Error.UnexpectedToken); _ = try p.consume(.sep_paren_l, Error.ExpectedParenthesis); const condition = try p.parse_expr() catch Error.ExpectedExpression; _ = try p.consume(.sep_paren_r, Error.ExpectedParenthesis); // TODO(mia): implement update statement if (p.peek(0).tag == .sep_colon) return Error.NotImplemented; // TODO(mia): this could just be a line statement const block = try p.parse_compound_statement(); return try p.ast.add_while_loop(condition, null, block); } /// parse a statement /// /// <statement> ::= (( <assignment> | <inline_op> | <expression> | ( "return" <expression> ) | "break" | "continue" ) ";" ) /// | <decl> | <while_loop> | <for_loop> | <if_statement> | <switch_statement> | <block> /// 2-token lookahead fn parse_statement(p: *Scanner) Error!Node.Index { var t = p.peek(0); switch (t.tag) { .identifier => { switch (p.peek(1).tag) { .sep_colon, .sep_double_colon, .sep_colon_equals, => { // some scoped declaration return try p.parse_decl(false); }, else => { // last chance to parse an expression before peacing out const expr = p.parse_expr() catch return Error.ExpectedStatement; _ = try p.consume(.sep_semicolon, Error.ExpectedSemicolon); return expr; }, } }, .kwd_while => { return try p.parse_while_statement(); }, .kwd_if => { return try p.parse_if_statement(); }, .kwd_break, .kwd_continue, => { _ = p.eat(); _ = try p.consume(.sep_semicolon, Error.ExpectedSemicolon); return try p.ast.add_statement(if (t.tag == .kwd_break) .break_stmt else .continue_stmt, null); }, .kwd_return => { _ = p.eat(); var expr: ?Node.Index = if (p.peek(0).tag != .sep_semicolon) try p.parse_expr() else null; _ = try p.consume(.sep_semicolon, Error.ExpectedSemicolon); return try p.ast.add_statement(.return_stmt, expr); }, .kwd_switch, // => {}, .kwd_for, => return Error.NotImplemented, .sep_brace_l => return try p.parse_compound_statement(), else => return Error.ExpectedStatement, } } fn parse_root_decl(p: *Scanner) Error!Node.Index { var root_items = std.ArrayList(Node.Index).init(p.allocator); var t = p.peek(0); while (t.tag != .end_of_file) { if (t.tag != .identifier) return Error.ExpectedIdentifier; const root_stmt = try p.parse_decl(true); try root_items.append(root_stmt); t = p.peek(0); } return try p.ast.add_root(root_items.items[0..]); } }; pub fn parse(allocator: std.mem.Allocator, tokens: []Token) Error!_ast.Ast { var p = Scanner.init(allocator, tokens); // TODO(mia): do something with this? _ = p.parse_root_decl() catch |err| { log.err("error {s}: {}\n", .{ p.linecol(), err }); log.err(" got: {}\n", .{p.peek(0).tag}); return err; }; p.ast.print(); return p.ast; } test "simple parse" { var allocator = std.heap.GeneralPurposeAllocator(.{}){}; const gpa = allocator.allocator(); const src = \\ foo :: (bar: T) -> T { \\ i := bar * 2; \\ } \\ \\ Bruh :: struct { \\ foo: T, \\ bar: T, \\ \\ frob :: (i: T) -> T { \\ i := 1; \\ } \\ } ; const tokens = try lexer.tokenize(gpa, src); _ = try parse(gpa, tokens); }
src/scanner.zig
const std = @import("std"); const builtin = @import("builtin"); var sqlite3: ?*std.build.LibExeObjStep = null; fn linkSqlite(b: *std.build.LibExeObjStep) void { b.linkLibC(); if (sqlite3) |lib| { b.linkLibrary(lib); } else { b.linkSystemLibrary("sqlite3"); } } fn getTarget(original_target: std.zig.CrossTarget, bundled: bool) std.zig.CrossTarget { if (bundled) { var tmp = original_target; if (tmp.isGnuLibC()) { const min_glibc_version = std.builtin.Version{ .major = 2, .minor = 28, .patch = 0, }; if (tmp.glibc_version) |ver| { if (ver.order(min_glibc_version) == .lt) { std.debug.panic("sqlite requires glibc version >= 2.28", .{}); } } else { tmp.setGnuLibCVersion(2, 28, 0); } } return tmp; } return original_target; } const TestTarget = struct { target: std.zig.CrossTarget = @as(std.zig.CrossTarget, .{}), mode: std.builtin.Mode = .Debug, single_threaded: bool = false, bundled: bool, }; const all_test_targets = switch (builtin.target.cpu.arch) { .x86_64 => switch (builtin.target.os.tag) { .linux => [_]TestTarget{ // Targets linux but other CPU archs. TestTarget{ .target = .{}, .bundled = false, }, TestTarget{ .target = .{ .cpu_arch = .x86_64, .abi = .musl, }, .bundled = true, }, TestTarget{ .target = .{ .cpu_arch = .i386, .abi = .musl, }, .bundled = true, }, TestTarget{ .target = .{ .cpu_arch = .aarch64, .abi = .musl, }, .bundled = true, }, TestTarget{ .target = .{ .cpu_arch = .riscv64, .abi = .musl, }, .bundled = true, }, TestTarget{ .target = .{ .cpu_arch = .mips, .abi = .musl, }, .bundled = true, }, TestTarget{ .target = .{ .cpu_arch = .arm, .abi = .musleabihf, }, .bundled = true, }, // Targets windows TestTarget{ .target = .{ .cpu_arch = .x86_64, .os_tag = .windows, }, .bundled = true, }, TestTarget{ .target = .{ .cpu_arch = .i386, .os_tag = .windows, }, .bundled = true, }, // Targets macOS TestTarget{ .target = .{ .cpu_arch = .x86_64, .os_tag = .macos, }, .bundled = true, }, TestTarget{ .target = .{ .cpu_arch = .aarch64, .os_tag = .macos, }, .bundled = true, }, }, .windows => [_]TestTarget{ TestTarget{ .target = .{ .cpu_arch = .x86_64, .abi = .gnu, }, .bundled = true, }, TestTarget{ .target = .{ .cpu_arch = .i386, .abi = .gnu, }, .bundled = true, }, }, .freebsd => [_]TestTarget{ TestTarget{ .target = .{}, .bundled = false, }, TestTarget{ .target = .{ .cpu_arch = .x86_64, }, .bundled = true, }, }, .macos => [_]TestTarget{ TestTarget{ .target = .{ .cpu_arch = .x86_64, }, .bundled = true, }, }, else => [_]TestTarget{ TestTarget{ .target = .{}, .bundled = false, }, }, }, else => [_]TestTarget{ TestTarget{ .target = .{}, .bundled = false, }, }, }; pub fn build(b: *std.build.Builder) !void { const in_memory = b.option(bool, "in_memory", "Should the tests run with sqlite in memory (default true)") orelse true; const dbfile = b.option([]const u8, "dbfile", "Always use this database file instead of a temporary one"); const use_bundled = b.option(bool, "use_bundled", "Use the bundled sqlite3 source instead of linking the system library (default false)"); const target = b.standardTargetOptions(.{}); // If the target is native we assume the user didn't change it with -Dtarget and run all test targets. // Otherwise we run a single test target. const test_targets = if (target.isNative()) &all_test_targets else &[_]TestTarget{.{ .target = target, .bundled = use_bundled orelse false, }}; const test_step = b.step("test", "Run library tests"); // By default the tests will only be execute for native test targets, however they will be compiled // for _all_ targets defined in `test_targets`. // // If you want to execute tests for other targets you can pass -fqemu, -fdarling, -fwine, -frosetta. for (test_targets) |test_target| { const bundled = use_bundled orelse test_target.bundled; const cross_target = getTarget(test_target.target, bundled); const tests = b.addTest("sqlite.zig"); if (bundled) { const lib = b.addStaticLibrary("sqlite", null); lib.addCSourceFile("c/sqlite3.c", &[_][]const u8{"-std=c99"}); lib.linkLibC(); lib.setTarget(cross_target); lib.setBuildMode(test_target.mode); sqlite3 = lib; } const lib = b.addStaticLibrary("zig-sqlite", "sqlite.zig"); if (bundled) lib.addIncludeDir("c"); linkSqlite(lib); lib.setTarget(cross_target); lib.setBuildMode(test_target.mode); const single_threaded_txt = if (test_target.single_threaded) "single" else "multi"; tests.setNamePrefix(b.fmt("{s}-{s}-{s} ", .{ cross_target.zigTriple(b.allocator), @tagName(test_target.mode), single_threaded_txt, })); tests.single_threaded = test_target.single_threaded; tests.setBuildMode(test_target.mode); tests.setTarget(cross_target); if (bundled) tests.addIncludeDir("c"); linkSqlite(tests); const tests_options = b.addOptions(); tests.addOptions("build_options", tests_options); tests_options.addOption(bool, "in_memory", in_memory); tests_options.addOption(?[]const u8, "dbfile", dbfile); test_step.dependOn(&tests.step); } // Fuzzing const lib = b.addStaticLibrary("sqlite", null); lib.addCSourceFile("c/sqlite3.c", &[_][]const u8{"-std=c99"}); lib.linkLibC(); lib.setBuildMode(.Debug); lib.setTarget(getTarget(target, true)); // The library const fuzz_lib = b.addStaticLibrary("fuzz-lib", "fuzz/main.zig"); fuzz_lib.addIncludeDir("c"); fuzz_lib.setBuildMode(.Debug); fuzz_lib.setTarget(getTarget(target, true)); fuzz_lib.linkLibrary(lib); fuzz_lib.want_lto = true; fuzz_lib.bundle_compiler_rt = true; fuzz_lib.addPackagePath("sqlite", "sqlite.zig"); // Setup the output name const fuzz_executable_name = "fuzz"; const fuzz_exe_path = try std.fs.path.join(b.allocator, &.{ b.cache_root, fuzz_executable_name }); // We want `afl-clang-lto -o path/to/output path/to/library` const fuzz_compile = b.addSystemCommand(&.{ "afl-clang-lto", "-o", fuzz_exe_path }); fuzz_compile.addArtifactArg(lib); fuzz_compile.addArtifactArg(fuzz_lib); // Install the cached output to the install 'bin' path const fuzz_install = b.addInstallBinFile(.{ .path = fuzz_exe_path }, fuzz_executable_name); // Add a top-level step that compiles and installs the fuzz executable const fuzz_compile_run = b.step("fuzz", "Build executable for fuzz testing using afl-clang-lto"); // fuzz_compile_run.dependOn(&fuzz_lib.step); fuzz_compile_run.dependOn(&fuzz_compile.step); fuzz_compile_run.dependOn(&fuzz_install.step); // Compile a companion exe for debugging crashes const fuzz_debug_exe = b.addExecutable("fuzz-debug", "fuzz/main.zig"); fuzz_debug_exe.addIncludeDir("c"); fuzz_debug_exe.setBuildMode(.Debug); fuzz_debug_exe.setTarget(getTarget(target, true)); fuzz_debug_exe.linkLibrary(lib); fuzz_debug_exe.addPackagePath("sqlite", "sqlite.zig"); // Only install fuzz-debug when the fuzz step is run const install_fuzz_debug_exe = b.addInstallArtifact(fuzz_debug_exe); fuzz_compile_run.dependOn(&install_fuzz_debug_exe.step); }
build.zig
pub const WINTRUST_MAX_HEADER_BYTES_TO_MAP_DEFAULT = @as(u32, 10485760); pub const WINTRUST_MAX_HASH_BYTES_TO_MAP_DEFAULT = @as(u32, 1048576); pub const WSS_VERIFY_SEALING = @as(u32, 4); pub const WSS_INPUT_FLAG_MASK = @as(u32, 7); pub const WSS_OUT_SEALING_STATUS_VERIFIED = @as(u32, 2147483648); pub const WSS_OUT_HAS_SEALING_INTENT = @as(u32, 1073741824); pub const WSS_OUT_FILE_SUPPORTS_SEAL = @as(u32, 536870912); pub const WSS_OUTPUT_FLAG_MASK = @as(u32, 3758096384); pub const TRUSTERROR_STEP_WVTPARAMS = @as(u32, 0); pub const TRUSTERROR_STEP_FILEIO = @as(u32, 2); pub const TRUSTERROR_STEP_SIP = @as(u32, 3); pub const TRUSTERROR_STEP_SIPSUBJINFO = @as(u32, 5); pub const TRUSTERROR_STEP_CATALOGFILE = @as(u32, 6); pub const TRUSTERROR_STEP_CERTSTORE = @as(u32, 7); pub const TRUSTERROR_STEP_MESSAGE = @as(u32, 8); pub const TRUSTERROR_STEP_MSG_SIGNERCOUNT = @as(u32, 9); pub const TRUSTERROR_STEP_MSG_INNERCNTTYPE = @as(u32, 10); pub const TRUSTERROR_STEP_MSG_INNERCNT = @as(u32, 11); pub const TRUSTERROR_STEP_MSG_STORE = @as(u32, 12); pub const TRUSTERROR_STEP_MSG_SIGNERINFO = @as(u32, 13); pub const TRUSTERROR_STEP_MSG_SIGNERCERT = @as(u32, 14); pub const TRUSTERROR_STEP_MSG_CERTCHAIN = @as(u32, 15); pub const TRUSTERROR_STEP_MSG_COUNTERSIGINFO = @as(u32, 16); pub const TRUSTERROR_STEP_MSG_COUNTERSIGCERT = @as(u32, 17); pub const TRUSTERROR_STEP_VERIFY_MSGHASH = @as(u32, 18); pub const TRUSTERROR_STEP_VERIFY_MSGINDIRECTDATA = @as(u32, 19); pub const TRUSTERROR_STEP_FINAL_WVTINIT = @as(u32, 30); pub const TRUSTERROR_STEP_FINAL_INITPROV = @as(u32, 31); pub const TRUSTERROR_STEP_FINAL_OBJPROV = @as(u32, 32); pub const TRUSTERROR_STEP_FINAL_SIGPROV = @as(u32, 33); pub const TRUSTERROR_STEP_FINAL_CERTPROV = @as(u32, 34); pub const TRUSTERROR_STEP_FINAL_CERTCHKPROV = @as(u32, 35); pub const TRUSTERROR_STEP_FINAL_POLICYPROV = @as(u32, 36); pub const TRUSTERROR_STEP_FINAL_UIPROV = @as(u32, 37); pub const TRUSTERROR_MAX_STEPS = @as(u32, 38); pub const WSS_OBJTRUST_SUPPORT = @as(u32, 1); pub const WSS_SIGTRUST_SUPPORT = @as(u32, 2); pub const WSS_CERTTRUST_SUPPORT = @as(u32, 4); pub const WT_CURRENT_VERSION = @as(u32, 512); pub const WT_ADD_ACTION_ID_RET_RESULT_FLAG = @as(u32, 1); pub const SPC_UUID_LENGTH = @as(u32, 16); pub const WIN_CERT_REVISION_1_0 = @as(u32, 256); pub const WIN_CERT_REVISION_2_0 = @as(u32, 512); pub const WIN_CERT_TYPE_X509 = @as(u32, 1); pub const WIN_CERT_TYPE_PKCS_SIGNED_DATA = @as(u32, 2); pub const WIN_CERT_TYPE_RESERVED_1 = @as(u32, 3); pub const WIN_CERT_TYPE_TS_STACK_SIGNED = @as(u32, 4); pub const WT_TRUSTDBDIALOG_NO_UI_FLAG = @as(u32, 1); pub const WT_TRUSTDBDIALOG_ONLY_PUB_TAB_FLAG = @as(u32, 2); pub const WT_TRUSTDBDIALOG_WRITE_LEGACY_REG_FLAG = @as(u32, 256); pub const WT_TRUSTDBDIALOG_WRITE_IEAK_STORE_FLAG = @as(u32, 512); //-------------------------------------------------------------------------------- // Section: Types (75) //-------------------------------------------------------------------------------- pub const WINTRUST_GET_DEFAULT_FOR_USAGE_ACTION = enum(u32) { ALLOCANDFILL = 1, FREE = 2, }; pub const DWACTION_ALLOCANDFILL = WINTRUST_GET_DEFAULT_FOR_USAGE_ACTION.ALLOCANDFILL; pub const DWACTION_FREE = WINTRUST_GET_DEFAULT_FOR_USAGE_ACTION.FREE; pub const WINTRUST_POLICY_FLAGS = enum(u32) { TRUSTTEST = 32, TESTCANBEVALID = 128, IGNOREEXPIRATION = 256, IGNOREREVOKATION = 512, OFFLINEOK_IND = 1024, OFFLINEOK_COM = 2048, OFFLINEOKNBU_IND = 4096, OFFLINEOKNBU_COM = 8192, VERIFY_V1_OFF = 65536, IGNOREREVOCATIONONTS = 131072, ALLOWONLYPERTRUST = 262144, _, pub fn initFlags(o: struct { TRUSTTEST: u1 = 0, TESTCANBEVALID: u1 = 0, IGNOREEXPIRATION: u1 = 0, IGNOREREVOKATION: u1 = 0, OFFLINEOK_IND: u1 = 0, OFFLINEOK_COM: u1 = 0, OFFLINEOKNBU_IND: u1 = 0, OFFLINEOKNBU_COM: u1 = 0, VERIFY_V1_OFF: u1 = 0, IGNOREREVOCATIONONTS: u1 = 0, ALLOWONLYPERTRUST: u1 = 0, }) WINTRUST_POLICY_FLAGS { return @intToEnum(WINTRUST_POLICY_FLAGS, (if (o.TRUSTTEST == 1) @enumToInt(WINTRUST_POLICY_FLAGS.TRUSTTEST) else 0) | (if (o.TESTCANBEVALID == 1) @enumToInt(WINTRUST_POLICY_FLAGS.TESTCANBEVALID) else 0) | (if (o.IGNOREEXPIRATION == 1) @enumToInt(WINTRUST_POLICY_FLAGS.IGNOREEXPIRATION) else 0) | (if (o.IGNOREREVOKATION == 1) @enumToInt(WINTRUST_POLICY_FLAGS.IGNOREREVOKATION) else 0) | (if (o.OFFLINEOK_IND == 1) @enumToInt(WINTRUST_POLICY_FLAGS.OFFLINEOK_IND) else 0) | (if (o.OFFLINEOK_COM == 1) @enumToInt(WINTRUST_POLICY_FLAGS.OFFLINEOK_COM) else 0) | (if (o.OFFLINEOKNBU_IND == 1) @enumToInt(WINTRUST_POLICY_FLAGS.OFFLINEOKNBU_IND) else 0) | (if (o.OFFLINEOKNBU_COM == 1) @enumToInt(WINTRUST_POLICY_FLAGS.OFFLINEOKNBU_COM) else 0) | (if (o.VERIFY_V1_OFF == 1) @enumToInt(WINTRUST_POLICY_FLAGS.VERIFY_V1_OFF) else 0) | (if (o.IGNOREREVOCATIONONTS == 1) @enumToInt(WINTRUST_POLICY_FLAGS.IGNOREREVOCATIONONTS) else 0) | (if (o.ALLOWONLYPERTRUST == 1) @enumToInt(WINTRUST_POLICY_FLAGS.ALLOWONLYPERTRUST) else 0) ); } }; pub const WTPF_TRUSTTEST = WINTRUST_POLICY_FLAGS.TRUSTTEST; pub const WTPF_TESTCANBEVALID = WINTRUST_POLICY_FLAGS.TESTCANBEVALID; pub const WTPF_IGNOREEXPIRATION = WINTRUST_POLICY_FLAGS.IGNOREEXPIRATION; pub const WTPF_IGNOREREVOKATION = WINTRUST_POLICY_FLAGS.IGNOREREVOKATION; pub const WTPF_OFFLINEOK_IND = WINTRUST_POLICY_FLAGS.OFFLINEOK_IND; pub const WTPF_OFFLINEOK_COM = WINTRUST_POLICY_FLAGS.OFFLINEOK_COM; pub const WTPF_OFFLINEOKNBU_IND = WINTRUST_POLICY_FLAGS.OFFLINEOKNBU_IND; pub const WTPF_OFFLINEOKNBU_COM = WINTRUST_POLICY_FLAGS.OFFLINEOKNBU_COM; pub const WTPF_VERIFY_V1_OFF = WINTRUST_POLICY_FLAGS.VERIFY_V1_OFF; pub const WTPF_IGNOREREVOCATIONONTS = WINTRUST_POLICY_FLAGS.IGNOREREVOCATIONONTS; pub const WTPF_ALLOWONLYPERTRUST = WINTRUST_POLICY_FLAGS.ALLOWONLYPERTRUST; pub const WINTRUST_DATA_UICHOICE = enum(u32) { ALL = 1, NONE = 2, NOBAD = 3, NOGOOD = 4, }; pub const WTD_UI_ALL = WINTRUST_DATA_UICHOICE.ALL; pub const WTD_UI_NONE = WINTRUST_DATA_UICHOICE.NONE; pub const WTD_UI_NOBAD = WINTRUST_DATA_UICHOICE.NOBAD; pub const WTD_UI_NOGOOD = WINTRUST_DATA_UICHOICE.NOGOOD; pub const WINTRUST_SIGNATURE_SETTINGS_FLAGS = enum(u32) { VERIFY_SPECIFIC = 1, GET_SECONDARY_SIG_COUNT = 2, }; pub const WSS_VERIFY_SPECIFIC = WINTRUST_SIGNATURE_SETTINGS_FLAGS.VERIFY_SPECIFIC; pub const WSS_GET_SECONDARY_SIG_COUNT = WINTRUST_SIGNATURE_SETTINGS_FLAGS.GET_SECONDARY_SIG_COUNT; pub const WINTRUST_DATA_STATE_ACTION = enum(u32) { IGNORE = 0, VERIFY = 1, CLOSE = 2, AUTO_CACHE = 3, AUTO_CACHE_FLUSH = 4, }; pub const WTD_STATEACTION_IGNORE = WINTRUST_DATA_STATE_ACTION.IGNORE; pub const WTD_STATEACTION_VERIFY = WINTRUST_DATA_STATE_ACTION.VERIFY; pub const WTD_STATEACTION_CLOSE = WINTRUST_DATA_STATE_ACTION.CLOSE; pub const WTD_STATEACTION_AUTO_CACHE = WINTRUST_DATA_STATE_ACTION.AUTO_CACHE; pub const WTD_STATEACTION_AUTO_CACHE_FLUSH = WINTRUST_DATA_STATE_ACTION.AUTO_CACHE_FLUSH; pub const WINTRUST_DATA_UNION_CHOICE = enum(u32) { FILE = 1, CATALOG = 2, BLOB = 3, SIGNER = 4, CERT = 5, }; pub const WTD_CHOICE_FILE = WINTRUST_DATA_UNION_CHOICE.FILE; pub const WTD_CHOICE_CATALOG = WINTRUST_DATA_UNION_CHOICE.CATALOG; pub const WTD_CHOICE_BLOB = WINTRUST_DATA_UNION_CHOICE.BLOB; pub const WTD_CHOICE_SIGNER = WINTRUST_DATA_UNION_CHOICE.SIGNER; pub const WTD_CHOICE_CERT = WINTRUST_DATA_UNION_CHOICE.CERT; pub const WINTRUST_DATA_REVOCATION_CHECKS = enum(u32) { NONE = 0, WHOLECHAIN = 1, }; pub const WTD_REVOKE_NONE = WINTRUST_DATA_REVOCATION_CHECKS.NONE; pub const WTD_REVOKE_WHOLECHAIN = WINTRUST_DATA_REVOCATION_CHECKS.WHOLECHAIN; pub const WINTRUST_DATA_UICONTEXT = enum(u32) { EXECUTE = 0, INSTALL = 1, }; pub const WTD_UICONTEXT_EXECUTE = WINTRUST_DATA_UICONTEXT.EXECUTE; pub const WTD_UICONTEXT_INSTALL = WINTRUST_DATA_UICONTEXT.INSTALL; pub const WINTRUST_DATA = extern struct { cbStruct: u32, pPolicyCallbackData: ?*anyopaque, pSIPClientData: ?*anyopaque, dwUIChoice: WINTRUST_DATA_UICHOICE, fdwRevocationChecks: WINTRUST_DATA_REVOCATION_CHECKS, dwUnionChoice: WINTRUST_DATA_UNION_CHOICE, Anonymous: extern union { pFile: ?*WINTRUST_FILE_INFO, pCatalog: ?*WINTRUST_CATALOG_INFO, pBlob: ?*WINTRUST_BLOB_INFO, pSgnr: ?*WINTRUST_SGNR_INFO, pCert: ?*WINTRUST_CERT_INFO, }, dwStateAction: WINTRUST_DATA_STATE_ACTION, hWVTStateData: ?HANDLE, pwszURLReference: ?PWSTR, dwProvFlags: u32, dwUIContext: WINTRUST_DATA_UICONTEXT, pSignatureSettings: ?*WINTRUST_SIGNATURE_SETTINGS, }; pub const WINTRUST_SIGNATURE_SETTINGS = extern struct { cbStruct: u32, dwIndex: u32, dwFlags: WINTRUST_SIGNATURE_SETTINGS_FLAGS, cSecondarySigs: u32, dwVerifiedSigIndex: u32, pCryptoPolicy: ?*CERT_STRONG_SIGN_PARA, }; pub const WINTRUST_FILE_INFO = extern struct { cbStruct: u32, pcwszFilePath: ?[*:0]const u16, hFile: ?HANDLE, pgKnownSubject: ?*Guid, }; pub const WINTRUST_CATALOG_INFO = extern struct { cbStruct: u32, dwCatalogVersion: u32, pcwszCatalogFilePath: ?[*:0]const u16, pcwszMemberTag: ?[*:0]const u16, pcwszMemberFilePath: ?[*:0]const u16, hMemberFile: ?HANDLE, pbCalculatedFileHash: ?*u8, cbCalculatedFileHash: u32, pcCatalogContext: ?*CTL_CONTEXT, hCatAdmin: isize, }; pub const WINTRUST_BLOB_INFO = extern struct { cbStruct: u32, gSubject: Guid, pcwszDisplayName: ?[*:0]const u16, cbMemObject: u32, pbMemObject: ?*u8, cbMemSignedMsg: u32, pbMemSignedMsg: ?*u8, }; pub const WINTRUST_SGNR_INFO = extern struct { cbStruct: u32, pcwszDisplayName: ?[*:0]const u16, psSignerInfo: ?*CMSG_SIGNER_INFO, chStores: u32, pahStores: ?*?*anyopaque, }; pub const WINTRUST_CERT_INFO = extern struct { cbStruct: u32, pcwszDisplayName: ?[*:0]const u16, psCertContext: ?*CERT_CONTEXT, chStores: u32, pahStores: ?*?*anyopaque, dwFlags: u32, psftVerifyAsOf: ?*FILETIME, }; pub const PFN_CPD_MEM_ALLOC = fn( cbSize: u32, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub const PFN_CPD_MEM_FREE = fn( pvMem2Free: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub const PFN_CPD_ADD_STORE = fn( pProvData: ?*CRYPT_PROVIDER_DATA, hStore2Add: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_CPD_ADD_SGNR = fn( pProvData: ?*CRYPT_PROVIDER_DATA, fCounterSigner: BOOL, idxSigner: u32, pSgnr2Add: ?*CRYPT_PROVIDER_SGNR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_CPD_ADD_CERT = fn( pProvData: ?*CRYPT_PROVIDER_DATA, idxSigner: u32, fCounterSigner: BOOL, idxCounterSigner: u32, pCert2Add: ?*const CERT_CONTEXT, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_CPD_ADD_PRIVDATA = fn( pProvData: ?*CRYPT_PROVIDER_DATA, pPrivData2Add: ?*CRYPT_PROVIDER_PRIVDATA, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_PROVIDER_INIT_CALL = fn( pProvData: ?*CRYPT_PROVIDER_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PFN_PROVIDER_OBJTRUST_CALL = fn( pProvData: ?*CRYPT_PROVIDER_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PFN_PROVIDER_SIGTRUST_CALL = fn( pProvData: ?*CRYPT_PROVIDER_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PFN_PROVIDER_CERTTRUST_CALL = fn( pProvData: ?*CRYPT_PROVIDER_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PFN_PROVIDER_FINALPOLICY_CALL = fn( pProvData: ?*CRYPT_PROVIDER_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PFN_PROVIDER_TESTFINALPOLICY_CALL = fn( pProvData: ?*CRYPT_PROVIDER_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PFN_PROVIDER_CLEANUP_CALL = fn( pProvData: ?*CRYPT_PROVIDER_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PFN_PROVIDER_CERTCHKPOLICY_CALL = fn( pProvData: ?*CRYPT_PROVIDER_DATA, idxSigner: u32, fCounterSignerChain: BOOL, idxCounterSigner: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const CRYPT_PROVIDER_DATA = extern struct { cbStruct: u32, pWintrustData: ?*WINTRUST_DATA, fOpenedFile: BOOL, hWndParent: ?HWND, pgActionID: ?*Guid, hProv: usize, dwError: u32, dwRegSecuritySettings: u32, dwRegPolicySettings: u32, psPfns: ?*CRYPT_PROVIDER_FUNCTIONS, cdwTrustStepErrors: u32, padwTrustStepErrors: ?*u32, chStores: u32, pahStores: ?*?*anyopaque, dwEncoding: u32, hMsg: ?*anyopaque, csSigners: u32, pasSigners: ?*CRYPT_PROVIDER_SGNR, csProvPrivData: u32, pasProvPrivData: ?*CRYPT_PROVIDER_PRIVDATA, dwSubjectChoice: u32, Anonymous: extern union { pPDSip: ?*PROVDATA_SIP, }, pszUsageOID: ?PSTR, fRecallWithState: BOOL, sftSystemTime: FILETIME, pszCTLSignerUsageOID: ?PSTR, dwProvFlags: u32, dwFinalError: u32, pRequestUsage: ?*CERT_USAGE_MATCH, dwTrustPubSettings: u32, dwUIStateFlags: u32, pSigState: ?*CRYPT_PROVIDER_SIGSTATE, pSigSettings: ?*WINTRUST_SIGNATURE_SETTINGS, }; pub const CRYPT_PROVIDER_SIGSTATE = extern struct { cbStruct: u32, rhSecondarySigs: ?*?*anyopaque, hPrimarySig: ?*anyopaque, fFirstAttemptMade: BOOL, fNoMoreSigs: BOOL, cSecondarySigs: u32, dwCurrentIndex: u32, fSupportMultiSig: BOOL, dwCryptoPolicySupport: u32, iAttemptCount: u32, fCheckedSealing: BOOL, pSealingSignature: ?*SEALING_SIGNATURE_ATTRIBUTE, }; pub const CRYPT_PROVIDER_FUNCTIONS = extern struct { cbStruct: u32, pfnAlloc: ?PFN_CPD_MEM_ALLOC, pfnFree: ?PFN_CPD_MEM_FREE, pfnAddStore2Chain: ?PFN_CPD_ADD_STORE, pfnAddSgnr2Chain: ?PFN_CPD_ADD_SGNR, pfnAddCert2Chain: ?PFN_CPD_ADD_CERT, pfnAddPrivData2Chain: ?PFN_CPD_ADD_PRIVDATA, pfnInitialize: ?PFN_PROVIDER_INIT_CALL, pfnObjectTrust: ?PFN_PROVIDER_OBJTRUST_CALL, pfnSignatureTrust: ?PFN_PROVIDER_SIGTRUST_CALL, pfnCertificateTrust: ?PFN_PROVIDER_CERTTRUST_CALL, pfnFinalPolicy: ?PFN_PROVIDER_FINALPOLICY_CALL, pfnCertCheckPolicy: ?PFN_PROVIDER_CERTCHKPOLICY_CALL, pfnTestFinalPolicy: ?PFN_PROVIDER_TESTFINALPOLICY_CALL, psUIpfns: ?*CRYPT_PROVUI_FUNCS, pfnCleanupPolicy: ?PFN_PROVIDER_CLEANUP_CALL, }; pub const PFN_PROVUI_CALL = fn( hWndSecurityDialog: ?HWND, pProvData: ?*CRYPT_PROVIDER_DATA, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const CRYPT_PROVUI_FUNCS = extern struct { cbStruct: u32, psUIData: ?*CRYPT_PROVUI_DATA, pfnOnMoreInfoClick: ?PFN_PROVUI_CALL, pfnOnMoreInfoClickDefault: ?PFN_PROVUI_CALL, pfnOnAdvancedClick: ?PFN_PROVUI_CALL, pfnOnAdvancedClickDefault: ?PFN_PROVUI_CALL, }; pub const CRYPT_PROVUI_DATA = extern struct { cbStruct: u32, dwFinalError: u32, pYesButtonText: ?PWSTR, pNoButtonText: ?PWSTR, pMoreInfoButtonText: ?PWSTR, pAdvancedLinkText: ?PWSTR, pCopyActionText: ?PWSTR, pCopyActionTextNoTS: ?PWSTR, pCopyActionTextNotSigned: ?PWSTR, }; pub const CRYPT_PROVIDER_SGNR = extern struct { cbStruct: u32, sftVerifyAsOf: FILETIME, csCertChain: u32, pasCertChain: ?*CRYPT_PROVIDER_CERT, dwSignerType: u32, psSigner: ?*CMSG_SIGNER_INFO, dwError: u32, csCounterSigners: u32, pasCounterSigners: ?*CRYPT_PROVIDER_SGNR, pChainContext: ?*CERT_CHAIN_CONTEXT, }; pub const CRYPT_PROVIDER_CERT = extern struct { cbStruct: u32, pCert: ?*const CERT_CONTEXT, fCommercial: BOOL, fTrustedRoot: BOOL, fSelfSigned: BOOL, fTestCert: BOOL, dwRevokedReason: u32, dwConfidence: u32, dwError: u32, pTrustListContext: ?*CTL_CONTEXT, fTrustListSignerCert: BOOL, pCtlContext: ?*CTL_CONTEXT, dwCtlError: u32, fIsCyclic: BOOL, pChainElement: ?*CERT_CHAIN_ELEMENT, }; pub const CRYPT_PROVIDER_PRIVDATA = extern struct { cbStruct: u32, gProviderID: Guid, cbProvData: u32, pvProvData: ?*anyopaque, }; pub const PROVDATA_SIP = extern struct { cbStruct: u32, gSubject: Guid, pSip: ?*SIP_DISPATCH_INFO, pCATSip: ?*SIP_DISPATCH_INFO, psSipSubjectInfo: ?*SIP_SUBJECTINFO, psSipCATSubjectInfo: ?*SIP_SUBJECTINFO, psIndirectData: ?*SIP_INDIRECT_DATA, }; pub const CRYPT_TRUST_REG_ENTRY = extern struct { cbStruct: u32, pwszDLLName: ?PWSTR, pwszFunctionName: ?PWSTR, }; pub const CRYPT_REGISTER_ACTIONID = extern struct { cbStruct: u32, sInitProvider: CRYPT_TRUST_REG_ENTRY, sObjectProvider: CRYPT_TRUST_REG_ENTRY, sSignatureProvider: CRYPT_TRUST_REG_ENTRY, sCertificateProvider: CRYPT_TRUST_REG_ENTRY, sCertificatePolicyProvider: CRYPT_TRUST_REG_ENTRY, sFinalPolicyProvider: CRYPT_TRUST_REG_ENTRY, sTestPolicyProvider: CRYPT_TRUST_REG_ENTRY, sCleanupProvider: CRYPT_TRUST_REG_ENTRY, }; pub const PFN_ALLOCANDFILLDEFUSAGE = fn( pszUsageOID: ?[*:0]const u8, psDefUsage: ?*CRYPT_PROVIDER_DEFUSAGE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_FREEDEFUSAGE = fn( pszUsageOID: ?[*:0]const u8, psDefUsage: ?*CRYPT_PROVIDER_DEFUSAGE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const CRYPT_PROVIDER_REGDEFUSAGE = extern struct { cbStruct: u32, pgActionID: ?*Guid, pwszDllName: ?PWSTR, pwszLoadCallbackDataFunctionName: ?PSTR, pwszFreeCallbackDataFunctionName: ?PSTR, }; pub const CRYPT_PROVIDER_DEFUSAGE = extern struct { cbStruct: u32, gActionID: Guid, pDefPolicyCallbackData: ?*anyopaque, pDefSIPClientData: ?*anyopaque, }; pub const SPC_SERIALIZED_OBJECT = extern struct { ClassId: [16]u8, SerializedData: CRYPTOAPI_BLOB, }; pub const SPC_SIGINFO = extern struct { dwSipVersion: u32, gSIPGuid: Guid, dwReserved1: u32, dwReserved2: u32, dwReserved3: u32, dwReserved4: u32, dwReserved5: u32, }; pub const SPC_LINK = extern struct { dwLinkChoice: u32, Anonymous: extern union { pwszUrl: ?PWSTR, Moniker: SPC_SERIALIZED_OBJECT, pwszFile: ?PWSTR, }, }; pub const SPC_PE_IMAGE_DATA = extern struct { Flags: CRYPT_BIT_BLOB, pFile: ?*SPC_LINK, }; pub const SPC_INDIRECT_DATA_CONTENT = extern struct { Data: CRYPT_ATTRIBUTE_TYPE_VALUE, DigestAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, Digest: CRYPTOAPI_BLOB, }; pub const SPC_FINANCIAL_CRITERIA = extern struct { fFinancialInfoAvailable: BOOL, fMeetsCriteria: BOOL, }; pub const SPC_IMAGE = extern struct { pImageLink: ?*SPC_LINK, Bitmap: CRYPTOAPI_BLOB, Metafile: CRYPTOAPI_BLOB, EnhancedMetafile: CRYPTOAPI_BLOB, GifFile: CRYPTOAPI_BLOB, }; pub const SPC_SP_AGENCY_INFO = extern struct { pPolicyInformation: ?*SPC_LINK, pwszPolicyDisplayText: ?PWSTR, pLogoImage: ?*SPC_IMAGE, pLogoLink: ?*SPC_LINK, }; pub const SPC_STATEMENT_TYPE = extern struct { cKeyPurposeId: u32, rgpszKeyPurposeId: ?*?PSTR, }; pub const SPC_SP_OPUS_INFO = extern struct { pwszProgramName: ?[*:0]const u16, pMoreInfo: ?*SPC_LINK, pPublisherInfo: ?*SPC_LINK, }; pub const CAT_NAMEVALUE = extern struct { pwszTag: ?PWSTR, fdwFlags: u32, Value: CRYPTOAPI_BLOB, }; pub const CAT_MEMBERINFO = extern struct { pwszSubjGuid: ?PWSTR, dwCertVersion: u32, }; pub const CAT_MEMBERINFO2 = extern struct { SubjectGuid: Guid, dwCertVersion: u32, }; pub const INTENT_TO_SEAL_ATTRIBUTE = extern struct { version: u32, seal: BOOLEAN, }; pub const SEALING_SIGNATURE_ATTRIBUTE = extern struct { version: u32, signerIndex: u32, signatureAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, encryptedDigest: CRYPTOAPI_BLOB, }; pub const SEALING_TIMESTAMP_ATTRIBUTE = extern struct { version: u32, signerIndex: u32, sealTimeStampToken: CRYPTOAPI_BLOB, }; pub const WIN_CERTIFICATE = extern struct { dwLength: u32, wRevision: u16, wCertificateType: u16, bCertificate: [1]u8, }; pub const WIN_TRUST_ACTDATA_CONTEXT_WITH_SUBJECT = extern struct { hClientToken: ?HANDLE, SubjectType: ?*Guid, Subject: ?*anyopaque, }; pub const WIN_TRUST_ACTDATA_SUBJECT_ONLY = extern struct { SubjectType: ?*Guid, Subject: ?*anyopaque, }; pub const WIN_TRUST_SUBJECT_FILE = extern struct { hFile: ?HANDLE, lpPath: ?[*:0]const u16, }; pub const WIN_TRUST_SUBJECT_FILE_AND_DISPLAY = extern struct { hFile: ?HANDLE, lpPath: ?[*:0]const u16, lpDisplayName: ?[*:0]const u16, }; pub const WIN_SPUB_TRUSTED_PUBLISHER_DATA = extern struct { hClientToken: ?HANDLE, lpCertificate: ?*WIN_CERTIFICATE, }; pub const WTD_GENERIC_CHAIN_POLICY_SIGNER_INFO = extern struct { Anonymous: extern union { cbStruct: u32, cbSize: u32, }, pChainContext: ?*CERT_CHAIN_CONTEXT, dwSignerType: u32, pMsgSignerInfo: ?*CMSG_SIGNER_INFO, dwError: u32, cCounterSigner: u32, rgpCounterSigner: ?*?*WTD_GENERIC_CHAIN_POLICY_SIGNER_INFO, }; pub const PFN_WTD_GENERIC_CHAIN_POLICY_CALLBACK = fn( pProvData: ?*CRYPT_PROVIDER_DATA, dwStepError: u32, dwRegPolicySettings: u32, cSigner: u32, rgpSigner: ?*?*WTD_GENERIC_CHAIN_POLICY_SIGNER_INFO, pvPolicyArg: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const WTD_GENERIC_CHAIN_POLICY_CREATE_INFO = extern struct { Anonymous: extern union { cbStruct: u32, cbSize: u32, }, hChainEngine: ?HCERTCHAINENGINE, pChainPara: ?*CERT_CHAIN_PARA, dwFlags: u32, pvReserved: ?*anyopaque, }; pub const WTD_GENERIC_CHAIN_POLICY_DATA = extern struct { Anonymous: extern union { cbStruct: u32, cbSize: u32, }, pSignerChainInfo: ?*WTD_GENERIC_CHAIN_POLICY_CREATE_INFO, pCounterSignerChainInfo: ?*WTD_GENERIC_CHAIN_POLICY_CREATE_INFO, pfnPolicyCallback: ?PFN_WTD_GENERIC_CHAIN_POLICY_CALLBACK, pvPolicyArg: ?*anyopaque, }; pub const DRIVER_VER_MAJORMINOR = extern struct { dwMajor: u32, dwMinor: u32, }; pub const DRIVER_VER_INFO = extern struct { cbStruct: u32, dwReserved1: usize, dwReserved2: usize, dwPlatform: u32, dwVersion: u32, wszVersion: [260]u16, wszSignedBy: [260]u16, pcSignerCertContext: ?*const CERT_CONTEXT, sOSVersionLow: DRIVER_VER_MAJORMINOR, sOSVersionHigh: DRIVER_VER_MAJORMINOR, dwBuildNumberLow: u32, dwBuildNumberHigh: u32, }; pub const CONFIG_CI_PROV_INFO_RESULT = extern struct { hr: HRESULT, dwResult: u32, dwPolicyIndex: u32, fIsExplicitDeny: BOOLEAN, }; pub const CONFIG_CI_PROV_INFO = extern struct { cbSize: u32, dwPolicies: u32, pPolicies: ?*CRYPTOAPI_BLOB, result: CONFIG_CI_PROV_INFO_RESULT, dwScenario: u32, }; //-------------------------------------------------------------------------------- // Section: Functions (18) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WINTRUST" fn WinVerifyTrust( hwnd: ?HWND, pgActionID: ?*Guid, pWVTData: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WINTRUST" fn WinVerifyTrustEx( hwnd: ?HWND, pgActionID: ?*Guid, pWinTrustData: ?*WINTRUST_DATA, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WINTRUST" fn WintrustGetRegPolicyFlags( pdwPolicyFlags: ?*WINTRUST_POLICY_FLAGS, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WINTRUST" fn WintrustSetRegPolicyFlags( dwPolicyFlags: WINTRUST_POLICY_FLAGS, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WINTRUST" fn WintrustAddActionID( pgActionID: ?*Guid, fdwFlags: u32, psProvInfo: ?*CRYPT_REGISTER_ACTIONID, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WINTRUST" fn WintrustRemoveActionID( pgActionID: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WINTRUST" fn WintrustLoadFunctionPointers( pgActionID: ?*Guid, pPfns: ?*CRYPT_PROVIDER_FUNCTIONS, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WINTRUST" fn WintrustAddDefaultForUsage( pszUsageOID: ?[*:0]const u8, psDefUsage: ?*CRYPT_PROVIDER_REGDEFUSAGE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WINTRUST" fn WintrustGetDefaultForUsage( dwAction: WINTRUST_GET_DEFAULT_FOR_USAGE_ACTION, pszUsageOID: ?[*:0]const u8, psUsage: ?*CRYPT_PROVIDER_DEFUSAGE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WINTRUST" fn WTHelperGetProvSignerFromChain( pProvData: ?*CRYPT_PROVIDER_DATA, idxSigner: u32, fCounterSigner: BOOL, idxCounterSigner: u32, ) callconv(@import("std").os.windows.WINAPI) ?*CRYPT_PROVIDER_SGNR; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WINTRUST" fn WTHelperGetProvCertFromChain( pSgnr: ?*CRYPT_PROVIDER_SGNR, idxCert: u32, ) callconv(@import("std").os.windows.WINAPI) ?*CRYPT_PROVIDER_CERT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WINTRUST" fn WTHelperProvDataFromStateData( hStateData: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) ?*CRYPT_PROVIDER_DATA; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WINTRUST" fn WTHelperGetProvPrivateDataFromChain( pProvData: ?*CRYPT_PROVIDER_DATA, pgProviderID: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) ?*CRYPT_PROVIDER_PRIVDATA; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WINTRUST" fn WTHelperCertIsSelfSigned( dwEncoding: u32, pCert: ?*CERT_INFO, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WINTRUST" fn WTHelperCertCheckValidSignature( pProvData: ?*CRYPT_PROVIDER_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WINTRUST" fn OpenPersonalTrustDBDialogEx( hwndParent: ?HWND, dwFlags: u32, pvReserved: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WINTRUST" fn OpenPersonalTrustDBDialog( hwndParent: ?HWND, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WINTRUST" fn WintrustSetDefaultIncludePEPageHashes( fIncludePEPageHashes: BOOL, ) callconv(@import("std").os.windows.WINAPI) void; //-------------------------------------------------------------------------------- // 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 (26) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const BOOLEAN = @import("../foundation.zig").BOOLEAN; const CERT_CHAIN_CONTEXT = @import("../security/cryptography.zig").CERT_CHAIN_CONTEXT; const CERT_CHAIN_ELEMENT = @import("../security/cryptography.zig").CERT_CHAIN_ELEMENT; const CERT_CHAIN_PARA = @import("../security/cryptography.zig").CERT_CHAIN_PARA; const CERT_CONTEXT = @import("../security/cryptography.zig").CERT_CONTEXT; const CERT_INFO = @import("../security/cryptography.zig").CERT_INFO; const CERT_STRONG_SIGN_PARA = @import("../security/cryptography.zig").CERT_STRONG_SIGN_PARA; const CERT_USAGE_MATCH = @import("../security/cryptography.zig").CERT_USAGE_MATCH; const CMSG_SIGNER_INFO = @import("../security/cryptography.zig").CMSG_SIGNER_INFO; const CRYPT_ALGORITHM_IDENTIFIER = @import("../security/cryptography.zig").CRYPT_ALGORITHM_IDENTIFIER; const CRYPT_ATTRIBUTE_TYPE_VALUE = @import("../security/cryptography.zig").CRYPT_ATTRIBUTE_TYPE_VALUE; const CRYPT_BIT_BLOB = @import("../security/cryptography.zig").CRYPT_BIT_BLOB; const CRYPTOAPI_BLOB = @import("../security/cryptography.zig").CRYPTOAPI_BLOB; const CTL_CONTEXT = @import("../security/cryptography.zig").CTL_CONTEXT; const FILETIME = @import("../foundation.zig").FILETIME; const HANDLE = @import("../foundation.zig").HANDLE; const HCERTCHAINENGINE = @import("../security/cryptography.zig").HCERTCHAINENGINE; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const PSTR = @import("../foundation.zig").PSTR; const PWSTR = @import("../foundation.zig").PWSTR; const SIP_DISPATCH_INFO = @import("../security/cryptography/sip.zig").SIP_DISPATCH_INFO; const SIP_INDIRECT_DATA = @import("../security/cryptography/sip.zig").SIP_INDIRECT_DATA; const SIP_SUBJECTINFO = @import("../security/cryptography/sip.zig").SIP_SUBJECTINFO; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PFN_CPD_MEM_ALLOC")) { _ = PFN_CPD_MEM_ALLOC; } if (@hasDecl(@This(), "PFN_CPD_MEM_FREE")) { _ = PFN_CPD_MEM_FREE; } if (@hasDecl(@This(), "PFN_CPD_ADD_STORE")) { _ = PFN_CPD_ADD_STORE; } if (@hasDecl(@This(), "PFN_CPD_ADD_SGNR")) { _ = PFN_CPD_ADD_SGNR; } if (@hasDecl(@This(), "PFN_CPD_ADD_CERT")) { _ = PFN_CPD_ADD_CERT; } if (@hasDecl(@This(), "PFN_CPD_ADD_PRIVDATA")) { _ = PFN_CPD_ADD_PRIVDATA; } if (@hasDecl(@This(), "PFN_PROVIDER_INIT_CALL")) { _ = PFN_PROVIDER_INIT_CALL; } if (@hasDecl(@This(), "PFN_PROVIDER_OBJTRUST_CALL")) { _ = PFN_PROVIDER_OBJTRUST_CALL; } if (@hasDecl(@This(), "PFN_PROVIDER_SIGTRUST_CALL")) { _ = PFN_PROVIDER_SIGTRUST_CALL; } if (@hasDecl(@This(), "PFN_PROVIDER_CERTTRUST_CALL")) { _ = PFN_PROVIDER_CERTTRUST_CALL; } if (@hasDecl(@This(), "PFN_PROVIDER_FINALPOLICY_CALL")) { _ = PFN_PROVIDER_FINALPOLICY_CALL; } if (@hasDecl(@This(), "PFN_PROVIDER_TESTFINALPOLICY_CALL")) { _ = PFN_PROVIDER_TESTFINALPOLICY_CALL; } if (@hasDecl(@This(), "PFN_PROVIDER_CLEANUP_CALL")) { _ = PFN_PROVIDER_CLEANUP_CALL; } if (@hasDecl(@This(), "PFN_PROVIDER_CERTCHKPOLICY_CALL")) { _ = PFN_PROVIDER_CERTCHKPOLICY_CALL; } if (@hasDecl(@This(), "PFN_PROVUI_CALL")) { _ = PFN_PROVUI_CALL; } if (@hasDecl(@This(), "PFN_ALLOCANDFILLDEFUSAGE")) { _ = PFN_ALLOCANDFILLDEFUSAGE; } if (@hasDecl(@This(), "PFN_FREEDEFUSAGE")) { _ = PFN_FREEDEFUSAGE; } if (@hasDecl(@This(), "PFN_WTD_GENERIC_CHAIN_POLICY_CALLBACK")) { _ = PFN_WTD_GENERIC_CHAIN_POLICY_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/security/win_trust.zig
//-------------------------------------------------------------------------------- // Section: Types (1) //-------------------------------------------------------------------------------- const IID_ICoreFrameworkInputViewInterop_Value = Guid.initString("0e3da342-b11c-484b-9c1c-be0d61c2f6c5"); pub const IID_ICoreFrameworkInputViewInterop = &IID_ICoreFrameworkInputViewInterop_Value; pub const ICoreFrameworkInputViewInterop = extern struct { pub const VTable = extern struct { base: IInspectable.VTable, GetForWindow: fn( self: *const ICoreFrameworkInputViewInterop, appWindow: ?HWND, riid: ?*const Guid, coreFrameworkInputView: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IInspectable.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICoreFrameworkInputViewInterop_GetForWindow(self: *const T, appWindow: ?HWND, riid: ?*const Guid, coreFrameworkInputView: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const ICoreFrameworkInputViewInterop.VTable, self.vtable).GetForWindow(@ptrCast(*const ICoreFrameworkInputViewInterop, self), appWindow, riid, coreFrameworkInputView); } };} 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 (4) //-------------------------------------------------------------------------------- const Guid = @import("../../zig.zig").Guid; const HRESULT = @import("../../foundation.zig").HRESULT; const HWND = @import("../../foundation.zig").HWND; const IInspectable = @import("../../system/win_rt.zig").IInspectable; 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/system/win_rt/core_input_view.zig
const std = @import("std"); const builtin = std.builtin; const math = std.math; const mem = std.mem; const os = std.os; const testing = std.testing; const assert = std.debug.assert; pub const page_size = std.mem.page_size; /// Maps a chunk of memory from the OS pub fn alloc(allocation_size: usize) error{OutOfMemory}![*]align(page_size) u8 { if (builtin.os.tag == .windows) { const w = os.windows; const addr = w.VirtualAlloc( null, allocation_size, w.MEM_COMMIT | w.MEM_RESERVE, w.PAGE_READWRITE, ) catch return error.OutOfMemory; return @alignCast(page_size, @ptrCast([*]u8, addr)); } else { const slice = os.mmap( null, allocation_size, os.PROT_READ | os.PROT_WRITE, os.MAP_PRIVATE | os.MAP_ANONYMOUS, -1, 0, ) catch return error.OutOfMemory; return slice.ptr; } } /// Frees pages back to the OS. The passed slice must previously /// have been allocated by a function in this file. Cannot unmap /// part of a previous allocation. It must be the whole thing. pub fn free(mem_unaligned: []u8) void { if (mem_unaligned.len == 0) return; const mem_aligned = @alignCast(page_size, mem_unaligned); if (builtin.os.tag == .windows) { os.windows.VirtualFree(mem_aligned.ptr, 0, os.windows.MEM_RELEASE); } else { os.munmap(mem_aligned); } } /// Maps an aligned chunk of memory from the OS pub fn allocAligned(n: usize, alignment: u29) error{OutOfMemory}![*]align(page_size) u8 { if (n == 0) return undefined; if (builtin.os.tag == .windows) { const w = os.windows; // Although officially it's at least aligned to page boundary, // Windows is known to reserve pages on a 64K boundary. It's // even more likely that the requested alignment is <= 64K than // 4K, so we're just allocating blindly and hoping for the best. // see https://devblogs.microsoft.com/oldnewthing/?p=42223 const addr = w.VirtualAlloc( null, n, w.MEM_COMMIT | w.MEM_RESERVE, w.PAGE_READWRITE, ) catch return error.OutOfMemory; // If the allocation is sufficiently aligned, use it. if (@ptrToInt(addr) & (alignment - 1) == 0) { return @alignCast(page_size, @ptrCast([*]u8, addr)); } // If it wasn't, actually do an explicitely aligned allocation. w.VirtualFree(addr, 0, w.MEM_RELEASE); const alloc_size = n + alignment; const final_addr = while (true) { // Reserve a range of memory large enough to find a sufficiently // aligned address. const reserved_addr = w.VirtualAlloc( null, alloc_size, w.MEM_RESERVE, w.PAGE_NOACCESS, ) catch return error.OutOfMemory; const aligned_addr = mem.alignForward(@ptrToInt(reserved_addr), alignment); // Release the reserved pages (not actually used). w.VirtualFree(reserved_addr, 0, w.MEM_RELEASE); // At this point, it is possible that another thread has // obtained some memory space that will cause the next // VirtualAlloc call to fail. To handle this, we will retry // until it succeeds. const ptr = w.VirtualAlloc( @intToPtr(*c_void, aligned_addr), n, w.MEM_COMMIT | w.MEM_RESERVE, w.PAGE_READWRITE, ) catch continue; return @alignCast(page_size, @ptrCast([*]u8, ptr)); }; return @alignCast(page_size, @ptrCast([*]u8, final_addr)); } const alloc_size = if (alignment <= page_size) n else n + alignment; const slice = os.mmap( null, mem.alignForward(alloc_size, page_size), os.PROT_READ | os.PROT_WRITE, os.MAP_PRIVATE | os.MAP_ANONYMOUS, -1, 0, ) catch return error.OutOfMemory; if (alloc_size == n) return @alignCast(page_size, slice[0..n].ptr); const aligned_addr = mem.alignForward(@ptrToInt(slice.ptr), alignment); // Unmap the extra bytes that were only requested in order to guarantee // that the range of memory we were provided had a proper alignment in // it somewhere. The extra bytes could be at the beginning, or end, or both. const unused_start_len = aligned_addr - @ptrToInt(slice.ptr); if (unused_start_len != 0) { os.munmap(slice[0..unused_start_len]); } const aligned_end_addr = mem.alignForward(aligned_addr + n, page_size); const unused_end_len = @ptrToInt(slice.ptr) + slice.len - aligned_end_addr; if (unused_end_len != 0) { os.munmap(@intToPtr([*]align(page_size) u8, aligned_end_addr)[0..unused_end_len]); } return @alignCast(page_size, @intToPtr([*]u8, aligned_addr)); } /// Shrinks a page allocation, respecting alignment pub fn shrinkAligned(old_mem_unaligned: []u8, old_align: u29, new_size: usize, new_align: u29) [*]align(page_size) u8 { const old_mem = @alignCast(page_size, old_mem_unaligned); if (builtin.os.tag == .windows) { const w = os.windows; if (new_size == 0) { // From the docs: // "If the dwFreeType parameter is MEM_RELEASE, this parameter // must be 0 (zero). The function frees the entire region that // is reserved in the initial allocation call to VirtualAlloc." // So we can only use MEM_RELEASE when actually releasing the // whole allocation. w.VirtualFree(old_mem.ptr, 0, w.MEM_RELEASE); } else { const base_addr = @ptrToInt(old_mem.ptr); const old_addr_end = base_addr + old_mem.len; const new_addr_end = base_addr + new_size; const new_addr_end_rounded = mem.alignForward(new_addr_end, page_size); if (old_addr_end > new_addr_end_rounded) { // For shrinking that is not releasing, we will only // decommit the pages not needed anymore. w.VirtualFree( @intToPtr(*c_void, new_addr_end_rounded), old_addr_end - new_addr_end_rounded, w.MEM_DECOMMIT, ); } } return @alignCast(page_size, old_mem.ptr); } const base_addr = @ptrToInt(old_mem.ptr); const old_addr_end = base_addr + old_mem.len; const new_addr_end = base_addr + new_size; const new_addr_end_rounded = mem.alignForward(new_addr_end, page_size); if (old_addr_end > new_addr_end_rounded) { const ptr = @intToPtr([*]align(page_size) u8, new_addr_end_rounded); os.munmap(ptr[0 .. old_addr_end - new_addr_end_rounded]); } return @alignCast(page_size, old_mem.ptr); } /// Relocates a page allocation, respecting alignment pub fn reallocAligned(old_mem_unaligned: []u8, old_align: u29, new_size: usize, new_align: u29) ![*]align(page_size) u8 { const old_mem = @alignCast(page_size, old_mem_unaligned); if (builtin.os.tag == .windows) { if (old_mem.len == 0) { return allocAligned(new_size, new_align); } if (new_size <= old_mem.len and new_align <= old_align) { return shrinkAligned(old_mem, old_align, new_size, new_align); } const w = os.windows; const base_addr = @ptrToInt(old_mem.ptr); if (new_align > old_align and base_addr & (new_align - 1) != 0) { // Current allocation doesn't satisfy the new alignment. // For now we'll do a new one no matter what, but maybe // there is something smarter to do instead. const result = try allocAligned(new_size, new_align); assert(old_mem.len != 0); @memcpy(result, old_mem.ptr, std.math.min(old_mem.len, new_size)); w.VirtualFree(old_mem.ptr, 0, w.MEM_RELEASE); return result; } const old_addr_end = base_addr + old_mem.len; const old_addr_end_rounded = mem.alignForward(old_addr_end, page_size); const new_addr_end = base_addr + new_size; const new_addr_end_rounded = mem.alignForward(new_addr_end, page_size); if (new_addr_end_rounded == old_addr_end_rounded) { // The reallocation fits in the already allocated pages. return @alignCast(page_size, old_mem.ptr); } assert(new_addr_end_rounded > old_addr_end_rounded); // We need to commit new pages. const additional_size = new_addr_end - old_addr_end_rounded; const realloc_addr = w.kernel32.VirtualAlloc( @intToPtr(*c_void, old_addr_end_rounded), additional_size, w.MEM_COMMIT | w.MEM_RESERVE, w.PAGE_READWRITE, ) orelse { // Committing new pages at the end of the existing allocation // failed, we need to try a new one. const new_alloc_mem = try allocAligned(new_size, new_align); @memcpy(new_alloc_mem, old_mem.ptr, old_mem.len); w.VirtualFree(old_mem.ptr, 0, w.MEM_RELEASE); return new_alloc_mem; }; assert(@ptrToInt(realloc_addr) == old_addr_end_rounded); return @alignCast(page_size, old_mem.ptr); } if (new_size <= old_mem.len and new_align <= old_align) { return shrink(old_mem, old_align, new_size, new_align); } const result = try allocAligned(allocator, new_size, new_align); if (old_mem.len != 0) { @memcpy(result, old_mem.ptr, std.math.min(old_mem.len, new_size)); os.munmap(old_mem); asdf; } return result; } /// Queries the allocation granularity from the operating system. /// On windows, this is probably 64k. On linux, it is probably 4k. pub fn findAllocationGranularity() usize { if (builtin.os.tag == .windows) { const w = os.windows; var info: w.SYSTEM_INFO = undefined; w.kernel32.GetSystemInfo(&info); assert(math.isPowerOfTwo(info.dwAllocationGranularity)); return info.dwAllocationGranularity; } else { return page_size; } } test "Get Granularity" { const granularity = findAllocationGranularity(); if (builtin.os.tag == .windows) { testing.expectEqual(@as(usize, 64 * 1024), granularity); } else { testing.expectEqual(@as(usize, os.page_size), granularity); } } test "Alloc" { const granularity = findAllocationGranularity(); const chunk = try alloc(granularity); const slice = chunk[0..granularity]; mem.set(u8, slice, 0xF8); for (slice) |item| { assert(item == 0xF8); } free(chunk[0..granularity]); } test "Compile" { _ = allocAligned; _ = shrinkAligned; _ = reallocAligned; }
page_alloc.zig
const std = @import("std"); const Date = @import("date.zig"); const config = @import("config.zig"); const util = @import("util.zig"); const Styles = @import("cli.zig").Styles; content: []const u8, due: ?Date, completed: bool, index: ?usize = null, const Self = @This(); /// The higher the number, the less "urgent" the task is pub fn compare(self: Self, other: Self) i64 { // If this isn't completed but the other is, then this is higher value if (!self.completed and other.completed) { return -1; } else if (self.completed and !other.completed) { return 1; } // .completed is now assumed to be the same // Tasks without due dates should be ranked higher than ones with dates if (self.due) |d| { if (other.due) |d2| { return d.compare(d2); } return -1; } // self.due must equal null if (other.due != null) { return 1; } return 0; } pub const HashtagCounter = struct { names: [][]const u8, counter: []util.Pair(u64), len: usize = 0, // Returns true if it made a new entry. pub fn add(self: *HashtagCounter, name: []const u8, task: Self) bool { for (self.names[0..self.len]) |n, i| { if (util.eqlNoCase(u8, n, name)) { if (task.completed) { self.counter[i].a += 1; } else self.counter[i].b += 1; return false; } } self.names[self.len] = name; self.counter[self.len] = util.Pair(u64) { .a = if (task.completed) 1 else 0, .b = if (task.completed) 0 else 1, }; self.len += 1; return true; } }; pub const HashtagIterator = struct { words: std.mem.TokenIterator, counter: HashtagCounter, task: Self, pub fn next(self: *HashtagIterator) ?[]const u8 { while (self.words.next()) |w| { if (isHashtag(w)) { if (self.counter.add(w, self.task)) { return w; } else return self.next(); } } return null; } }; /// Returns an iterator of hashtags. Does not produce duplicates. pub fn hashtags(self: Self, name_buffer: [][]const u8, counter: []util.Pair(u64)) HashtagIterator { return HashtagIterator { .words = std.mem.tokenize(self.content, " "), .counter = HashtagCounter { .names = name_buffer, .counter = counter, }, .task = self, }; } pub fn isHashtag(word: []const u8) bool { return word[0] == '#' and word.len > 1; } test "task.compare not completed" { { // Two equal dates const a = Self { .content = "a", .due = try Date.init(2021, 4, 15), .completed = false, }; const b = Self { .content = "b", .due = try Date.init(2021, 4, 15), .completed = false, }; std.testing.expectEqual(@as(i64, 0), a.compare(b)); } { // a is more urgent than b const a = Self { .content = "a", .due = try Date.init(2021, 4, 15), .completed = false, }; const b = Self { .content = "b", .due = try Date.init(2021, 4, 16), .completed = false, }; std.testing.expect(a.compare(b) < 0); } { // a is less urgent than b const a = Self { .content = "a", .due = try Date.init(2021, 4, 17), .completed = false, }; const b = Self { .content = "b", .due = try Date.init(2021, 4, 15), .completed = false, }; std.testing.expect(a.compare(b) > 0); } } test "task.compare completed" { { // Two equal dates const a = Self { .content = "a", .due = try Date.init(2021, 4, 15), .completed = true, }; const b = Self { .content = "b", .due = try Date.init(2021, 4, 15), .completed = true, }; std.testing.expectEqual(@as(i64, 0), a.compare(b)); } { // a is more urgent than b const a = Self { .content = "a", .due = try Date.init(2021, 4, 15), .completed = true, }; const b = Self { .content = "b", .due = try Date.init(2021, 4, 16), .completed = true, }; std.testing.expect(a.compare(b) < 0); } { // a is less urgent than b const a = Self { .content = "a", .due = try Date.init(2021, 4, 17), .completed = true, }; const b = Self { .content = "b", .due = try Date.init(2021, 4, 15), .completed = true, }; std.testing.expect(a.compare(b) > 0); } } test "test.compare completed & not completed" { { // Equal dates - a is less urgent than b const a = Self { .content = "a", .due = try Date.init(2021, 4, 15), .completed = true, }; const b = Self { .content = "b", .due = try Date.init(2021, 4, 15), .completed = false, }; std.testing.expect(a.compare(b) > 0); } { // a is more urgent than b, but a is completed const a = Self { .content = "a", .due = try Date.init(2021, 4, 15), .completed = true, }; const b = Self { .content = "b", .due = try Date.init(2021, 4, 16), .completed = false, }; std.testing.expect(a.compare(b) > 0); } { // a is less urgent than b, and a is completed const a = Self { .content = "a", .due = try Date.init(2021, 4, 17), .completed = true, }; const b = Self { .content = "b", .due = try Date.init(2021, 4, 15), .completed = false, }; std.testing.expect(a.compare(b) > 0); } { // Case test const a = Self { .content = "Chemistry #exam", .due = try Date.init(2021, 4, 30), .completed = false, }; const b = Self { .content = "book a vacation", .due = try Date.init(2021, 4, 16), .completed = true, }; std.testing.expect(a.compare(b) < 0); } }
src/task.zig