code
stringlengths
38
801k
repo_path
stringlengths
6
263
const TestContext = @import("../../src-self-hosted/test.zig").TestContext; const std = @import("std"); const ErrorMsg = @import("../../src-self-hosted/Module.zig").ErrorMsg; const linux_x64 = std.zig.CrossTarget{ .cpu_arch = .x86_64, .os_tag = .linux, }; pub fn addCases(ctx: *TestContext) !void { ctx.compileErrorZIR("call undefined local", linux_x64, \\@noreturn = primitive(noreturn) \\ \\@start_fnty = fntype([], @noreturn, cc=Naked) \\@start = fn(@start_fnty, { \\ %0 = call(%test, []) \\}) // TODO: address inconsistency in this message and the one in the next test , &[_][]const u8{":5:13: error: unrecognized identifier: %test"}); ctx.compileErrorZIR("call with non-existent target", linux_x64, \\@noreturn = primitive(noreturn) \\ \\@start_fnty = fntype([], @noreturn, cc=Naked) \\@start = fn(@start_fnty, { \\ %0 = call(@notafunc, []) \\}) \\@0 = str("_start") \\@1 = export(@0, "start") , &[_][]const u8{":5:13: error: decl 'notafunc' not found"}); // TODO: this error should occur at the call site, not the fntype decl ctx.compileErrorZIR("call naked function", linux_x64, \\@noreturn = primitive(noreturn) \\ \\@start_fnty = fntype([], @noreturn, cc=Naked) \\@s = fn(@start_fnty, {}) \\@start = fn(@start_fnty, { \\ %0 = call(@s, []) \\}) \\@0 = str("_start") \\@1 = export(@0, "start") , &[_][]const u8{":4:9: error: unable to call function with naked calling convention"}); ctx.incrementalFailureZIR("exported symbol collision", linux_x64, \\@noreturn = primitive(noreturn) \\ \\@start_fnty = fntype([], @noreturn) \\@start = fn(@start_fnty, {}) \\ \\@0 = str("_start") \\@1 = export(@0, "start") \\@2 = export(@0, "start") , &[_][]const u8{":8:13: error: exported symbol collision: _start"}, \\@noreturn = primitive(noreturn) \\ \\@start_fnty = fntype([], @noreturn) \\@start = fn(@start_fnty, {}) \\ \\@0 = str("_start") \\@1 = export(@0, "start") ); ctx.compileError("function redefinition", linux_x64, \\fn entry() void {} \\fn entry() void {} , &[_][]const u8{":2:4: error: redefinition of 'entry'"}); //ctx.incrementalFailure("function redefinition", linux_x64, // \\fn entry() void {} // \\fn entry() void {} //, &[_][]const u8{":2:4: error: redefinition of 'entry'"}, // \\fn entry() void {} //); //// TODO: need to make sure this works with other variants of export. //ctx.incrementalFailure("exported symbol collision", linux_x64, // \\export fn entry() void {} // \\export fn entry() void {} //, &[_][]const u8{":2:11: error: redefinition of 'entry'"}, // \\export fn entry() void {} //); // ctx.incrementalFailure("missing function name", linux_x64, // \\fn() void {} // , &[_][]const u8{":1:3: error: missing function name"}, // \\fn a() void {} // ); // TODO: re-enable these tests. // https://github.com/ziglang/zig/issues/1364 //ctx.testCompileError( // \\comptime { // \\ return; // \\} //, "1.zig", 2, 5, "return expression outside function definition"); //ctx.testCompileError( // \\export fn entry() void { // \\ defer return; // \\} //, "1.zig", 2, 11, "cannot return from defer expression"); //ctx.testCompileError( // \\export fn entry() c_int { // \\ return 36893488147419103232; // \\} //, "1.zig", 2, 12, "integer value '36893488147419103232' cannot be stored in type 'c_int'"); //ctx.testCompileError( // \\comptime { // \\ var a: *align(4) align(4) i32 = 0; // \\} //, "1.zig", 2, 22, "Extra align qualifier"); //ctx.testCompileError( // \\comptime { // \\ var b: *const const i32 = 0; // \\} //, "1.zig", 2, 19, "Extra align qualifier"); //ctx.testCompileError( // \\comptime { // \\ var c: *volatile volatile i32 = 0; // \\} //, "1.zig", 2, 22, "Extra align qualifier"); //ctx.testCompileError( // \\comptime { // \\ var d: *allowzero allowzero i32 = 0; // \\} //, "1.zig", 2, 23, "Extra align qualifier"); }
test/stage2/compile_errors.zig
const inputFile = @embedFile("./input/day15.txt"); const std = @import("std"); const Allocator = std.mem.Allocator; const List = std.ArrayList; const Str = []const u8; const BitSet = std.DynamicBitSet; const StrMap = std.StringHashMap; const HashMap = std.HashMap; const Map = std.AutoHashMap; const PriorityQueue = std.PriorityQueue; const assert = std.debug.assert; const tokenize = std.mem.tokenize; const print = std.debug.print; const parseInt = std.fmt.parseInt; fn sort(comptime T: type, items: []T) void { std.sort.sort(T, items, {}, comptime std.sort.asc(T)); } fn println(x: Str) void { print("{s}\n", .{x}); } const QueueDatum = struct { size: u32, pos: u32, pub fn compare(_: void, a: @This(), b: @This()) std.math.Order { const ord = std.math.order(a.size, b.size); if (ord == .eq) { return std.math.order(a.pos, b.pos); // heuristic: favor items with bigger pos } else { return ord; } } }; fn gridDjikstra(input: Input, allocator: Allocator) !u32 { var visited = try BitSet.initEmpty(allocator, input.items.len); defer visited.deinit(); var queue = PriorityQueue(QueueDatum, void, QueueDatum.compare).init(allocator, {}); defer queue.deinit(); const nCols = @intCast(u32, input.nCols); // ============= Step 1: initialize start and kick off the queue ================ // (0, 0) is start const startPos = 0; visited.set(startPos); // ensures it doesn't get re-visited // (0, 1) and (1, 0) try queue.add(.{ .size = input.items[startPos + 1], .pos = startPos + 1 }); try queue.add(.{ .size = input.items[startPos + nCols], .pos = startPos + nCols }); // ============= Step 2: Run djikstra ================ while (queue.removeOrNull()) |datum| { const pos = datum.pos; const w = datum.size; if (pos == input.items.len - 1) { // reached the end! return w; } if (!visited.isSet(pos)) { // mark the node as visited and mark it with the current size visited.set(pos); // add all of the children to the queue const row = pos / nCols; const col = pos % nCols; // left, right, up, down // zig fmt: off if (col > 0) try queue.add(.{ .size = w + input.items[pos - 1], .pos = pos - 1 }); if (col < nCols - 1) try queue.add(.{ .size = w + input.items[pos + 1], .pos = pos + 1 }); if (row > 0) try queue.add(.{ .size = w + input.items[pos - nCols], .pos = pos - nCols }); if (row < input.nRows - 1) try queue.add(.{ .size = w + input.items[pos + nCols], .pos = pos + nCols }); // zig fmt: on } } unreachable; } pub fn main() !void { // Standard boilerplate for Aoc problems const stdout = std.io.getStdOut().writer(); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var gpaAllocator = gpa.allocator(); defer assert(!gpa.deinit()); // Check for memory leaks var arena = std.heap.ArenaAllocator.init(gpaAllocator); defer arena.deinit(); var allocator = arena.allocator(); const input = try parseInput(inputFile, allocator); try stdout.print("Part 1: {d}\n", .{try gridDjikstra(input, allocator)}); const expandedInput = try expandInput(input, 5); try stdout.print("Part 2: {d}\n", .{try gridDjikstra(expandedInput, allocator)}); } const Input = struct { items: Str, nRows: usize, nCols: usize, allocator: Allocator, pub fn deinit(self: @This()) void { self.allocator.free(self.items); } }; fn parseInput(input: Str, allocator: Allocator) !Input { var lines = try List(u8).initCapacity(allocator, 100 * 100); errdefer lines.deinit(); const nCols = std.mem.indexOfScalar(u8, input, '\n').?; var nRows: usize = 0; var it = tokenize(u8, input, "\n"); while (it.next()) |line| : (nRows += 1) { for (line) |c| { try lines.append(c - '0'); } } return Input{ .items = lines.toOwnedSlice(), .nRows = nRows, .nCols = nCols, .allocator = allocator }; } // Returns a new copy of input with the same allocator, expanded n times fn expandInput(input: Input, numExpand: usize) !Input { const allocator = input.allocator; var items = try allocator.alloc(u8, input.items.len * numExpand * numExpand); errdefer allocator.free(items); const nCols = input.nCols * numExpand; const nRows = input.nRows * numExpand; var row: usize = 0; while (row < nRows) : (row += 1) { var col: usize = 0; while (col < nCols) : (col += 1) { // wrap around const rowIncrement = row / input.nRows; const colIncrement = col / input.nCols; const inc = rowIncrement + colIncrement; const originalRow = row % input.nRows; const originalCol = col % input.nCols; items[row * nCols + col] = wrapAround(input.items[originalRow * input.nCols + originalCol], inc); } } return Input{ .items = items, .nRows = nRows, .nCols = nCols, .allocator = allocator }; } /// 5 + 5 -> 10 -> 1 fn wrapAround(x: u8, inc: usize) u8 { assert(x != 0); const inc_ = @intCast(u8, inc); return ((x + inc_ - 1) % 9) + 1; } test "part 2" { var allocator = std.testing.allocator; const input = try parseInput(inputFile, allocator); defer input.deinit(); const expandedInput = try expandInput(input, 5); defer expandedInput.deinit(); try std.testing.expectEqual(@as(usize, 2825), try gridDjikstra(expandedInput, allocator)); }
src/day15.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 int = i64; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day15.txt"); const Coord = [2]u16; const PriorityEntry = struct { pos: Coord, cost: u64, pub fn compare(_: void, a: @This(), b: @This()) std.math.Order { return std.math.order(a.cost, b.cost); } }; const Queue = std.PriorityDequeue(PriorityEntry, void, PriorityEntry.compare); fn wrap(val: u8) u8 { if (val <= 9) return val; var v2 = val; while (true) { v2 -= 9; if (v2 <= 9) return v2; } } pub fn main() !void { var width: usize = 0; var height: usize = 0; const grid = blk: { var recs = List(u8).init(gpa); errdefer recs.deinit(); var lines = tokenize(u8, data, "\r\n"); while (lines.next()) |line| { if (line.len == 0) { continue; } if (width == 0) { width = line.len; } else { assert(line.len == width); } try recs.ensureUnusedCapacity(line.len); for (line) |c| { recs.appendAssumeCapacity(c - '0'); } height += 1; } break :blk recs.toOwnedSlice(); }; defer gpa.free(grid); const pitch = width; const start = 0; var timer = try std.time.Timer.start(); const part1 = blk: { const costs = try gpa.alloc(u64, grid.len); defer gpa.free(costs); std.mem.set(u64, costs, std.math.maxInt(u64)); costs[0] = 0; var queue = Queue.init(gpa, {}); defer queue.deinit(); try queue.add(.{ .pos = .{0, 0}, .cost = costs[0] }); while (true) { const item = queue.removeMin(); const index = item.pos[1] * pitch + item.pos[0] + start; if (index == grid.len - 1) { break :blk item.cost; } if (costs[index] != item.cost) { continue; } if (item.pos[0] > 0) { if (item.cost + grid[index-1] < costs[index-1]) { costs[index-1] = item.cost + grid[index-1]; try queue.add(.{ .pos = .{ item.pos[0] - 1, item.pos[1] }, .cost = costs[index-1] }); } } if (item.pos[0] + 1 < width) { if (item.cost + grid[index+1] < costs[index+1]) { costs[index+1] = item.cost + grid[index+1]; try queue.add(.{ .pos = .{ item.pos[0] + 1, item.pos[1] }, .cost = costs[index+1] }); } } if (item.pos[1] > 0) { if (item.cost + grid[index-pitch] < costs[index-pitch]) { costs[index-pitch] = item.cost + grid[index-pitch]; try queue.add(.{ .pos = .{ item.pos[0], item.pos[1] - 1 }, .cost = costs[index-pitch] }); } } if (item.pos[1] + 1 < height) { if (item.cost + grid[index+pitch] < costs[index+pitch]) { costs[index+pitch] = item.cost + grid[index+pitch]; try queue.add(.{ .pos = .{ item.pos[0], item.pos[1] + 1 }, .cost = costs[index+pitch] }); } } } }; const tp1 = timer.lap(); const part2 = blk: { const costs = try gpa.alloc(u64, grid.len * 5 * 5); defer gpa.free(costs); std.mem.set(u64, costs, std.math.maxInt(u64)); costs[0] = 0; var queue = Queue.init(gpa, {}); defer queue.deinit(); try queue.add(.{ .pos = .{0, 0}, .cost = costs[0] }); while (true) { const item = queue.removeMin(); { const cost_idx = item.pos[1] * pitch * 5 + item.pos[0] + start; if (cost_idx == costs.len - 1) { break :blk item.cost; } if (costs[cost_idx] != item.cost) { continue; } } var neighbors = std.BoundedArray(Coord, 4).init(0) catch unreachable; if (item.pos[0] > 0) { neighbors.append(.{item.pos[0] - 1, item.pos[1]}) catch unreachable; } if (item.pos[0] + 1 < width*5) { neighbors.append(.{item.pos[0] + 1, item.pos[1]}) catch unreachable; } if (item.pos[1] > 0) { neighbors.append(.{item.pos[0], item.pos[1] - 1}) catch unreachable; } if (item.pos[1] + 1 < height*5) { neighbors.append(.{item.pos[0], item.pos[1] + 1}) catch unreachable; } for (neighbors.constSlice()) |n| { const grid_x = n[0] % width; const cell_x = n[0] / width; const grid_y = n[1] % height; const cell_y = n[1] / height; const grid_idx = grid_y * pitch + grid_x + start; const cost_idx = n[1] * pitch * 5 + n[0] + start; const cost_off = @intCast(u8, cell_x + cell_y); const grid_cost = wrap(grid[grid_idx] + cost_off); if (item.cost + grid_cost < costs[cost_idx]) { costs[cost_idx] = item.cost + grid_cost; try queue.add(.{ .pos = n, .cost = costs[cost_idx] }); } } } }; const tp2 = timer.read(); print("part1={}, part2={}\n", .{part1, part2}); print("tp1={}, tp2={}\n", .{tp1, tp2}); } // 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 eql = std.mem.eql; const parseEnum = std.meta.stringToEnum; 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/day15.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; pub var gpa_impl = std.heap.GeneralPurposeAllocator(.{}){}; pub const gpa = gpa_impl.allocator(); // Add utility functions here pub const default_delims = " ,:(){}<>[]!\r\n\t"; pub fn parseLines(comptime T: type, text: []const u8) []T { return parseLinesDelim(T, text, default_delims); } pub fn parseLinesDelim(comptime T: type, text: []const u8, delims: []const u8) []T { var list = List(T).init(gpa); var lines = tokenize(u8, text, "\r\n"); var linenum: u32 = 1; while (lines.next()) |line| : (linenum += 1) { if (line.len == 0) { continue; } list.append(parseLine(T, line, delims, linenum)) catch unreachable; } return list.toOwnedSlice(); } pub fn parse(comptime T: type, str: []const u8) T { return parseLine(T, str, default_delims, 1337); } pub fn parseLine(comptime T: type, str: []const u8, delims: []const u8, linenum: u32) T { var it = std.mem.tokenize(u8, str, delims); const result = parseNext(T, &it, linenum).?; if (it.next()) |next| { debugError("Extra token on line {}: '{s}'", .{linenum, next}); } return result; } pub fn parseNext(comptime T: type, it: *std.mem.TokenIterator(u8), linenum: u32) ?T { if (T == []const u8) return it.next(); switch (@typeInfo(T)) { .Int => { const token = it.next() orelse return null; return parseInt(T, token, 10) catch |err| debugError("invalid integer '{s}' on line {}, err={}", .{token, linenum, err}); }, .Float => { const token = it.next() orelse return null; return parseFloat(T, token) catch |err| debugError("invalid float '{s}' on line {}, err={}", .{token, linenum, err}); }, .Enum => { const token = it.next() orelse return null; return strToEnum(T, token) orelse debugError("cannot convert '{s}' to enum {s} on line {}", .{token, @typeName(T), linenum}); }, .Array => |arr| { var result: T = undefined; for (result) |*item, i| { item.* = parseNext(arr.child, it, linenum) orelse { if (i == 0) { return null; } debugError("Only found {} of {} items in array, on line {}\n", .{i, arr.len, linenum}); }; } return result; }, .Struct => |str| { var result: T = undefined; _ = str; var exit: bool = false; // workaround for control flow in inline for issues inline for (str.fields) |field, i| { parseNextStructField(&result, field, i, &exit, it, linenum); } if (exit) return null; return result; }, .Optional => |opt| { return @as(T, parseNext(opt.child, it, linenum)); }, .Pointer => |ptr| { if (ptr.size == .Slice) { var results = List(ptr.child).init(gpa); while (parseNext(ptr.child, it, linenum)) |value| { results.append(value) catch unreachable; } return results.toOwnedSlice(); } else @compileError("Unsupported type "++@typeName(T)); }, else => @compileError("Unsupported type "++@typeName(T)), } } fn parseNextStructField( result: anytype, comptime field: std.builtin.TypeInfo.StructField, comptime i: usize, exit: *bool, it: *std.mem.TokenIterator(u8), linenum: u32, ) void { if (!exit.*) { if (field.name[0] == '_') { @field(result, field.name) = field.default_value orelse undefined; } else if (parseNext(field.field_type, it, linenum)) |value| { @field(result, field.name) = value; } else if (field.default_value) |default| { @field(result, field.name) = default; } else if (i == 0) { exit.* = true; } else if (comptime std.meta.trait.isSlice(field.field_type)) { @field(result, field.name) = &.{}; } else { debugError("Missing field {s}.{s} and no default, on line {}", .{@typeName(@TypeOf(result)), field.name, linenum}); } } } test "parseLine" { assert(parseLine(u32, " 42 ", " ,", @src().line) == 42); assert(parseLine(f32, " 0.5", " ,", @src().line) == 0.5); assert(parseLine(f32, "42", " ,", @src().line) == 42); assert(parseLine(enum { foo, bar }, "foo", " ,", @src().line) == .foo); assert(eql(u16, &parseLine([3]u16, " 2, 15 4 ", " ,", @src().line), &[_]u16{2, 15, 4})); assert(eql(u16, parseLine([]u16, " 2, 15 4 ", " ,", @src().line), &[_]u16{2, 15, 4})); assert(parseLine(?f32, "42", " ,", @src().line).? == 42); assert(parseLine(?f32, "", " ,", @src().line) == null); assert(eql(u8, parseLine([]const u8, "foob", " ,", @src().line), "foob")); assert(eql(u8, parseLine([]const u8, "foob", " ,", @src().line), "foob")); assert(eql(u8, parseLine(Str, "foob", " ,", @src().line), "foob")); const T = struct { int: i32, float: f32, enumeration: enum{ foo, bar, baz }, _first: bool = true, array: [3]u16, string: []const u8, _skip: *@This(), optional: ?u16, tail: [][]const u8, }; { const a = parseLine(T, "4: 5.0, bar 4, 5, 6 badaboom", ":, ", @src().line); assert(a.int == 4); assert(a.float == 5.0); assert(a.enumeration == .bar); assert(a._first == true); assert(eql(u16, &a.array, &[_]u16{4, 5, 6})); assert(eql(u8, a.string, "badaboom")); assert(a.optional == null); assert(a.tail.len == 0); } { const a = parseLine(T, "-5: 3: foo 4, 5, 6 booptroop 53", ":, ", @src().line); assert(a.int == -5); assert(a.float == 3); assert(a.enumeration == .foo); assert(a._first == true); assert(eql(u16, &a.array, &[_]u16{4, 5, 6})); assert(eql(u8, a.string, "booptroop")); assert(a.optional.? == 53); assert(a.tail.len == 0); } { const a = parseLine(T, "+15: -10: baz 5, 6, 7 skidoosh 82 ruby supports bare words", ":, ", @src().line); assert(a.int == 15); assert(a.float == -10); assert(a.enumeration == .baz); assert(a._first == true); assert(eql(u16, &a.array, &[_]u16{5, 6, 7})); assert(eql(u8, a.string, "skidoosh")); assert(a.optional.? == 82); assert(a.tail.len == 4); assert(eql(u8, a.tail[0], "ruby")); assert(eql(u8, a.tail[1], "supports")); assert(eql(u8, a.tail[2], "bare")); assert(eql(u8, a.tail[3], "words")); } print("All tests passed.\n", .{}); } inline fn debugError(comptime fmt: []const u8, args: anytype) noreturn { if (std.debug.runtime_safety) { std.debug.panic(fmt, args); } 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 eql = std.mem.eql; const strToEnum = std.meta.stringToEnum; 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/util.zig
const c = @import("c.zig"); const nk = @import("../nuklear.zig"); const std = @import("std"); const testing = std.testing; pub const Text = c.nk_text_edit; pub const Flags = struct { read_only: bool = false, auto_select: bool = false, sig_enter: bool = false, allow_tab: bool = false, no_cursor: bool = false, selectable: bool = false, clipboard: bool = false, ctrl_enter_newline: bool = false, no_horizontal_scroll: bool = false, always_insert_mode: bool = false, multiline: bool = false, goto_end_on_activate: bool = false, fn toNulkear(flags: Flags) nk.Flags { return @intCast(nk.Flags, (c.NK_EDIT_READ_ONLY * @boolToInt(flags.read_only)) | (c.NK_EDIT_AUTO_SELECT * @boolToInt(flags.auto_select)) | (c.NK_EDIT_SIG_ENTER * @boolToInt(flags.sig_enter)) | (c.NK_EDIT_ALLOW_TAB * @boolToInt(flags.allow_tab)) | (c.NK_EDIT_NO_CURSOR * @boolToInt(flags.no_cursor)) | (c.NK_EDIT_SELECTABLE * @boolToInt(flags.selectable)) | (c.NK_EDIT_CLIPBOARD * @boolToInt(flags.clipboard)) | (c.NK_EDIT_CTRL_ENTER_NEWLINE * @boolToInt(flags.ctrl_enter_newline)) | (c.NK_EDIT_NO_HORIZONTAL_SCROLL * @boolToInt(flags.no_horizontal_scroll)) | (c.NK_EDIT_ALWAYS_INSERT_MODE * @boolToInt(flags.always_insert_mode)) | (c.NK_EDIT_MULTILINE * @boolToInt(flags.multiline)) | (c.NK_EDIT_GOTO_END_ON_ACTIVATE * @boolToInt(flags.goto_end_on_activate))); } pub const simple = Flags{ .always_insert_mode = true }; pub const field = Flags{ .always_insert_mode = true, .selectable = true, .clipboard = true, }; pub const box = Flags{ .always_insert_mode = true, .selectable = true, .clipboard = true, .multiline = true, .allow_tab = true, }; pub const editor = Flags{ .selectable = true, .multiline = true, .allow_tab = true, .clipboard = true, }; }; pub const Options = struct { filter: nk.Filter = c.nk_filter_default, flags: Flags = Flags{}, }; pub fn string( ctx: *nk.Context, buf: *[]u8, max: usize, opts: Options, ) nk.Flags { var c_len = @intCast(c_int, buf.len); defer buf.len = @intCast(usize, c_len); return c.nk_edit_string( ctx, opts.flags.toNulkear(), buf.ptr, &c_len, @intCast(c_int, max), opts.filter, ); } pub fn stringZ( ctx: *nk.Context, buf: [*:0]u8, max: usize, opts: Options, ) nk.Flags { return c.nk_edit_string_zero_terminated( ctx, opts.flags.toNulkear(), buf, @intCast(c_int, max), opts.filter, ); } pub fn buffer(ctx: *nk.Context, t: *Text, opts: Options) nk.Flags { return c.nk_edit_buffer(ctx, opts.flags.toNulkear(), t, opts.filter); } pub fn focus(ctx: *nk.Context, flags: nk.Flags) void { return c.nk_edit_focus(ctx, flags); } pub fn unfocus(ctx: *nk.Context) void { return c.nk_edit_unfocus(ctx); } test { testing.refAllDecls(@This()); }
src/edit.zig
const std = @import("std"); const core = @import("core/core.zig"); const renderer = core.renderer; const gl = core.gl; const alog = std.log.scoped(.alka); pub const Error = error{ AssetAlreadyExists, FailedToAllocate, InvalidAssetID } || core.Error; pub const AssetManager = struct { fn GenericType(comptime T: type) type { return struct { id: ?u64 = null, data: T = undefined, }; } const Shader = comptime GenericType(u32); const Texture = comptime GenericType(renderer.Texture); const Font = comptime GenericType(renderer.Font); alloc: *std.mem.Allocator = undefined, shaders: std.ArrayList(Shader) = undefined, textures: std.ArrayList(Texture) = undefined, fonts: std.ArrayList(Font) = undefined, fn findShader(self: AssetManager, id: u64) Error!u64 { var i: u64 = 0; while (i < self.shaders.items.len) : (i += 1) { if (self.shaders.items[i].id == id) return i; } return Error.InvalidAssetID; } fn findTexture(self: AssetManager, id: u64) Error!u64 { var i: u64 = 0; while (i < self.textures.items.len) : (i += 1) { if (self.textures.items[i].id == id) return i; } return Error.InvalidAssetID; } fn findFont(self: AssetManager, id: u64) Error!u64 { var i: u64 = 0; while (i < self.fonts.items.len) : (i += 1) { if (self.fonts.items[i].id == id) return i; } return Error.InvalidAssetID; } pub fn init(self: *AssetManager) Error!void { self.shaders = std.ArrayList(Shader).init(self.alloc); self.textures = std.ArrayList(Texture).init(self.alloc); self.fonts = std.ArrayList(Font).init(self.alloc); self.shaders.resize(5) catch { return Error.FailedToAllocate; }; self.textures.resize(32) catch { return Error.FailedToAllocate; }; self.fonts.resize(5) catch { return Error.FailedToAllocate; }; } pub fn deinit(self: *AssetManager) void { var i: u64 = 0; while (i < self.shaders.items.len) : (i += 1) { if (self.shaders.items[i].id) |id| { alog.notice("shader(id: {}) unloaded!", .{id}); gl.shaderProgramDelete(self.shaders.items[i].data); self.shaders.items[i].id = null; } } i = 0; while (i < self.textures.items.len) : (i += 1) { if (self.textures.items[i].id) |id| { alog.notice("texture(id: {}) unloaded!", .{id}); self.textures.items[i].data.destroy(); self.textures.items[i].id = null; } } i = 0; while (i < self.fonts.items.len) : (i += 1) { if (self.fonts.items[i].id) |id| { alog.notice("font(id: {}) unloaded!", .{id}); self.fonts.items[i].data.destroy(); self.fonts.items[i].id = null; } } self.shaders.deinit(); self.textures.deinit(); self.fonts.deinit(); } pub fn isShaderExists(self: AssetManager, id: u64) bool { var i: u64 = 0; while (i < self.shaders.items.len) : (i += 1) { if (self.shaders.items[i].id == id) return true; } return false; } pub fn isTextureExists(self: AssetManager, id: u64) bool { var i: u64 = 0; while (i < self.textures.items.len) : (i += 1) { if (self.textures.items[i].id == id) return true; } return false; } pub fn isFontExists(self: AssetManager, id: u64) bool { var i: u64 = 0; while (i < self.fonts.items.len) : (i += 1) { if (self.fonts.items[i].id == id) return true; } return false; } pub fn loadShader(self: *AssetManager, id: u64, vertex: []const u8, fragment: []const u8) Error!void { if (self.isShaderExists(id)) { alog.err("shader(id: {}) already exists!", .{id}); return Error.AssetAlreadyExists; } const program = try gl.shaderProgramCreate(self.alloc, vertex, fragment); try self.shaders.append(.{ .id = id, .data = program, }); alog.notice("shader(id: {}) loaded!", .{id}); } pub fn loadTexture(self: *AssetManager, id: u64, path: []const u8) Error!void { try self.loadTexturePro(id, try renderer.Texture.createFromPNG(self.alloc, path)); } pub fn loadTextureFromMemory(self: *AssetManager, id: u64, mem: []const u8) Error!void { try self.loadTexturePro(id, try renderer.Texture.createFromPNGMemory(mem)); } pub fn loadTexturePro(self: *AssetManager, id: u64, texture: renderer.Texture) Error!void { if (self.isTextureExists(id)) { alog.err("texture(id: {}) already exists!", .{id}); return Error.AssetAlreadyExists; } try self.textures.append(.{ .id = id, .data = texture }); alog.notice("texture(id: {}) loaded!", .{id}); } pub fn loadFont(self: *AssetManager, id: u64, path: []const u8, pixelsize: i32) Error!void { try self.loadFontPro(id, try renderer.Font.createFromTTF(self.alloc, path, null, pixelsize)); } pub fn loadFontFromMemory(self: *AssetManager, id: u64, mem: []const u8, pixelsize: i32) Error!void { try self.loadFontPro(id, try renderer.Font.createFromTTFMemory(self.alloc, mem, null, pixelsize)); } pub fn loadFontPro(self: *AssetManager, id: u64, font: renderer.Font) Error!void { if (self.isFontExists(id)) { alog.err("font(id: {}) already exists!", .{id}); return Error.AssetAlreadyExists; } try self.fonts.append(.{ .id = id, .data = font }); alog.notice("font(id: {}) loaded!", .{id}); } pub fn unloadShader(self: *AssetManager, id: u64) Error!void { if (!self.isShaderExists(id)) { alog.warn("shader(id: {}) does not exists!", .{id}); return; } else if (id == 0) { alog.warn("shader(id: {}) is provided by the engine! It is not meant to unload manually!", .{id}); return; } const i = try self.findShader(id); gl.shaderProgramDelete(self.shaders.items[i].data); _ = self.shaders.swapRemove(i); alog.notice("shader(id: {}) unloaded!", .{id}); } pub fn unloadTexture(self: *AssetManager, id: u64) Error!void { if (!self.isTextureExists(id)) { alog.warn("texture(id: {}) does not exists!", .{id}); return; } else if (id == 0) { alog.warn("texture(id: {}) is provided by the engine! It is not meant to unload manually!", .{id}); return; } const i = try self.findTexture(id); self.textures.items[i].texture.destroy(); _ = self.textures.swapRemove(i); alog.notice("texture(id: {}) unloaded!", .{id}); } pub fn unloadFont(self: *AssetManager, id: u64) Error!void { if (!self.isFontExists(id)) { alog.warn("font(id: {}) does not exists!", .{id}); return; } else if (id == 0) { alog.warn("font(id: {}) is provided by the engine! It is not meant to unload manually!", .{id}); return; } const i = try self.findFont(id); self.fonts.items[i].font.destroy(); _ = self.fonts.swapRemove(i); alog.notice("font(id: {}) unloaded!", .{id}); } pub fn getShader(self: AssetManager, id: u64) Error!u32 { const i = self.findShader(id) catch |err| { if (err == Error.InvalidAssetID) { alog.warn("shader(id: {}) does not exists!", .{id}); return Error.InvalidAssetID; } else return err; }; return self.shaders.items[i].data; } pub fn getTexture(self: AssetManager, id: u64) Error!renderer.Texture { const i = self.findTexture(id) catch |err| { if (err == Error.InvalidAssetID) { alog.warn("texture(id: {}) does not exists!", .{id}); return Error.InvalidAssetID; } else return err; }; return self.textures.items[i].data; } pub fn getFont(self: AssetManager, id: u64) Error!renderer.Font { const i = self.findFont(id) catch |err| { if (err == Error.InvalidAssetID) { alog.warn("font(id: {}) does not exists!", .{id}); return Error.InvalidAssetID; } else return err; }; return self.fonts.items[i].data; } };
src/assetmanager.zig
const gllparser = @import("../gllparser/gllparser.zig"); const Error = gllparser.Error; const Parser = gllparser.Parser; const ParserContext = gllparser.Context; const Result = gllparser.Result; const NodeName = gllparser.NodeName; const std = @import("std"); const testing = std.testing; const mem = std.mem; pub const Context = struct { // from byte (inclusive) from: u8, // to byte (inclusive) to: u8, }; pub const Value = struct { value: u8, pub fn deinit(self: *const @This(), allocator: mem.Allocator) void { _ = self; _ = allocator; } }; /// Matches any single byte in the specified range. pub fn ByteRange(comptime Payload: type) type { return struct { parser: Parser(Payload, Value) = Parser(Payload, Value).init(parse, nodeName, null, null), input: Context, const Self = @This(); pub fn init(allocator: mem.Allocator, input: Context) !*Parser(Payload, Value) { const self = Self{ .input = input }; return try self.parser.heapAlloc(allocator, self); } pub fn initStack(input: Context) Self { return Self{ .input = input }; } pub fn nodeName(parser: *const Parser(Payload, Value), node_name_cache: *std.AutoHashMap(usize, NodeName)) Error!u64 { _ = node_name_cache; const self = @fieldParentPtr(Self, "parser", parser); var v = std.hash_map.hashString("ByteRange"); v +%= self.input.from; v +%= self.input.to; return v; } pub fn parse(parser: *const Parser(Payload, Value), in_ctx: *const ParserContext(Payload, Value)) callconv(.Async) !void { const self = @fieldParentPtr(Self, "parser", parser); var ctx = in_ctx.with(self.input); defer ctx.results.close(); const src = ctx.src[ctx.offset..]; if (src.len == 0 or src[0] < self.input.from or src[0] > self.input.to) { // TODO(slimsag): include in error message the expected range (or "any byte" if full range) try ctx.results.add(Result(Value).initError(ctx.offset + 1, "expected byte range")); return; } try ctx.results.add(Result(Value).init(ctx.offset + 1, .{ .value = src[0] })); return; } }; } test "byte_range" { nosuspend { const allocator = testing.allocator; const Payload = void; var ctx = try ParserContext(Payload, Value).init(allocator, "hello world", {}); defer ctx.deinit(); var any_byte = try ByteRange(Payload).init(allocator, .{ .from = 0, .to = 255 }); defer any_byte.deinit(allocator, null); try any_byte.parse(&ctx); var sub = ctx.subscribe(); var first = sub.next().?; defer first.deinit(ctx.allocator); try testing.expectEqual(Result(Value).init(1, .{ .value = 'h' }), first); try testing.expect(sub.next() == null); } }
src/combn/parser/byte_range.zig
const std = @import("std"); const mem = std.mem; const log = std.log; const fs = std.fs; const exempt_files = [_][]const u8{ // This file is maintained by a separate project and does not come from glibc. "abilists", // Generated files. "include/libc-modules.h", "include/config.h", // These are easier to maintain like this, without updating to the abi-note.c // that glibc did upstream. "csu/abi-tag.h", "csu/abi-note.S", // We have patched these files to require fewer includes. "stdlib/at_quick_exit.c", "stdlib/atexit.c", "sysdeps/pthread/pthread_atfork.c", }; pub fn main() !void { var arena_instance = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena_instance.deinit(); const arena = arena_instance.allocator(); const args = try std.process.argsAlloc(arena); const glibc_src_path = args[1]; const zig_src_path = args[2]; const dest_dir_path = try std.fmt.allocPrint(arena, "{s}/lib/libc/glibc", .{zig_src_path}); var dest_dir = fs.cwd().openDir(dest_dir_path, .{ .iterate = true }) catch |err| { fatal("unable to open destination directory '{s}': {s}", .{ dest_dir_path, @errorName(err), }); }; defer dest_dir.close(); var glibc_src_dir = try fs.cwd().openDir(glibc_src_path, .{}); defer glibc_src_dir.close(); // Copy updated files from upstream. { var walker = try dest_dir.walk(arena); defer walker.deinit(); walk: while (try walker.next()) |entry| { if (entry.kind != .File) continue; if (mem.startsWith(u8, entry.basename, ".")) continue; for (exempt_files) |p| { if (mem.eql(u8, entry.path, p)) continue :walk; } glibc_src_dir.copyFile(entry.path, dest_dir, entry.path, .{}) catch |err| { log.warn("unable to copy '{s}/{s}' to '{s}/{s}': {s}", .{ glibc_src_path, entry.path, dest_dir_path, entry.path, @errorName(err), }); if (err == error.FileNotFound) { try dest_dir.deleteFile(entry.path); } }; } } // Warn about duplicated files inside glibc/include/* that can be omitted // because they are already in generic-glibc/*. var include_dir = dest_dir.openDir("include", .{ .iterate = true }) catch |err| { fatal("unable to open directory '{s}/include': {s}", .{ dest_dir_path, @errorName(err), }); }; defer include_dir.close(); const generic_glibc_path = try std.fmt.allocPrint( arena, "{s}/lib/libc/include/generic-glibc", .{zig_src_path}, ); var generic_glibc_dir = try fs.cwd().openDir(generic_glibc_path, .{}); defer generic_glibc_dir.close(); var walker = try include_dir.walk(arena); defer walker.deinit(); walk: while (try walker.next()) |entry| { if (entry.kind != .File) continue; if (mem.startsWith(u8, entry.basename, ".")) continue; for (exempt_files) |p| { if (mem.eql(u8, entry.path, p)) continue :walk; } const max_file_size = 10 * 1024 * 1024; const generic_glibc_contents = generic_glibc_dir.readFileAlloc( arena, entry.path, max_file_size, ) catch |err| switch (err) { error.FileNotFound => continue, else => |e| fatal("unable to load '{s}/include/{s}': {s}", .{ generic_glibc_path, entry.path, @errorName(e), }), }; const glibc_include_contents = include_dir.readFileAlloc( arena, entry.path, max_file_size, ) catch |err| { fatal("unable to load '{s}/include/{s}': {s}", .{ dest_dir_path, entry.path, @errorName(err), }); }; const whitespace = " \r\n\t"; const generic_glibc_trimmed = mem.trim(u8, generic_glibc_contents, whitespace); const glibc_include_trimmed = mem.trim(u8, glibc_include_contents, whitespace); if (mem.eql(u8, generic_glibc_trimmed, glibc_include_trimmed)) { log.warn("same contents: '{s}/include/{s}' and '{s}/include/{s}'", .{ generic_glibc_path, entry.path, dest_dir_path, entry.path, }); } } } fn fatal(comptime format: []const u8, args: anytype) noreturn { log.err(format, args); std.process.exit(1); }
tools/update_glibc.zig
const std = @import("std"); const clap = @import("clap"); const net = @import("net"); usingnamespace @import("commands.zig"); const Command = enum { fetch, search, tags, add, remove, }; fn printUsage() noreturn { const stderr = std.io.getStdErr().writer(); _ = stderr.write( \\zkg <cmd> [cmd specific options] \\ \\cmds: \\ search List packages matching your query \\ tags List tags found in your remote \\ add Add a package to your imports file \\ remove Remove a package from your imports file \\ fetch Download packages specified in your imports file into your \\ cache dir \\ \\for more information: zkg <cmd> --help \\ \\ ) catch {}; std.os.exit(1); } fn checkHelp(comptime summary: []const u8, comptime params: anytype, args: anytype) void { const stderr = std.io.getStdErr().writer(); if (args.flag("--help")) { _ = stderr.write(summary ++ "\n\n") catch {}; clap.help(stderr, params) catch {}; _ = stderr.write("\n") catch {}; std.os.exit(0); } } pub fn main() anyerror!void { const stderr = std.io.getStdErr().writer(); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = &gpa.allocator; try net.init(); defer net.deinit(); var iter = try clap.args.OsIterator.init(allocator); defer iter.deinit(); const cmd_str = (try iter.next()) orelse { try stderr.print("no command given\n", .{}); printUsage(); }; const cmd = inline for (std.meta.fields(Command)) |field| { if (std.mem.eql(u8, cmd_str, field.name)) { break @field(Command, field.name); } } else { try stderr.print("{} is not a valid command\n", .{cmd_str}); printUsage(); }; @setEvalBranchQuota(5000); switch (cmd) { .fetch => { const summary = "Download packages specified in your imports file into your cache dir"; const params = comptime [_]clap.Param(clap.Help){ clap.parseParam("-h, --help Display help") catch unreachable, clap.parseParam("-c, --cache-dir <DIR> cache directory, default is zig-cache") catch unreachable, }; var args = try clap.ComptimeClap(clap.Help, &params).parse(allocator, &iter, null); defer args.deinit(); checkHelp(summary, &params, args); try fetch(args.option("--cache-dir")); }, .search => { const summary = "Lists packages matching your query"; const params = comptime [_]clap.Param(clap.Help){ clap.parseParam("-h, --help Display help") catch unreachable, clap.parseParam("-r, --remote <REMOTE> Select which endpoint to query") catch unreachable, clap.parseParam("-t, --tag <TAG> Filter results for specific tag") catch unreachable, clap.parseParam("-n, --name <NAME> Query specific package") catch unreachable, clap.parseParam("-a, --author <NAME> Filter results for specific author") catch unreachable, clap.parseParam("-j, --json Print raw JSON") catch unreachable, }; var args = try clap.ComptimeClap(clap.Help, &params).parse(allocator, &iter, null); defer args.deinit(); checkHelp(summary, &params, args); const name_opt = args.option("--name"); const tag_opt = args.option("--tag"); const author_opt = args.option("--author"); var count: usize = 0; if (name_opt != null) count += 1; if (tag_opt != null) count += 1; if (author_opt != null) count += 1; if (count > 1) return error.OnlyOneQueryType; const search_params = if (name_opt) |name| SearchParams{ .name = name } else if (tag_opt) |tag| SearchParams{ .tag = tag } else if (author_opt) |author| SearchParams{ .author = author } else SearchParams{ .all = {} }; try search( allocator, search_params, args.flag("--json"), args.option("--remote"), ); }, .tags => { const summary = "List tags found in your remote"; const params = comptime [_]clap.Param(clap.Help){ clap.parseParam("-h, --help Display help") catch unreachable, clap.parseParam("-r, --remote <REMOTE> Select which endpoint to query") catch unreachable, }; var args = try clap.ComptimeClap(clap.Help, &params).parse(allocator, &iter, null); defer args.deinit(); checkHelp(summary, &params, args); try tags(allocator, args.option("--remote")); }, .add => { const summary = "Add a package to your imports file"; const params = comptime [_]clap.Param(clap.Help){ clap.parseParam("-h, --help Display help") catch unreachable, clap.parseParam("-r, --remote <REMOTE> Select which endpoint to query") catch unreachable, clap.parseParam("-a, --alias <ALIAS> Set the @import name of the package") catch unreachable, clap.Param(clap.Help){ .takes_value = .One, }, }; var args = try clap.ComptimeClap(clap.Help, &params).parse(allocator, &iter, null); defer args.deinit(); checkHelp(summary, &params, args); switch (args.positionals().len) { 0 => return error.MissingName, 1 => try add(allocator, args.positionals()[0], args.option("--alias"), args.option("--remote")), else => for (args.positionals()) |pos| { try add(allocator, pos, null, args.option("--remote")); }, } }, .remove => { const summary = "Remove a package from your imports file"; const params = comptime [_]clap.Param(clap.Help){ clap.parseParam("-h, --help Display help") catch unreachable, clap.Param(clap.Help){ .takes_value = .One, }, }; var args = try clap.ComptimeClap(clap.Help, &params).parse(allocator, &iter, null); defer args.deinit(); checkHelp(summary, &params, args); // there can only be one positional argument if (args.positionals().len > 1) { return error.TooManyPositionalArgs; } else if (args.positionals().len != 1) { return error.MissingName; } try remove(allocator, args.positionals()[0]); }, } }
src/main.zig
const std = @import("std"); const fs = std.fs; const io = std.io; const info = std.log.info; const print = std.debug.print; const fmt = std.fmt; const ArrayList = std.ArrayList; const utils = @import("utils.zig"); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; // Edit input1 to calc p1, by defualt this calculates p2 // const RuleDetails = union(enum) { or_rules: [][]usize, char: u8, }; const Rule = struct { allo: *std.mem.Allocator, id: usize, details: RuleDetails, pub fn init(allo: *std.mem.Allocator, line: []const u8) Rule { var line_iter = std.mem.tokenize(line, ":"); var rule_id = std.fmt.parseInt(usize, line_iter.next() orelse unreachable, 10) catch unreachable; var rules = std.mem.trim(u8, line_iter.next() orelse unreachable, " "); if (std.mem.indexOf(u8, line, "\"")) |_| { return Rule{ .allo = allo, .id = rule_id, .details = RuleDetails{ .char = rules[1], }, }; } else { var or_rules = allo.alloc([]usize, 0) catch unreachable; var parts = std.mem.split(line, " "); var genned = false; while (parts.next()) |sub_rule_id| { if (sub_rule_id[0] == '|' or !genned) { var inner_rules = allo.alloc(usize, 0) catch unreachable; or_rules = allo.realloc(or_rules, or_rules.len + 1) catch unreachable; or_rules[or_rules.len - 1] = inner_rules; genned = true; if (genned) { continue; } } var ruleset = or_rules[or_rules.len - 1]; ruleset = allo.realloc(ruleset, ruleset.len + 1) catch unreachable; ruleset[ruleset.len - 1] = std.fmt.parseInt(usize, sub_rule_id, 10) catch unreachable; or_rules[or_rules.len - 1] = ruleset; } return Rule{ .allo = allo, .id = rule_id, .details = RuleDetails{ .or_rules = or_rules, }, }; } } pub fn deinit(self: *Rule, allo: *std.mem.Allocator) void { _ = switch (self.details) { RuleDetails.or_rules => |rules| { for (rules) |rule| { allo.free(rule); } allo.free(rules); }, else => void, }; } pub fn matches(self: Rule, and_rules: []usize, all_rules: []?Rule, line: []const u8) bool { // only happens in p2 - actually this was the only addition to get p2 to work if (line.len == 0) { return false; } switch (self.details) { .char => |chr| { // bad char if (line[0] != chr) return false; if (and_rules.len > 0) { const and_rule = all_rules[and_rules[0]] orelse unreachable; const res = and_rule.matches(and_rules[1..], all_rules, line[1..]); return res; } else { return line.len == 1; } }, .or_rules => |or_rules| { // one of the rule sets must match for (or_rules) |rule_set, i| { const first_rule_id = rule_set[0]; const first_rule = all_rules[first_rule_id] orelse unreachable; const concatted = self.allo.alloc(usize, rule_set[1..].len + and_rules.len) catch unreachable; defer self.allo.free(concatted); std.mem.copy(usize, concatted, rule_set[1..]); std.mem.copy(usize, concatted[rule_set[1..].len..], and_rules); const match = first_rule.matches(concatted, all_rules, line); if (match) { return true; } } }, } return false; } }; pub fn main() !void { const begin = @divTrunc(std.time.nanoTimestamp(), 1000); // setup // defer _ = gpa.deinit(); var allo = &gpa.allocator; var lines: std.mem.TokenIterator = try utils.readInputLines(allo, "./input1"); defer allo.free(lines.buffer); var sum_p2: isize = 0; var rules: []?Rule = allo.alloc(?Rule, 0) catch unreachable; defer { for (rules) |*maybe_rule| { if (maybe_rule.*) |*rule| { rule.deinit(allo); } } allo.free(rules); } while (lines.next()) |line| { info("line: {} ", .{line}); if (std.mem.indexOf(u8, line, ":") != null) { const rule = Rule.init(allo, line); if (rules.len < rule.id + 1) { rules = allo.realloc(rules, rule.id + 1) catch unreachable; } rules[rule.id] = rule; } else { // match const main_rule = rules[0] orelse unreachable; if (main_rule.matches(&[0]usize{}, rules, line)) { sum_p2 += 1; } } } print("p2: {}\n", .{sum_p2}); // end const delta = @divTrunc(std.time.nanoTimestamp(), 1000) - begin; print("all done in {} microseconds\n", .{delta}); }
day_19/src/main.zig
const std = @import("std"); const ray = @import("translate-c/raylib.zig"); const BroadPhase = @import("physic/BroadPhase.zig"); const basic_type = @import("physic/basic_type.zig"); const Vec2 = basic_type.Vec2; const Rect = basic_type.Rect; const Index = basic_type.Index; const Proxy = BroadPhase.Proxy; const QueryCallback = BroadPhase.QueryCallback; fn randomPos(random: std.rand.Random, min: f32, max: f32) Vec2 { return Vec2.new( std.math.max(random.float(f32) * max, min), std.math.max(random.float(f32) * max, min), ); } fn randomVel(random: std.rand.Random, value: f32) Vec2 { return Vec2.new( (random.float(f32) - 0.5) * value * 2, (random.float(f32) - 0.5) * value * 2, ); } fn randomPosTo(random: std.rand.Random, m_pos: Vec2, h_size: Vec2) Vec2 { return Vec2.new( (random.float(f32) - 0.5) * h_size.x * 2 + m_pos.x, (random.float(f32) - 0.5) * h_size.y * 2 + m_pos.y, ); } pub const ScreenQueryCallback = struct { stack: std.ArrayList(Index), entities: std.ArrayList(Index), pub fn init(allocator: *std.mem.Allocator) ScreenQueryCallback { return .{ .stack = std.ArrayList(Index).init(allocator), .entities = std.ArrayList(Index).init(allocator), }; } pub fn deinit(q: *ScreenQueryCallback) void { q.stack.deinit(); q.entities.deinit(); } pub fn onOverlap(self: *ScreenQueryCallback, payload: void, entity: u32) void { _ = payload; self.entities.append(entity) catch unreachable; } pub fn reset(q: *ScreenQueryCallback) void { q.entities.clearRetainingCapacity(); } }; pub const RedCallback = struct { const Pair = struct { left: Index, right: Index }; stack: std.ArrayList(Index), pairs: std.ArrayList(Pair), map: std.AutoHashMap(u32, void), pub fn init(allocator: *std.mem.Allocator) RedCallback { return .{ .stack = std.ArrayList(Index).init(allocator), .pairs = std.ArrayList(Pair).init(allocator), .map = std.AutoHashMap(u32, void).init(allocator), }; } pub fn deinit(q: *RedCallback) void { q.stack.deinit(); q.pairs.deinit(); q.map.deinit(); } pub fn onOverlap(self: *RedCallback, left: u32, right: u32) void { if (left == right) return; const l = if(left < right) left else right; const r = if(l == left) right else left; const key = <KEY>; if (self.map.contains(key)) return; self.map.putNoClobber(key, {}) catch unreachable; self.pairs.append(.{ .left = l, .right = r }) catch unreachable; } pub fn reset(q: *RedCallback) void { q.pairs.clearRetainingCapacity(); q.map.clearRetainingCapacity(); } }; pub fn main() !void { // Initialization //-------------------------------------------------------------------------------------- const pixel = 20; const screenWidth = 1200; const screenHeight = 675; var m_screen = Vec2.new(20, 20); const h_screen_size = Vec2.new(screenWidth / (2 * pixel), screenHeight / (2 * pixel)); ray.InitWindow(screenWidth, screenHeight, "Physic zig zag"); defer ray.CloseWindow(); ray.SetTargetFPS(60); const allocator = std.heap.c_allocator; var bp = BroadPhase.init(allocator); defer bp.deinit(); var stack = std.ArrayList(u8).init(allocator); defer stack.deinit(); var writer = stack.writer(); var random = std.rand.Xoshiro256.init(0).random(); const Entity = std.MultiArrayList(struct { entity: u32, pos: Vec2, half_size: Vec2, proxy: Proxy = undefined, vel: Vec2, refresh_vel: f32, }); var manager = Entity{}; defer manager.deinit(allocator); var total_small: u32 = 5000; var total_big: u32 = 100; const max_x: f32 = 1000; const min_size: f32 = 5; const max_size: f32 = 10; // bp.preCreateGrid(Vec2.zero(), Vec2.new(max_x, max_x)); try manager.setCapacity(allocator, total_big + total_small); // Init entities { var entity: u32 = 0; while (entity < total_small) : (entity += 1) { try manager.append(allocator, .{ .entity = entity, .pos = randomPos(random, 0, max_x), .half_size = BroadPhase.half_element_size, .vel = randomVel(random, 15), .refresh_vel = random.float(f32) * 10, }); } while (entity < total_small + total_big) : (entity += 1) { try manager.append(allocator, .{ .entity = entity, .pos = randomPos(random, 0, max_x), .half_size = randomPos(random, min_size, max_size), .vel = randomVel(random, 15), .refresh_vel = random.float(f32) * 10, }); } } var slice = manager.slice(); var entities = slice.items(.entity); var position = slice.items(.pos); var proxy = slice.items(.proxy); var h_size = slice.items(.half_size); var refresh_vel = slice.items(.refresh_vel); var vel = slice.items(.vel); { var timer = try std.time.Timer.start(); var index: u32 = 0; while (index < total_small) : (index += 1) { const p = bp.createProxy(position[index], h_size[index], entities[index]); std.debug.assert(p == .small); proxy[index] = p; } var time_0 = timer.read(); std.debug.print("add {} entity to grid take {}ms\n", .{ total_small, time_0 / std.time.ns_per_ms }); timer = try std.time.Timer.start(); while (index < slice.len) : (index += 1) { const p = bp.createProxy(position[index], h_size[index], entities[index]); std.debug.assert(p == .big); proxy[index] = p; } time_0 = timer.read(); std.debug.print("add {} entity to tree take {}ms\n", .{ total_big, time_0 / std.time.ns_per_ms }); } var callback = QueryCallback.init(allocator); defer callback.deinit(); var screen_callback = ScreenQueryCallback.init(allocator); defer screen_callback.deinit(); var red_callback = RedCallback.init(allocator); defer red_callback.deinit(); var update = true; // Main game loop while (!ray.WindowShouldClose()) { if (ray.IsKeyDown(ray.KEY_H)) { m_screen.x -= 0.016 * 50.0; } if (ray.IsKeyDown(ray.KEY_L)) { m_screen.x += 0.016 * 50.0; } if (ray.IsKeyDown(ray.KEY_K)) { m_screen.y += 0.016 * 50.0; } if (ray.IsKeyDown(ray.KEY_J)) { m_screen.y -= 0.016 * 50.0; } if (ray.IsKeyPressed(ray.KEY_F)) { var index: u32 = 0; var entity = @intCast(u32, slice.len); while (index < 10) : (index += 1) { const pos = randomPosTo(random, m_screen, h_screen_size); try manager.append(allocator, .{ .entity = entity, .pos = pos, .half_size = BroadPhase.half_element_size, .proxy = bp.createProxy(pos, BroadPhase.half_element_size, entity), .vel = randomVel(random, 15), .refresh_vel = random.float(f32) * 10, }); entity += 1; } index = 0; while (index < 2) : (index += 1) { const pos = randomPosTo(random, m_screen, h_screen_size); const half_size = randomPos(random, min_size, max_size); try manager.append(allocator, .{ .entity = entity, .pos = pos, .half_size = half_size, .proxy = bp.createProxy(pos, half_size, entity), .vel = randomVel(random, 15), .refresh_vel = random.float(f32) * 10, }); entity += 1; } total_big += 2; total_small += 10; slice = manager.slice(); entities = slice.items(.entity); position = slice.items(.pos); proxy = slice.items(.proxy); refresh_vel = slice.items(.refresh_vel); vel = slice.items(.vel); h_size = slice.items(.half_size); } if (ray.IsKeyPressed(ray.KEY_SPACE)) { update = !update; } //timer for (refresh_vel) |*t, i| { t.* -= 0.016; if (t.* <= 0) { t.* = random.float(f32) * 10; vel[i] = randomVel(random, 15); } } //Move var move_timer = try std.time.Timer.start(); if (update) { for (position) |*pos, i| { const new_pos = pos.add(vel[i].scale(0.016)); bp.moveProxy(proxy[i], pos.*, new_pos, h_size[i]); pos.* = new_pos; } } const moved_time = move_timer.read(); // query var index: u32 = 0; var timer = try std.time.Timer.start(); defer callback.total = 0; while (index < slice.len) : (index += 1) { try bp.query(position[index], h_size[index], proxy[index], entities[index], &callback); } const time_0 = timer.read(); defer screen_callback.reset(); defer red_callback.reset(); try bp.userQuery(m_screen, h_screen_size, {}, &screen_callback); for (screen_callback.entities.items) |entity| { try bp.query(position[entity], h_size[entity], proxy[entity], entities[entity], &red_callback); } ray.BeginDrawing(); defer ray.EndDrawing(); ray.ClearBackground(ray.BLACK); for (red_callback.pairs.items) |p| { const aabb_left = Rect.newRectInt( position[p.left], h_size[p.left], m_screen, h_screen_size, ); ray.DrawRectangle( aabb_left.lower_bound.x * pixel, aabb_left.lower_bound.y * pixel, aabb_left.upper_bound.x * pixel, aabb_left.upper_bound.y * pixel, ray.SKYBLUE, ); const aabb_right = Rect.newRectInt( position[p.right], h_size[p.right], m_screen, h_screen_size, ); ray.DrawRectangle( aabb_right.lower_bound.x * pixel, aabb_right.lower_bound.y * pixel, aabb_right.upper_bound.x * pixel, aabb_right.upper_bound.y * pixel, ray.SKYBLUE, ); } for (screen_callback.entities.items) |entity| { const is_draw = blk: { for (red_callback.pairs.items) |p| { if (entity == p.left or entity == p.right) { break :blk false; } } else { break :blk true; } break :blk true; }; if (is_draw) { const aabb = Rect.newRectInt( position[entity], h_size[entity], m_screen, h_screen_size, ); ray.DrawRectangle( aabb.lower_bound.x * pixel, aabb.lower_bound.y * pixel, aabb.upper_bound.x * pixel, aabb.upper_bound.y * pixel, ray.RED, ); } } try std.fmt.format(writer, "Total Grids: {}", .{bp.grid_map.count()}); try stack.append(0); ray.DrawText(@ptrCast([*c]const u8, stack.items), 20, 20, 20, ray.BEIGE); stack.clearRetainingCapacity(); try std.fmt.format( writer, "Move big: {} and small: {}. Take {}ms\n", .{ total_big, total_small, moved_time / std.time.ns_per_ms }, ); try stack.append(0); ray.DrawText(@ptrCast([*c]const u8, stack.items), 20, 42, 20, ray.BEIGE); stack.clearRetainingCapacity(); try std.fmt.format( writer, "Query big: {} and small: {}. Take {}ms with {} pairs\n", .{ total_big, total_small, time_0 / std.time.ns_per_ms, callback.total }, ); try stack.append(0); ray.DrawText(@ptrCast([*c]const u8, stack.items), 20, 64, 20, ray.BEIGE); stack.clearRetainingCapacity(); try std.fmt.format(writer, "Objects on screen {}\n", .{screen_callback.entities.items.len}); try stack.append(0); ray.DrawText(@ptrCast([*c]const u8, stack.items), 20, 86, 20, ray.BEIGE); stack.clearRetainingCapacity(); defer screen_callback.reset(); try std.fmt.format(writer, "Pairs overlap on screen {}\n", .{red_callback.pairs.items.len}); try stack.append(0); ray.DrawText(@ptrCast([*c]const u8, stack.items), 20, 108, 20, ray.BEIGE); stack.clearRetainingCapacity(); } }
src/main.zig
const std = @import("std"); const Pkg = std.build.Pkg; const FileSource = std.build.FileSource; const LibExeObjStep = std.build.LibExeObjStep; fn concat(lhs: []const u8, rhs: []const u8) []const u8 { if (std.testing.allocator.alloc(u8, lhs.len + rhs.len)) |buf| { for (lhs) |c, i| { buf[i] = c; } for (rhs) |c, i| { buf[i + lhs.len] = c; } return buf; } else |_| { @panic("alloc"); } } pub fn addTo(exe: *LibExeObjStep, relativePath: []const u8) void { // pkgs/glfw/pkgs/glfw/src/CMakeLists.txt exe.addPackage(Pkg{ .name = "glfw", .path = FileSource{ .path = concat(relativePath, "/src/main.zig") }, }); exe.defineCMacro("_GLFW_WIN32", "1"); exe.defineCMacro("UNICODE", "1"); exe.defineCMacro("_UNICODE", "1"); exe.addIncludeDir(concat(relativePath, "/pkgs/glfw/include")); // exe.addIncludeDir(concat(relativePath, "/pkgs/glfw/src")); exe.addCSourceFiles(&.{ concat(relativePath, "/pkgs/glfw/src/context.c"), concat(relativePath, "/pkgs/glfw/src/init.c"), concat(relativePath, "/pkgs/glfw/src/input.c"), concat(relativePath, "/pkgs/glfw/src/monitor.c"), concat(relativePath, "/pkgs/glfw/src/platform.c"), concat(relativePath, "/pkgs/glfw/src/vulkan.c"), concat(relativePath, "/pkgs/glfw/src/window.c"), concat(relativePath, "/pkgs/glfw/src/egl_context.c"), concat(relativePath, "/pkgs/glfw/src/osmesa_context.c"), concat(relativePath, "/pkgs/glfw/src/null_init.c"), concat(relativePath, "/pkgs/glfw/src/null_monitor.c"), concat(relativePath, "/pkgs/glfw/src/null_window.c"), concat(relativePath, "/pkgs/glfw/src/null_joystick.c"), }, &.{}); exe.addCSourceFiles(&.{ concat(relativePath, "/pkgs/glfw/src/win32_module.c"), concat(relativePath, "/pkgs/glfw/src/win32_time.c"), concat(relativePath, "/pkgs/glfw/src/win32_thread.c"), concat(relativePath, "/pkgs/glfw/src/win32_init.c"), concat(relativePath, "/pkgs/glfw/src/win32_joystick.c"), concat(relativePath, "/pkgs/glfw/src/win32_monitor.c"), concat(relativePath, "/pkgs/glfw/src/win32_window.c"), concat(relativePath, "/pkgs/glfw/src/wgl_context.c"), }, &.{}); exe.linkSystemLibrary("gdi32"); }
pkgs/glfw/pkg.zig
const wchar_t = c_int; const __off_t = c_long; const __off64_t = c_long; const _IO_lock_t = anyopaque; const union_unnamed_5 = extern union { __wch: c_uint, __wchb: [4]u8, }; const __mbstate_t = extern struct { __count: c_int, __value: union_unnamed_5, }; const struct___va_list_tag = extern struct { gp_offset: c_uint, fp_offset: c_uint, overflow_arg_area: ?*anyopaque, reg_save_area: ?*anyopaque, }; const __builtin_va_list = [1]struct___va_list_tag; const va_list = __builtin_va_list; const NULL = @import("std").zig.c_translation.cast(?*anyopaque, @as(c_int, 0)); const __builtin_bswap16 = @import("std").zig.c_builtins.__builtin_bswap16; const __builtin_bswap32 = @import("std").zig.c_builtins.__builtin_bswap32; const __builtin_bswap64 = @import("std").zig.c_builtins.__builtin_bswap64; const __LITTLE_ENDIAN = @as(c_int, 1234); const __BIG_ENDIAN = @as(c_int, 4321); const __PDP_ENDIAN = @as(c_int, 3412); const __BYTE_ORDER = __LITTLE_ENDIAN; const __OPTIMIZE__ = @as(c_int, 1); const __ORDER_LITTLE_ENDIAN__ = @as(c_int, 1234); const __ORDER_BIG_ENDIAN__ = @as(c_int, 4321); const __ORDER_PDP_ENDIAN__ = @as(c_int, 3412); const __PRI64_PREFIX = "l"; const __PRIPTR_PREFIX = "l"; const PRId8 = "d"; const PRId16 = "d"; const PRId32 = "d"; const PRId64 = __PRI64_PREFIX ++ "d"; const PRIdLEAST8 = "d"; const PRIdLEAST16 = "d"; const PRIdLEAST32 = "d"; const PRIdLEAST64 = __PRI64_PREFIX ++ "d"; const PRIdFAST8 = "d"; const PRIdFAST16 = __PRIPTR_PREFIX ++ "d"; const PRIdFAST32 = __PRIPTR_PREFIX ++ "d"; const PRIdFAST64 = __PRI64_PREFIX ++ "d"; const PRIi8 = "i"; const PRIi16 = "i"; const PRIi32 = "i"; const PRIi64 = __PRI64_PREFIX ++ "i"; const PRIiLEAST8 = "i"; const PRIiLEAST16 = "i"; const PRIiLEAST32 = "i"; const PRIiLEAST64 = __PRI64_PREFIX ++ "i"; const PRIiFAST8 = "i"; const PRIiFAST16 = __PRIPTR_PREFIX ++ "i"; const PRIiFAST32 = __PRIPTR_PREFIX ++ "i"; const PRIiFAST64 = __PRI64_PREFIX ++ "i"; const PRIo8 = "o"; const PRIo16 = "o"; const PRIo32 = "o"; const PRIo64 = __PRI64_PREFIX ++ "o"; const PRIoLEAST8 = "o"; const PRIoLEAST16 = "o"; const PRIoLEAST32 = "o"; const PRIoLEAST64 = __PRI64_PREFIX ++ "o"; const PRIoFAST8 = "o"; const PRIoFAST16 = __PRIPTR_PREFIX ++ "o"; const PRIoFAST32 = __PRIPTR_PREFIX ++ "o"; const PRIoFAST64 = __PRI64_PREFIX ++ "o"; const PRIu8 = "u"; const PRIu16 = "u"; const PRIu32 = "u"; const PRIu64 = __PRI64_PREFIX ++ "u"; const PRIuLEAST8 = "u"; const PRIuLEAST16 = "u"; const PRIuLEAST32 = "u"; const PRIuLEAST64 = __PRI64_PREFIX ++ "u"; const PRIuFAST8 = "u"; const PRIuFAST16 = __PRIPTR_PREFIX ++ "u"; const PRIuFAST32 = __PRIPTR_PREFIX ++ "u"; const PRIuFAST64 = __PRI64_PREFIX ++ "u"; const PRIx8 = "x"; const PRIx16 = "x"; const PRIx32 = "x"; const PRIx64 = __PRI64_PREFIX ++ "x"; const PRIxLEAST8 = "x"; const PRIxLEAST16 = "x"; const PRIxLEAST32 = "x"; const PRIxLEAST64 = __PRI64_PREFIX ++ "x"; const PRIxFAST8 = "x"; const PRIxFAST16 = __PRIPTR_PREFIX ++ "x"; const PRIxFAST32 = __PRIPTR_PREFIX ++ "x"; const PRIxFAST64 = __PRI64_PREFIX ++ "x"; const PRIX8 = "X"; const PRIX16 = "X"; const PRIX32 = "X"; const PRIX64 = __PRI64_PREFIX ++ "X"; const PRIXLEAST8 = "X"; const PRIXLEAST16 = "X"; const PRIXLEAST32 = "X"; const PRIXLEAST64 = __PRI64_PREFIX ++ "X"; const PRIXFAST8 = "X"; const PRIXFAST16 = __PRIPTR_PREFIX ++ "X"; const PRIXFAST32 = __PRIPTR_PREFIX ++ "X"; const PRIXFAST64 = __PRI64_PREFIX ++ "X"; const PRIdMAX = __PRI64_PREFIX ++ "d"; const PRIiMAX = __PRI64_PREFIX ++ "i"; const PRIoMAX = __PRI64_PREFIX ++ "o"; const PRIuMAX = __PRI64_PREFIX ++ "u"; const PRIxMAX = __PRI64_PREFIX ++ "x"; const PRIXMAX = __PRI64_PREFIX ++ "X"; const PRIdPTR = __PRIPTR_PREFIX ++ "d"; const PRIiPTR = __PRIPTR_PREFIX ++ "i"; const PRIoPTR = __PRIPTR_PREFIX ++ "o"; const PRIuPTR = __PRIPTR_PREFIX ++ "u"; const struct__IO_FILE = extern struct { _flags: c_int, _IO_read_ptr: [*c]u8, _IO_read_end: [*c]u8, _IO_read_base: [*c]u8, _IO_write_base: [*c]u8, _IO_write_ptr: [*c]u8, _IO_write_end: [*c]u8, _IO_buf_base: [*c]u8, _IO_buf_end: [*c]u8, _IO_save_base: [*c]u8, _IO_backup_base: [*c]u8, _IO_save_end: [*c]u8, _markers: ?*struct__IO_marker, _chain: [*c]struct__IO_FILE, _fileno: c_int, _flags2: c_int, _old_offset: __off_t, _cur_column: c_ushort, _vtable_offset: i8, _shortbuf: [1]u8, _lock: ?*_IO_lock_t, _offset: __off64_t, _codecvt: ?*struct__IO_codecvt, _wide_data: ?*struct__IO_wide_data, _freeres_list: [*c]struct__IO_FILE, _freeres_buf: ?*anyopaque, __pad5: usize, _mode: c_int, _unused2: [20]u8, }; const __FILE = struct__IO_FILE; const FILE = struct__IO_FILE; const fpos_t = __fpos_t; const struct__G_fpos_t = extern struct { __pos: __off_t, __state: __mbstate_t, }; const __fpos_t = struct__G_fpos_t; const struct__G_fpos64_t = extern struct { __pos: __off64_t, __state: __mbstate_t, }; const __fpos64_t = struct__G_fpos64_t; const struct__IO_marker = opaque {}; const struct__IO_codecvt = opaque {}; const struct__IO_wide_data = opaque {}; pub extern fn SDL_GetPlatform() [*c]const u8; pub const SDL_FALSE = @enumToInt(enum_unnamed_14.SDL_FALSE); pub const SDL_TRUE = @enumToInt(enum_unnamed_14.SDL_TRUE); const enum_unnamed_14 = enum(c_int) { SDL_FALSE = 0, SDL_TRUE = 1, _, }; pub const SDL_bool = enum_unnamed_14; pub const Sint8 = i8; pub const Uint8 = u8; pub const Sint16 = i16; pub const Uint16 = u16; pub const Sint32 = i32; pub const Uint32 = u32; pub const Sint64 = i64; pub const Uint64 = u64; pub const SDL_compile_time_assert_uint8 = [1]c_int; pub const SDL_compile_time_assert_sint8 = [1]c_int; pub const SDL_compile_time_assert_uint16 = [1]c_int; pub const SDL_compile_time_assert_sint16 = [1]c_int; pub const SDL_compile_time_assert_uint32 = [1]c_int; pub const SDL_compile_time_assert_sint32 = [1]c_int; pub const SDL_compile_time_assert_uint64 = [1]c_int; pub const SDL_compile_time_assert_sint64 = [1]c_int; pub const DUMMY_ENUM_VALUE = @enumToInt(enum_unnamed_15.DUMMY_ENUM_VALUE); const enum_unnamed_15 = enum(c_int) { DUMMY_ENUM_VALUE, _, }; pub const SDL_compile_time_assert_enum = [1]c_int; pub extern fn SDL_malloc(size: usize) ?*anyopaque; pub extern fn SDL_calloc(nmemb: usize, size: usize) ?*anyopaque; pub extern fn SDL_realloc(mem: ?*anyopaque, size: usize) ?*anyopaque; pub extern fn SDL_free(mem: ?*anyopaque) void; pub const SDL_malloc_func = ?fn (usize) callconv(.C) ?*anyopaque; pub const SDL_calloc_func = ?fn (usize, usize) callconv(.C) ?*anyopaque; pub const SDL_realloc_func = ?fn (?*anyopaque, usize) callconv(.C) ?*anyopaque; pub const SDL_free_func = ?fn (?*anyopaque) callconv(.C) void; pub extern fn SDL_GetMemoryFunctions(malloc_func: [*c]SDL_malloc_func, calloc_func: [*c]SDL_calloc_func, realloc_func: [*c]SDL_realloc_func, free_func: [*c]SDL_free_func) void; pub extern fn SDL_SetMemoryFunctions(malloc_func: SDL_malloc_func, calloc_func: SDL_calloc_func, realloc_func: SDL_realloc_func, free_func: SDL_free_func) c_int; pub extern fn SDL_GetNumAllocations() c_int; pub extern fn SDL_getenv(name: [*c]const u8) [*c]u8; pub extern fn SDL_setenv(name: [*c]const u8, value: [*c]const u8, overwrite: c_int) c_int; pub extern fn SDL_qsort(base: ?*anyopaque, nmemb: usize, size: usize, compare: ?fn (?*const anyopaque, ?*const anyopaque) callconv(.C) c_int) void; pub extern fn SDL_abs(x: c_int) c_int; pub extern fn SDL_isalpha(x: c_int) c_int; pub extern fn SDL_isalnum(x: c_int) c_int; pub extern fn SDL_isblank(x: c_int) c_int; pub extern fn SDL_iscntrl(x: c_int) c_int; pub extern fn SDL_isdigit(x: c_int) c_int; pub extern fn SDL_isxdigit(x: c_int) c_int; pub extern fn SDL_ispunct(x: c_int) c_int; pub extern fn SDL_isspace(x: c_int) c_int; pub extern fn SDL_isupper(x: c_int) c_int; pub extern fn SDL_islower(x: c_int) c_int; pub extern fn SDL_isprint(x: c_int) c_int; pub extern fn SDL_isgraph(x: c_int) c_int; pub extern fn SDL_toupper(x: c_int) c_int; pub extern fn SDL_tolower(x: c_int) c_int; pub extern fn SDL_crc32(crc: Uint32, data: ?*const anyopaque, len: usize) Uint32; pub extern fn SDL_memset(dst: ?*anyopaque, c: c_int, len: usize) ?*anyopaque; // /usr/include/SDL2/SDL_stdinc.h:491:9: warning: TODO complex switch // /usr/include/SDL2/SDL_stdinc.h:462:23: warning: unable to translate function, demoted to extern pub extern fn SDL_memset4(arg_dst: ?*anyopaque, arg_val: Uint32, arg_dwords: usize) void; pub extern fn SDL_memcpy(dst: ?*anyopaque, src: ?*const anyopaque, len: usize) ?*anyopaque; pub extern fn SDL_memmove(dst: ?*anyopaque, src: ?*const anyopaque, len: usize) ?*anyopaque; pub extern fn SDL_memcmp(s1: ?*const anyopaque, s2: ?*const anyopaque, len: usize) c_int; pub extern fn SDL_wcslen(wstr: [*c]const wchar_t) usize; pub extern fn SDL_wcslcpy(dst: [*c]wchar_t, src: [*c]const wchar_t, maxlen: usize) usize; pub extern fn SDL_wcslcat(dst: [*c]wchar_t, src: [*c]const wchar_t, maxlen: usize) usize; pub extern fn SDL_wcsdup(wstr: [*c]const wchar_t) [*c]wchar_t; pub extern fn SDL_wcsstr(haystack: [*c]const wchar_t, needle: [*c]const wchar_t) [*c]wchar_t; pub extern fn SDL_wcscmp(str1: [*c]const wchar_t, str2: [*c]const wchar_t) c_int; pub extern fn SDL_wcsncmp(str1: [*c]const wchar_t, str2: [*c]const wchar_t, maxlen: usize) c_int; pub extern fn SDL_wcscasecmp(str1: [*c]const wchar_t, str2: [*c]const wchar_t) c_int; pub extern fn SDL_wcsncasecmp(str1: [*c]const wchar_t, str2: [*c]const wchar_t, len: usize) c_int; pub extern fn SDL_strlen(str: [*c]const u8) usize; pub extern fn SDL_strlcpy(dst: [*c]u8, src: [*c]const u8, maxlen: usize) usize; pub extern fn SDL_utf8strlcpy(dst: [*c]u8, src: [*c]const u8, dst_bytes: usize) usize; pub extern fn SDL_strlcat(dst: [*c]u8, src: [*c]const u8, maxlen: usize) usize; pub extern fn SDL_strdup(str: [*c]const u8) [*c]u8; pub extern fn SDL_strrev(str: [*c]u8) [*c]u8; pub extern fn SDL_strupr(str: [*c]u8) [*c]u8; pub extern fn SDL_strlwr(str: [*c]u8) [*c]u8; pub extern fn SDL_strchr(str: [*c]const u8, c: c_int) [*c]u8; pub extern fn SDL_strrchr(str: [*c]const u8, c: c_int) [*c]u8; pub extern fn SDL_strstr(haystack: [*c]const u8, needle: [*c]const u8) [*c]u8; pub extern fn SDL_strtokr(s1: [*c]u8, s2: [*c]const u8, saveptr: [*c][*c]u8) [*c]u8; pub extern fn SDL_utf8strlen(str: [*c]const u8) usize; pub extern fn SDL_itoa(value: c_int, str: [*c]u8, radix: c_int) [*c]u8; pub extern fn SDL_uitoa(value: c_uint, str: [*c]u8, radix: c_int) [*c]u8; pub extern fn SDL_ltoa(value: c_long, str: [*c]u8, radix: c_int) [*c]u8; pub extern fn SDL_ultoa(value: c_ulong, str: [*c]u8, radix: c_int) [*c]u8; pub extern fn SDL_lltoa(value: Sint64, str: [*c]u8, radix: c_int) [*c]u8; pub extern fn SDL_ulltoa(value: Uint64, str: [*c]u8, radix: c_int) [*c]u8; pub extern fn SDL_atoi(str: [*c]const u8) c_int; pub extern fn SDL_atof(str: [*c]const u8) f64; pub extern fn SDL_strtol(str: [*c]const u8, endp: [*c][*c]u8, base: c_int) c_long; pub extern fn SDL_strtoul(str: [*c]const u8, endp: [*c][*c]u8, base: c_int) c_ulong; pub extern fn SDL_strtoll(str: [*c]const u8, endp: [*c][*c]u8, base: c_int) Sint64; pub extern fn SDL_strtoull(str: [*c]const u8, endp: [*c][*c]u8, base: c_int) Uint64; pub extern fn SDL_strtod(str: [*c]const u8, endp: [*c][*c]u8) f64; pub extern fn SDL_strcmp(str1: [*c]const u8, str2: [*c]const u8) c_int; pub extern fn SDL_strncmp(str1: [*c]const u8, str2: [*c]const u8, maxlen: usize) c_int; pub extern fn SDL_strcasecmp(str1: [*c]const u8, str2: [*c]const u8) c_int; pub extern fn SDL_strncasecmp(str1: [*c]const u8, str2: [*c]const u8, len: usize) c_int; pub extern fn SDL_sscanf(text: [*c]const u8, fmt: [*c]const u8, ...) c_int; pub extern fn SDL_vsscanf(text: [*c]const u8, fmt: [*c]const u8, ap: [*c]struct___va_list_tag) c_int; pub extern fn SDL_snprintf(text: [*c]u8, maxlen: usize, fmt: [*c]const u8, ...) c_int; pub extern fn SDL_vsnprintf(text: [*c]u8, maxlen: usize, fmt: [*c]const u8, ap: [*c]struct___va_list_tag) c_int; pub extern fn SDL_acos(x: f64) f64; pub extern fn SDL_acosf(x: f32) f32; pub extern fn SDL_asin(x: f64) f64; pub extern fn SDL_asinf(x: f32) f32; pub extern fn SDL_atan(x: f64) f64; pub extern fn SDL_atanf(x: f32) f32; pub extern fn SDL_atan2(x: f64, y: f64) f64; pub extern fn SDL_atan2f(x: f32, y: f32) f32; pub extern fn SDL_ceil(x: f64) f64; pub extern fn SDL_ceilf(x: f32) f32; pub extern fn SDL_copysign(x: f64, y: f64) f64; pub extern fn SDL_copysignf(x: f32, y: f32) f32; pub extern fn SDL_cos(x: f64) f64; pub extern fn SDL_cosf(x: f32) f32; pub extern fn SDL_exp(x: f64) f64; pub extern fn SDL_expf(x: f32) f32; pub extern fn SDL_fabs(x: f64) f64; pub extern fn SDL_fabsf(x: f32) f32; pub extern fn SDL_floor(x: f64) f64; pub extern fn SDL_floorf(x: f32) f32; pub extern fn SDL_trunc(x: f64) f64; pub extern fn SDL_truncf(x: f32) f32; pub extern fn SDL_fmod(x: f64, y: f64) f64; pub extern fn SDL_fmodf(x: f32, y: f32) f32; pub extern fn SDL_log(x: f64) f64; pub extern fn SDL_logf(x: f32) f32; pub extern fn SDL_log10(x: f64) f64; pub extern fn SDL_log10f(x: f32) f32; pub extern fn SDL_pow(x: f64, y: f64) f64; pub extern fn SDL_powf(x: f32, y: f32) f32; pub extern fn SDL_round(x: f64) f64; pub extern fn SDL_roundf(x: f32) f32; pub extern fn SDL_lround(x: f64) c_long; pub extern fn SDL_lroundf(x: f32) c_long; pub extern fn SDL_scalbn(x: f64, n: c_int) f64; pub extern fn SDL_scalbnf(x: f32, n: c_int) f32; pub extern fn SDL_sin(x: f64) f64; pub extern fn SDL_sinf(x: f32) f32; pub extern fn SDL_sqrt(x: f64) f64; pub extern fn SDL_sqrtf(x: f32) f32; pub extern fn SDL_tan(x: f64) f64; pub extern fn SDL_tanf(x: f32) f32; pub const struct__SDL_iconv_t = opaque {}; pub const SDL_iconv_t = ?*struct__SDL_iconv_t; pub extern fn SDL_iconv_open(tocode: [*c]const u8, fromcode: [*c]const u8) SDL_iconv_t; pub extern fn SDL_iconv_close(cd: SDL_iconv_t) c_int; pub extern fn SDL_iconv(cd: SDL_iconv_t, inbuf: [*c][*c]const u8, inbytesleft: [*c]usize, outbuf: [*c][*c]u8, outbytesleft: [*c]usize) usize; pub extern fn SDL_iconv_string(tocode: [*c]const u8, fromcode: [*c]const u8, inbuf: [*c]const u8, inbytesleft: usize) [*c]u8; pub inline fn SDL_memcpy4(arg_dst: ?*anyopaque, arg_src: ?*const anyopaque, arg_dwords: usize) ?*anyopaque { var dst = arg_dst; var src = arg_src; var dwords = arg_dwords; return SDL_memcpy(dst, src, dwords *% @bitCast(c_ulong, @as(c_long, @as(c_int, 4)))); } pub const SDL_main_func = ?fn (c_int, [*c][*c]u8) callconv(.C) c_int; pub extern fn SDL_main(argc: c_int, argv: [*c][*c]u8) c_int; pub extern fn SDL_SetMainReady() void; pub const SDL_ASSERTION_RETRY = @enumToInt(enum_unnamed_16.SDL_ASSERTION_RETRY); pub const SDL_ASSERTION_BREAK = @enumToInt(enum_unnamed_16.SDL_ASSERTION_BREAK); pub const SDL_ASSERTION_ABORT = @enumToInt(enum_unnamed_16.SDL_ASSERTION_ABORT); pub const SDL_ASSERTION_IGNORE = @enumToInt(enum_unnamed_16.SDL_ASSERTION_IGNORE); pub const SDL_ASSERTION_ALWAYS_IGNORE = @enumToInt(enum_unnamed_16.SDL_ASSERTION_ALWAYS_IGNORE); const enum_unnamed_16 = enum(c_int) { SDL_ASSERTION_RETRY, SDL_ASSERTION_BREAK, SDL_ASSERTION_ABORT, SDL_ASSERTION_IGNORE, SDL_ASSERTION_ALWAYS_IGNORE, _, }; pub const SDL_AssertState = enum_unnamed_16; pub const struct_SDL_AssertData = extern struct { always_ignore: c_int, trigger_count: c_uint, condition: [*c]const u8, filename: [*c]const u8, linenum: c_int, function: [*c]const u8, next: [*c]const struct_SDL_AssertData, }; pub const SDL_AssertData = struct_SDL_AssertData; pub extern fn SDL_ReportAssertion([*c]SDL_AssertData, [*c]const u8, [*c]const u8, c_int) SDL_AssertState; pub const SDL_AssertionHandler = ?fn ([*c]const SDL_AssertData, ?*anyopaque) callconv(.C) SDL_AssertState; pub extern fn SDL_SetAssertionHandler(handler: SDL_AssertionHandler, userdata: ?*anyopaque) void; pub extern fn SDL_GetDefaultAssertionHandler() SDL_AssertionHandler; pub extern fn SDL_GetAssertionHandler(puserdata: [*c]?*anyopaque) SDL_AssertionHandler; pub extern fn SDL_GetAssertionReport() [*c]const SDL_AssertData; pub extern fn SDL_ResetAssertionReport() void; pub const SDL_SpinLock = c_int; pub extern fn SDL_AtomicTryLock(lock: [*c]SDL_SpinLock) SDL_bool; pub extern fn SDL_AtomicLock(lock: [*c]SDL_SpinLock) void; pub extern fn SDL_AtomicUnlock(lock: [*c]SDL_SpinLock) void; pub extern fn SDL_MemoryBarrierReleaseFunction() void; pub extern fn SDL_MemoryBarrierAcquireFunction() void; pub const SDL_atomic_t = extern struct { value: c_int, }; pub extern fn SDL_AtomicCAS(a: [*c]SDL_atomic_t, oldval: c_int, newval: c_int) SDL_bool; pub extern fn SDL_AtomicSet(a: [*c]SDL_atomic_t, v: c_int) c_int; pub extern fn SDL_AtomicGet(a: [*c]SDL_atomic_t) c_int; pub extern fn SDL_AtomicAdd(a: [*c]SDL_atomic_t, v: c_int) c_int; pub extern fn SDL_AtomicCASPtr(a: [*c]?*anyopaque, oldval: ?*anyopaque, newval: ?*anyopaque) SDL_bool; pub extern fn SDL_AtomicSetPtr(a: [*c]?*anyopaque, v: ?*anyopaque) ?*anyopaque; pub extern fn SDL_AtomicGetPtr(a: [*c]?*anyopaque) ?*anyopaque; pub extern fn SDL_SetError(fmt: [*c]const u8, ...) c_int; pub extern fn SDL_GetError() [*c]const u8; pub extern fn SDL_GetErrorMsg(errstr: [*c]u8, maxlen: c_int) [*c]u8; pub extern fn SDL_ClearError() void; pub const SDL_ENOMEM = @enumToInt(enum_unnamed_18.SDL_ENOMEM); pub const SDL_EFREAD = @enumToInt(enum_unnamed_18.SDL_EFREAD); pub const SDL_EFWRITE = @enumToInt(enum_unnamed_18.SDL_EFWRITE); pub const SDL_EFSEEK = @enumToInt(enum_unnamed_18.SDL_EFSEEK); pub const SDL_UNSUPPORTED = @enumToInt(enum_unnamed_18.SDL_UNSUPPORTED); pub const SDL_LASTERROR = @enumToInt(enum_unnamed_18.SDL_LASTERROR); const enum_unnamed_18 = enum(c_int) { SDL_ENOMEM, SDL_EFREAD, SDL_EFWRITE, SDL_EFSEEK, SDL_UNSUPPORTED, SDL_LASTERROR, _, }; pub const SDL_errorcode = enum_unnamed_18; pub extern fn SDL_Error(code: SDL_errorcode) c_int; pub inline fn SDL_SwapFloat(arg_x: f32) f32 { var x = arg_x; const union_unnamed_8 = extern union { f: f32, ui32: Uint32, }; _ = union_unnamed_8; var swapper: union_unnamed_8 = undefined; swapper.f = x; swapper.ui32 = __builtin_bswap32(swapper.ui32); return swapper.f; } pub const struct_SDL_mutex = opaque {}; pub const SDL_mutex = struct_SDL_mutex; pub extern fn SDL_CreateMutex() ?*SDL_mutex; pub extern fn SDL_LockMutex(mutex: ?*SDL_mutex) c_int; pub extern fn SDL_TryLockMutex(mutex: ?*SDL_mutex) c_int; pub extern fn SDL_UnlockMutex(mutex: ?*SDL_mutex) c_int; pub extern fn SDL_DestroyMutex(mutex: ?*SDL_mutex) void; pub const struct_SDL_semaphore = opaque {}; pub const SDL_sem = struct_SDL_semaphore; pub extern fn SDL_CreateSemaphore(initial_value: Uint32) ?*SDL_sem; pub extern fn SDL_DestroySemaphore(sem: ?*SDL_sem) void; pub extern fn SDL_SemWait(sem: ?*SDL_sem) c_int; pub extern fn SDL_SemTryWait(sem: ?*SDL_sem) c_int; pub extern fn SDL_SemWaitTimeout(sem: ?*SDL_sem, ms: Uint32) c_int; pub extern fn SDL_SemPost(sem: ?*SDL_sem) c_int; pub extern fn SDL_SemValue(sem: ?*SDL_sem) Uint32; pub const struct_SDL_cond = opaque {}; pub const SDL_cond = struct_SDL_cond; pub extern fn SDL_CreateCond() ?*SDL_cond; pub extern fn SDL_DestroyCond(cond: ?*SDL_cond) void; pub extern fn SDL_CondSignal(cond: ?*SDL_cond) c_int; pub extern fn SDL_CondBroadcast(cond: ?*SDL_cond) c_int; pub extern fn SDL_CondWait(cond: ?*SDL_cond, mutex: ?*SDL_mutex) c_int; pub extern fn SDL_CondWaitTimeout(cond: ?*SDL_cond, mutex: ?*SDL_mutex, ms: Uint32) c_int; pub const struct_SDL_Thread = opaque {}; pub const SDL_Thread = struct_SDL_Thread; pub const SDL_threadID = c_ulong; pub const SDL_TLSID = c_uint; pub const SDL_THREAD_PRIORITY_LOW = @enumToInt(enum_unnamed_19.SDL_THREAD_PRIORITY_LOW); pub const SDL_THREAD_PRIORITY_NORMAL = @enumToInt(enum_unnamed_19.SDL_THREAD_PRIORITY_NORMAL); pub const SDL_THREAD_PRIORITY_HIGH = @enumToInt(enum_unnamed_19.SDL_THREAD_PRIORITY_HIGH); pub const SDL_THREAD_PRIORITY_TIME_CRITICAL = @enumToInt(enum_unnamed_19.SDL_THREAD_PRIORITY_TIME_CRITICAL); const enum_unnamed_19 = enum(c_int) { SDL_THREAD_PRIORITY_LOW, SDL_THREAD_PRIORITY_NORMAL, SDL_THREAD_PRIORITY_HIGH, SDL_THREAD_PRIORITY_TIME_CRITICAL, _, }; pub const SDL_ThreadPriority = enum_unnamed_19; pub const SDL_ThreadFunction = ?fn (?*anyopaque) callconv(.C) c_int; pub extern fn SDL_CreateThread(@"fn": SDL_ThreadFunction, name: [*c]const u8, data: ?*anyopaque) ?*SDL_Thread; pub extern fn SDL_CreateThreadWithStackSize(@"fn": SDL_ThreadFunction, name: [*c]const u8, stacksize: usize, data: ?*anyopaque) ?*SDL_Thread; pub extern fn SDL_GetThreadName(thread: ?*SDL_Thread) [*c]const u8; pub extern fn SDL_ThreadID() SDL_threadID; pub extern fn SDL_GetThreadID(thread: ?*SDL_Thread) SDL_threadID; pub extern fn SDL_SetThreadPriority(priority: SDL_ThreadPriority) c_int; pub extern fn SDL_WaitThread(thread: ?*SDL_Thread, status: [*c]c_int) void; pub extern fn SDL_DetachThread(thread: ?*SDL_Thread) void; pub extern fn SDL_TLSCreate() SDL_TLSID; pub extern fn SDL_TLSGet(id: SDL_TLSID) ?*anyopaque; pub extern fn SDL_TLSSet(id: SDL_TLSID, value: ?*const anyopaque, destructor: ?fn (?*anyopaque) callconv(.C) void) c_int; pub extern fn SDL_TLSCleanup() void; const struct_unnamed_10 = extern struct { autoclose: SDL_bool, fp: [*c]FILE, }; const struct_unnamed_11 = extern struct { base: [*c]Uint8, here: [*c]Uint8, stop: [*c]Uint8, }; const struct_unnamed_12 = extern struct { data1: ?*anyopaque, data2: ?*anyopaque, }; const union_unnamed_9 = extern union { stdio: struct_unnamed_10, mem: struct_unnamed_11, unknown: struct_unnamed_12, }; pub const struct_SDL_RWops = extern struct { size: ?fn ([*c]struct_SDL_RWops) callconv(.C) Sint64, seek: ?fn ([*c]struct_SDL_RWops, Sint64, c_int) callconv(.C) Sint64, read: ?fn ([*c]struct_SDL_RWops, ?*anyopaque, usize, usize) callconv(.C) usize, write: ?fn ([*c]struct_SDL_RWops, ?*const anyopaque, usize, usize) callconv(.C) usize, close: ?fn ([*c]struct_SDL_RWops) callconv(.C) c_int, type: Uint32, hidden: union_unnamed_9, }; pub const SDL_RWops = struct_SDL_RWops; pub extern fn SDL_RWFromFile(file: [*c]const u8, mode: [*c]const u8) [*c]SDL_RWops; pub extern fn SDL_RWFromFP(fp: [*c]FILE, autoclose: SDL_bool) [*c]SDL_RWops; pub extern fn SDL_RWFromMem(mem: ?*anyopaque, size: c_int) [*c]SDL_RWops; pub extern fn SDL_RWFromConstMem(mem: ?*const anyopaque, size: c_int) [*c]SDL_RWops; pub extern fn SDL_AllocRW() [*c]SDL_RWops; pub extern fn SDL_FreeRW(area: [*c]SDL_RWops) void; pub extern fn SDL_RWsize(context: [*c]SDL_RWops) Sint64; pub extern fn SDL_RWseek(context: [*c]SDL_RWops, offset: Sint64, whence: c_int) Sint64; pub extern fn SDL_RWtell(context: [*c]SDL_RWops) Sint64; pub extern fn SDL_RWread(context: [*c]SDL_RWops, ptr: ?*anyopaque, size: usize, maxnum: usize) usize; pub extern fn SDL_RWwrite(context: [*c]SDL_RWops, ptr: ?*const anyopaque, size: usize, num: usize) usize; pub extern fn SDL_RWclose(context: [*c]SDL_RWops) c_int; pub extern fn SDL_LoadFile_RW(src: [*c]SDL_RWops, datasize: [*c]usize, freesrc: c_int) ?*anyopaque; pub extern fn SDL_LoadFile(file: [*c]const u8, datasize: [*c]usize) ?*anyopaque; pub extern fn SDL_ReadU8(src: [*c]SDL_RWops) Uint8; pub extern fn SDL_ReadLE16(src: [*c]SDL_RWops) Uint16; pub extern fn SDL_ReadBE16(src: [*c]SDL_RWops) Uint16; pub extern fn SDL_ReadLE32(src: [*c]SDL_RWops) Uint32; pub extern fn SDL_ReadBE32(src: [*c]SDL_RWops) Uint32; pub extern fn SDL_ReadLE64(src: [*c]SDL_RWops) Uint64; pub extern fn SDL_ReadBE64(src: [*c]SDL_RWops) Uint64; pub extern fn SDL_WriteU8(dst: [*c]SDL_RWops, value: Uint8) usize; pub extern fn SDL_WriteLE16(dst: [*c]SDL_RWops, value: Uint16) usize; pub extern fn SDL_WriteBE16(dst: [*c]SDL_RWops, value: Uint16) usize; pub extern fn SDL_WriteLE32(dst: [*c]SDL_RWops, value: Uint32) usize; pub extern fn SDL_WriteBE32(dst: [*c]SDL_RWops, value: Uint32) usize; pub extern fn SDL_WriteLE64(dst: [*c]SDL_RWops, value: Uint64) usize; pub extern fn SDL_WriteBE64(dst: [*c]SDL_RWops, value: Uint64) usize; pub const SDL_AudioFormat = Uint16; pub const SDL_AudioCallback = ?fn (?*anyopaque, [*c]Uint8, c_int) callconv(.C) void; pub const struct_SDL_AudioSpec = extern struct { freq: c_int, format: SDL_AudioFormat, channels: Uint8, silence: Uint8, samples: Uint16, padding: Uint16, size: Uint32, callback: SDL_AudioCallback, userdata: ?*anyopaque, }; pub const SDL_AudioSpec = struct_SDL_AudioSpec; pub const SDL_AudioFilter = ?fn ([*c]struct_SDL_AudioCVT, SDL_AudioFormat) callconv(.C) void; pub const struct_SDL_AudioCVT = extern struct { needed: c_int, src_format: SDL_AudioFormat, dst_format: SDL_AudioFormat, rate_incr: f64, buf: [*c]Uint8, len: c_int, len_cvt: c_int, len_mult: c_int, len_ratio: f64, filters: [10]SDL_AudioFilter, filter_index: c_int, }; pub const SDL_AudioCVT = struct_SDL_AudioCVT; pub extern fn SDL_GetNumAudioDrivers() c_int; pub extern fn SDL_GetAudioDriver(index: c_int) [*c]const u8; pub extern fn SDL_AudioInit(driver_name: [*c]const u8) c_int; pub extern fn SDL_AudioQuit() void; pub extern fn SDL_GetCurrentAudioDriver() [*c]const u8; pub extern fn SDL_OpenAudio(desired: [*c]SDL_AudioSpec, obtained: [*c]SDL_AudioSpec) c_int; pub const SDL_AudioDeviceID = Uint32; pub extern fn SDL_GetNumAudioDevices(iscapture: c_int) c_int; pub extern fn SDL_GetAudioDeviceName(index: c_int, iscapture: c_int) [*c]const u8; pub extern fn SDL_GetAudioDeviceSpec(index: c_int, iscapture: c_int, spec: [*c]SDL_AudioSpec) c_int; pub extern fn SDL_OpenAudioDevice(device: [*c]const u8, iscapture: c_int, desired: [*c]const SDL_AudioSpec, obtained: [*c]SDL_AudioSpec, allowed_changes: c_int) SDL_AudioDeviceID; pub const SDL_AUDIO_STOPPED = @enumToInt(enum_unnamed_24.SDL_AUDIO_STOPPED); pub const SDL_AUDIO_PLAYING = @enumToInt(enum_unnamed_24.SDL_AUDIO_PLAYING); pub const SDL_AUDIO_PAUSED = @enumToInt(enum_unnamed_24.SDL_AUDIO_PAUSED); const enum_unnamed_24 = enum(c_int) { SDL_AUDIO_STOPPED = 0, SDL_AUDIO_PLAYING = 1, SDL_AUDIO_PAUSED = 2, _, }; pub const SDL_AudioStatus = enum_unnamed_24; pub extern fn SDL_GetAudioStatus() SDL_AudioStatus; pub extern fn SDL_GetAudioDeviceStatus(dev: SDL_AudioDeviceID) SDL_AudioStatus; pub extern fn SDL_PauseAudio(pause_on: c_int) void; pub extern fn SDL_PauseAudioDevice(dev: SDL_AudioDeviceID, pause_on: c_int) void; pub extern fn SDL_LoadWAV_RW(src: [*c]SDL_RWops, freesrc: c_int, spec: [*c]SDL_AudioSpec, audio_buf: [*c][*c]Uint8, audio_len: [*c]Uint32) [*c]SDL_AudioSpec; pub extern fn SDL_FreeWAV(audio_buf: [*c]Uint8) void; pub extern fn SDL_BuildAudioCVT(cvt: [*c]SDL_AudioCVT, src_format: SDL_AudioFormat, src_channels: Uint8, src_rate: c_int, dst_format: SDL_AudioFormat, dst_channels: Uint8, dst_rate: c_int) c_int; pub extern fn SDL_ConvertAudio(cvt: [*c]SDL_AudioCVT) c_int; pub const struct__SDL_AudioStream = opaque {}; pub const SDL_AudioStream = struct__SDL_AudioStream; pub extern fn SDL_NewAudioStream(src_format: SDL_AudioFormat, src_channels: Uint8, src_rate: c_int, dst_format: SDL_AudioFormat, dst_channels: Uint8, dst_rate: c_int) ?*SDL_AudioStream; pub extern fn SDL_AudioStreamPut(stream: ?*SDL_AudioStream, buf: ?*const anyopaque, len: c_int) c_int; pub extern fn SDL_AudioStreamGet(stream: ?*SDL_AudioStream, buf: ?*anyopaque, len: c_int) c_int; pub extern fn SDL_AudioStreamAvailable(stream: ?*SDL_AudioStream) c_int; pub extern fn SDL_AudioStreamFlush(stream: ?*SDL_AudioStream) c_int; pub extern fn SDL_AudioStreamClear(stream: ?*SDL_AudioStream) void; pub extern fn SDL_FreeAudioStream(stream: ?*SDL_AudioStream) void; pub extern fn SDL_MixAudio(dst: [*c]Uint8, src: [*c]const Uint8, len: Uint32, volume: c_int) void; pub extern fn SDL_MixAudioFormat(dst: [*c]Uint8, src: [*c]const Uint8, format: SDL_AudioFormat, len: Uint32, volume: c_int) void; pub extern fn SDL_QueueAudio(dev: SDL_AudioDeviceID, data: ?*const anyopaque, len: Uint32) c_int; pub extern fn SDL_DequeueAudio(dev: SDL_AudioDeviceID, data: ?*anyopaque, len: Uint32) Uint32; pub extern fn SDL_GetQueuedAudioSize(dev: SDL_AudioDeviceID) Uint32; pub extern fn SDL_ClearQueuedAudio(dev: SDL_AudioDeviceID) void; pub extern fn SDL_LockAudio() void; pub extern fn SDL_LockAudioDevice(dev: SDL_AudioDeviceID) void; pub extern fn SDL_UnlockAudio() void; pub extern fn SDL_UnlockAudioDevice(dev: SDL_AudioDeviceID) void; pub extern fn SDL_CloseAudio() void; pub extern fn SDL_CloseAudioDevice(dev: SDL_AudioDeviceID) void; pub extern fn SDL_SetClipboardText(text: [*c]const u8) c_int; pub extern fn SDL_GetClipboardText() [*c]u8; pub extern fn SDL_HasClipboardText() SDL_bool; pub extern fn SDL_GetCPUCount() c_int; pub extern fn SDL_GetCPUCacheLineSize() c_int; pub extern fn SDL_HasRDTSC() SDL_bool; pub extern fn SDL_HasAltiVec() SDL_bool; pub extern fn SDL_HasMMX() SDL_bool; pub extern fn SDL_Has3DNow() SDL_bool; pub extern fn SDL_HasSSE() SDL_bool; pub extern fn SDL_HasSSE2() SDL_bool; pub extern fn SDL_HasSSE3() SDL_bool; pub extern fn SDL_HasSSE41() SDL_bool; pub extern fn SDL_HasSSE42() SDL_bool; pub extern fn SDL_HasAVX() SDL_bool; pub extern fn SDL_HasAVX2() SDL_bool; pub extern fn SDL_HasAVX512F() SDL_bool; pub extern fn SDL_HasARMSIMD() SDL_bool; pub extern fn SDL_HasNEON() SDL_bool; pub extern fn SDL_GetSystemRAM() c_int; pub extern fn SDL_SIMDGetAlignment() usize; pub extern fn SDL_SIMDAlloc(len: usize) ?*anyopaque; pub extern fn SDL_SIMDRealloc(mem: ?*anyopaque, len: usize) ?*anyopaque; pub extern fn SDL_SIMDFree(ptr: ?*anyopaque) void; pub const SDL_PIXELTYPE_UNKNOWN = @enumToInt(enum_unnamed_29.SDL_PIXELTYPE_UNKNOWN); pub const SDL_PIXELTYPE_INDEX1 = @enumToInt(enum_unnamed_29.SDL_PIXELTYPE_INDEX1); pub const SDL_PIXELTYPE_INDEX4 = @enumToInt(enum_unnamed_29.SDL_PIXELTYPE_INDEX4); pub const SDL_PIXELTYPE_INDEX8 = @enumToInt(enum_unnamed_29.SDL_PIXELTYPE_INDEX8); pub const SDL_PIXELTYPE_PACKED8 = @enumToInt(enum_unnamed_29.SDL_PIXELTYPE_PACKED8); pub const SDL_PIXELTYPE_PACKED16 = @enumToInt(enum_unnamed_29.SDL_PIXELTYPE_PACKED16); pub const SDL_PIXELTYPE_PACKED32 = @enumToInt(enum_unnamed_29.SDL_PIXELTYPE_PACKED32); pub const SDL_PIXELTYPE_ARRAYU8 = @enumToInt(enum_unnamed_29.SDL_PIXELTYPE_ARRAYU8); pub const SDL_PIXELTYPE_ARRAYU16 = @enumToInt(enum_unnamed_29.SDL_PIXELTYPE_ARRAYU16); pub const SDL_PIXELTYPE_ARRAYU32 = @enumToInt(enum_unnamed_29.SDL_PIXELTYPE_ARRAYU32); pub const SDL_PIXELTYPE_ARRAYF16 = @enumToInt(enum_unnamed_29.SDL_PIXELTYPE_ARRAYF16); pub const SDL_PIXELTYPE_ARRAYF32 = @enumToInt(enum_unnamed_29.SDL_PIXELTYPE_ARRAYF32); const enum_unnamed_29 = enum(c_int) { SDL_PIXELTYPE_UNKNOWN, SDL_PIXELTYPE_INDEX1, SDL_PIXELTYPE_INDEX4, SDL_PIXELTYPE_INDEX8, SDL_PIXELTYPE_PACKED8, SDL_PIXELTYPE_PACKED16, SDL_PIXELTYPE_PACKED32, SDL_PIXELTYPE_ARRAYU8, SDL_PIXELTYPE_ARRAYU16, SDL_PIXELTYPE_ARRAYU32, SDL_PIXELTYPE_ARRAYF16, SDL_PIXELTYPE_ARRAYF32, _, }; pub const SDL_PixelType = enum_unnamed_29; pub const SDL_BITMAPORDER_NONE = @enumToInt(enum_unnamed_30.SDL_BITMAPORDER_NONE); pub const SDL_BITMAPORDER_4321 = @enumToInt(enum_unnamed_30.SDL_BITMAPORDER_4321); pub const SDL_BITMAPORDER_1234 = @enumToInt(enum_unnamed_30.SDL_BITMAPORDER_1234); const enum_unnamed_30 = enum(c_int) { SDL_BITMAPORDER_NONE, SDL_BITMAPORDER_4321, SDL_BITMAPORDER_1234, _, }; pub const SDL_BitmapOrder = enum_unnamed_30; pub const SDL_PACKEDORDER_NONE = @enumToInt(enum_unnamed_31.SDL_PACKEDORDER_NONE); pub const SDL_PACKEDORDER_XRGB = @enumToInt(enum_unnamed_31.SDL_PACKEDORDER_XRGB); pub const SDL_PACKEDORDER_RGBX = @enumToInt(enum_unnamed_31.SDL_PACKEDORDER_RGBX); pub const SDL_PACKEDORDER_ARGB = @enumToInt(enum_unnamed_31.SDL_PACKEDORDER_ARGB); pub const SDL_PACKEDORDER_RGBA = @enumToInt(enum_unnamed_31.SDL_PACKEDORDER_RGBA); pub const SDL_PACKEDORDER_XBGR = @enumToInt(enum_unnamed_31.SDL_PACKEDORDER_XBGR); pub const SDL_PACKEDORDER_BGRX = @enumToInt(enum_unnamed_31.SDL_PACKEDORDER_BGRX); pub const SDL_PACKEDORDER_ABGR = @enumToInt(enum_unnamed_31.SDL_PACKEDORDER_ABGR); pub const SDL_PACKEDORDER_BGRA = @enumToInt(enum_unnamed_31.SDL_PACKEDORDER_BGRA); const enum_unnamed_31 = enum(c_int) { SDL_PACKEDORDER_NONE, SDL_PACKEDORDER_XRGB, SDL_PACKEDORDER_RGBX, SDL_PACKEDORDER_ARGB, SDL_PACKEDORDER_RGBA, SDL_PACKEDORDER_XBGR, SDL_PACKEDORDER_BGRX, SDL_PACKEDORDER_ABGR, SDL_PACKEDORDER_BGRA, _, }; pub const SDL_PackedOrder = enum_unnamed_31; pub const SDL_ARRAYORDER_NONE = @enumToInt(enum_unnamed_32.SDL_ARRAYORDER_NONE); pub const SDL_ARRAYORDER_RGB = @enumToInt(enum_unnamed_32.SDL_ARRAYORDER_RGB); pub const SDL_ARRAYORDER_RGBA = @enumToInt(enum_unnamed_32.SDL_ARRAYORDER_RGBA); pub const SDL_ARRAYORDER_ARGB = @enumToInt(enum_unnamed_32.SDL_ARRAYORDER_ARGB); pub const SDL_ARRAYORDER_BGR = @enumToInt(enum_unnamed_32.SDL_ARRAYORDER_BGR); pub const SDL_ARRAYORDER_BGRA = @enumToInt(enum_unnamed_32.SDL_ARRAYORDER_BGRA); pub const SDL_ARRAYORDER_ABGR = @enumToInt(enum_unnamed_32.SDL_ARRAYORDER_ABGR); const enum_unnamed_32 = enum(c_int) { SDL_ARRAYORDER_NONE, SDL_ARRAYORDER_RGB, SDL_ARRAYORDER_RGBA, SDL_ARRAYORDER_ARGB, SDL_ARRAYORDER_BGR, SDL_ARRAYORDER_BGRA, SDL_ARRAYORDER_ABGR, _, }; pub const SDL_ArrayOrder = enum_unnamed_32; pub const SDL_PACKEDLAYOUT_NONE = @enumToInt(enum_unnamed_33.SDL_PACKEDLAYOUT_NONE); pub const SDL_PACKEDLAYOUT_332 = @enumToInt(enum_unnamed_33.SDL_PACKEDLAYOUT_332); pub const SDL_PACKEDLAYOUT_4444 = @enumToInt(enum_unnamed_33.SDL_PACKEDLAYOUT_4444); pub const SDL_PACKEDLAYOUT_1555 = @enumToInt(enum_unnamed_33.SDL_PACKEDLAYOUT_1555); pub const SDL_PACKEDLAYOUT_5551 = @enumToInt(enum_unnamed_33.SDL_PACKEDLAYOUT_5551); pub const SDL_PACKEDLAYOUT_565 = @enumToInt(enum_unnamed_33.SDL_PACKEDLAYOUT_565); pub const SDL_PACKEDLAYOUT_8888 = @enumToInt(enum_unnamed_33.SDL_PACKEDLAYOUT_8888); pub const SDL_PACKEDLAYOUT_2101010 = @enumToInt(enum_unnamed_33.SDL_PACKEDLAYOUT_2101010); pub const SDL_PACKEDLAYOUT_1010102 = @enumToInt(enum_unnamed_33.SDL_PACKEDLAYOUT_1010102); const enum_unnamed_33 = enum(c_int) { SDL_PACKEDLAYOUT_NONE, SDL_PACKEDLAYOUT_332, SDL_PACKEDLAYOUT_4444, SDL_PACKEDLAYOUT_1555, SDL_PACKEDLAYOUT_5551, SDL_PACKEDLAYOUT_565, SDL_PACKEDLAYOUT_8888, SDL_PACKEDLAYOUT_2101010, SDL_PACKEDLAYOUT_1010102, _, }; pub const SDL_PackedLayout = enum_unnamed_33; pub const SDL_PIXELFORMAT_UNKNOWN = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_UNKNOWN); pub const SDL_PIXELFORMAT_INDEX1LSB = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_INDEX1LSB); pub const SDL_PIXELFORMAT_INDEX1MSB = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_INDEX1MSB); pub const SDL_PIXELFORMAT_INDEX4LSB = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_INDEX4LSB); pub const SDL_PIXELFORMAT_INDEX4MSB = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_INDEX4MSB); pub const SDL_PIXELFORMAT_INDEX8 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_INDEX8); pub const SDL_PIXELFORMAT_RGB332 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_RGB332); pub const SDL_PIXELFORMAT_XRGB4444 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_XRGB4444); pub const SDL_PIXELFORMAT_RGB444 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_RGB444); pub const SDL_PIXELFORMAT_XBGR4444 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_XBGR4444); pub const SDL_PIXELFORMAT_BGR444 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_BGR444); pub const SDL_PIXELFORMAT_XRGB1555 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_XRGB1555); pub const SDL_PIXELFORMAT_RGB555 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_RGB555); pub const SDL_PIXELFORMAT_XBGR1555 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_XBGR1555); pub const SDL_PIXELFORMAT_BGR555 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_BGR555); pub const SDL_PIXELFORMAT_ARGB4444 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_ARGB4444); pub const SDL_PIXELFORMAT_RGBA4444 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_RGBA4444); pub const SDL_PIXELFORMAT_ABGR4444 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_ABGR4444); pub const SDL_PIXELFORMAT_BGRA4444 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_BGRA4444); pub const SDL_PIXELFORMAT_ARGB1555 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_ARGB1555); pub const SDL_PIXELFORMAT_RGBA5551 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_RGBA5551); pub const SDL_PIXELFORMAT_ABGR1555 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_ABGR1555); pub const SDL_PIXELFORMAT_BGRA5551 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_BGRA5551); pub const SDL_PIXELFORMAT_RGB565 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_RGB565); pub const SDL_PIXELFORMAT_BGR565 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_BGR565); pub const SDL_PIXELFORMAT_RGB24 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_RGB24); pub const SDL_PIXELFORMAT_BGR24 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_BGR24); pub const SDL_PIXELFORMAT_XRGB8888 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_XRGB8888); pub const SDL_PIXELFORMAT_RGB888 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_RGB888); pub const SDL_PIXELFORMAT_RGBX8888 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_RGBX8888); pub const SDL_PIXELFORMAT_XBGR8888 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_XBGR8888); pub const SDL_PIXELFORMAT_BGR888 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_BGR888); pub const SDL_PIXELFORMAT_BGRX8888 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_BGRX8888); pub const SDL_PIXELFORMAT_ARGB8888 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_ARGB8888); pub const SDL_PIXELFORMAT_RGBA8888 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_RGBA8888); pub const SDL_PIXELFORMAT_ABGR8888 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_ABGR8888); pub const SDL_PIXELFORMAT_BGRA8888 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_BGRA8888); pub const SDL_PIXELFORMAT_ARGB2101010 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_ARGB2101010); pub const SDL_PIXELFORMAT_RGBA32 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_RGBA32); pub const SDL_PIXELFORMAT_ARGB32 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_ARGB32); pub const SDL_PIXELFORMAT_BGRA32 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_BGRA32); pub const SDL_PIXELFORMAT_ABGR32 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_ABGR32); pub const SDL_PIXELFORMAT_YV12 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_YV12); pub const SDL_PIXELFORMAT_IYUV = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_IYUV); pub const SDL_PIXELFORMAT_YUY2 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_YUY2); pub const SDL_PIXELFORMAT_UYVY = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_UYVY); pub const SDL_PIXELFORMAT_YVYU = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_YVYU); pub const SDL_PIXELFORMAT_NV12 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_NV12); pub const SDL_PIXELFORMAT_NV21 = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_NV21); pub const SDL_PIXELFORMAT_EXTERNAL_OES = @enumToInt(enum_unnamed_34.SDL_PIXELFORMAT_EXTERNAL_OES); const enum_unnamed_34 = enum(c_int) { SDL_PIXELFORMAT_UNKNOWN = 0, SDL_PIXELFORMAT_INDEX1LSB = 286261504, SDL_PIXELFORMAT_INDEX1MSB = 287310080, SDL_PIXELFORMAT_INDEX4LSB = 303039488, SDL_PIXELFORMAT_INDEX4MSB = 304088064, SDL_PIXELFORMAT_INDEX8 = 318769153, SDL_PIXELFORMAT_RGB332 = 336660481, SDL_PIXELFORMAT_XRGB4444 = 353504258, SDL_PIXELFORMAT_RGB444 = 353504258, SDL_PIXELFORMAT_XBGR4444 = 357698562, SDL_PIXELFORMAT_BGR444 = 357698562, SDL_PIXELFORMAT_XRGB1555 = 353570562, SDL_PIXELFORMAT_RGB555 = 353570562, SDL_PIXELFORMAT_XBGR1555 = 357764866, SDL_PIXELFORMAT_BGR555 = 357764866, SDL_PIXELFORMAT_ARGB4444 = 355602434, SDL_PIXELFORMAT_RGBA4444 = 356651010, SDL_PIXELFORMAT_ABGR4444 = 359796738, SDL_PIXELFORMAT_BGRA4444 = 360845314, SDL_PIXELFORMAT_ARGB1555 = 355667970, SDL_PIXELFORMAT_RGBA5551 = 356782082, SDL_PIXELFORMAT_ABGR1555 = 359862274, SDL_PIXELFORMAT_BGRA5551 = 360976386, SDL_PIXELFORMAT_RGB565 = 353701890, SDL_PIXELFORMAT_BGR565 = 357896194, SDL_PIXELFORMAT_RGB24 = 386930691, SDL_PIXELFORMAT_BGR24 = 390076419, SDL_PIXELFORMAT_XRGB8888 = 370546692, SDL_PIXELFORMAT_RGB888 = 370546692, SDL_PIXELFORMAT_RGBX8888 = 371595268, SDL_PIXELFORMAT_XBGR8888 = 374740996, SDL_PIXELFORMAT_BGR888 = 374740996, SDL_PIXELFORMAT_BGRX8888 = 375789572, SDL_PIXELFORMAT_ARGB8888 = 372645892, SDL_PIXELFORMAT_RGBA8888 = 373694468, SDL_PIXELFORMAT_ABGR8888 = 376840196, SDL_PIXELFORMAT_BGRA8888 = 377888772, SDL_PIXELFORMAT_ARGB2101010 = 372711428, SDL_PIXELFORMAT_RGBA32 = 376840196, SDL_PIXELFORMAT_ARGB32 = 377888772, SDL_PIXELFORMAT_BGRA32 = 372645892, SDL_PIXELFORMAT_ABGR32 = 373694468, SDL_PIXELFORMAT_YV12 = 842094169, SDL_PIXELFORMAT_IYUV = 1448433993, SDL_PIXELFORMAT_YUY2 = 844715353, SDL_PIXELFORMAT_UYVY = 1498831189, SDL_PIXELFORMAT_YVYU = 1431918169, SDL_PIXELFORMAT_NV12 = 842094158, SDL_PIXELFORMAT_NV21 = 825382478, SDL_PIXELFORMAT_EXTERNAL_OES = 542328143, _, }; pub const SDL_PixelFormatEnum = enum_unnamed_34; pub const struct_SDL_Color = extern struct { r: Uint8, g: Uint8, b: Uint8, a: Uint8, }; pub const SDL_Color = struct_SDL_Color; pub const struct_SDL_Palette = extern struct { ncolors: c_int, colors: [*c]SDL_Color, version: Uint32, refcount: c_int, }; pub const SDL_Palette = struct_SDL_Palette; pub const struct_SDL_PixelFormat = extern struct { format: Uint32, palette: [*c]SDL_Palette, BitsPerPixel: Uint8, BytesPerPixel: Uint8, padding: [2]Uint8, Rmask: Uint32, Gmask: Uint32, Bmask: Uint32, Amask: Uint32, Rloss: Uint8, Gloss: Uint8, Bloss: Uint8, Aloss: Uint8, Rshift: Uint8, Gshift: Uint8, Bshift: Uint8, Ashift: Uint8, refcount: c_int, next: [*c]struct_SDL_PixelFormat, }; pub const SDL_PixelFormat = struct_SDL_PixelFormat; pub extern fn SDL_GetPixelFormatName(format: Uint32) [*c]const u8; pub extern fn SDL_PixelFormatEnumToMasks(format: Uint32, bpp: [*c]c_int, Rmask: [*c]Uint32, Gmask: [*c]Uint32, Bmask: [*c]Uint32, Amask: [*c]Uint32) SDL_bool; pub extern fn SDL_MasksToPixelFormatEnum(bpp: c_int, Rmask: Uint32, Gmask: Uint32, Bmask: Uint32, Amask: Uint32) Uint32; pub extern fn SDL_AllocFormat(pixel_format: Uint32) [*c]SDL_PixelFormat; pub extern fn SDL_FreeFormat(format: [*c]SDL_PixelFormat) void; pub extern fn SDL_AllocPalette(ncolors: c_int) [*c]SDL_Palette; pub extern fn SDL_SetPixelFormatPalette(format: [*c]SDL_PixelFormat, palette: [*c]SDL_Palette) c_int; pub extern fn SDL_SetPaletteColors(palette: [*c]SDL_Palette, colors: [*c]const SDL_Color, firstcolor: c_int, ncolors: c_int) c_int; pub extern fn SDL_FreePalette(palette: [*c]SDL_Palette) void; pub extern fn SDL_MapRGB(format: [*c]const SDL_PixelFormat, r: Uint8, g: Uint8, b: Uint8) Uint32; pub extern fn SDL_MapRGBA(format: [*c]const SDL_PixelFormat, r: Uint8, g: Uint8, b: Uint8, a: Uint8) Uint32; pub extern fn SDL_GetRGB(pixel: Uint32, format: [*c]const SDL_PixelFormat, r: [*c]Uint8, g: [*c]Uint8, b: [*c]Uint8) void; pub extern fn SDL_GetRGBA(pixel: Uint32, format: [*c]const SDL_PixelFormat, r: [*c]Uint8, g: [*c]Uint8, b: [*c]Uint8, a: [*c]Uint8) void; pub extern fn SDL_CalculateGammaRamp(gamma: f32, ramp: [*c]Uint16) void; pub const struct_SDL_Point = extern struct { x: c_int, y: c_int, }; pub const SDL_Point = struct_SDL_Point; pub const struct_SDL_FPoint = extern struct { x: f32, y: f32, }; pub const SDL_FPoint = struct_SDL_FPoint; pub const struct_SDL_Rect = extern struct { x: c_int, y: c_int, w: c_int, h: c_int, }; pub const SDL_Rect = struct_SDL_Rect; pub const struct_SDL_FRect = extern struct { x: f32, y: f32, w: f32, h: f32, }; pub const SDL_FRect = struct_SDL_FRect; pub inline fn SDL_PointInRect(arg_p: [*c]const SDL_Point, arg_r: [*c]const SDL_Rect) SDL_bool { var p = arg_p; var r = arg_r; return @bitCast(c_uint, if ((((p.*.x >= r.*.x) and (p.*.x < (r.*.x + r.*.w))) and (p.*.y >= r.*.y)) and (p.*.y < (r.*.y + r.*.h))) SDL_TRUE else SDL_FALSE); } pub inline fn SDL_RectEmpty(arg_r: [*c]const SDL_Rect) SDL_bool { var r = arg_r; return @bitCast(c_uint, if ((!(r != null) or (r.*.w <= @as(c_int, 0))) or (r.*.h <= @as(c_int, 0))) SDL_TRUE else SDL_FALSE); } pub inline fn SDL_RectEquals(arg_a: [*c]const SDL_Rect, arg_b: [*c]const SDL_Rect) SDL_bool { var a = arg_a; var b = arg_b; return @bitCast(c_uint, if ((((((a != null) and (b != null)) and (a.*.x == b.*.x)) and (a.*.y == b.*.y)) and (a.*.w == b.*.w)) and (a.*.h == b.*.h)) SDL_TRUE else SDL_FALSE); } pub extern fn SDL_HasIntersection(A: [*c]const SDL_Rect, B: [*c]const SDL_Rect) SDL_bool; pub extern fn SDL_IntersectRect(A: [*c]const SDL_Rect, B: [*c]const SDL_Rect, result: [*c]SDL_Rect) SDL_bool; pub extern fn SDL_UnionRect(A: [*c]const SDL_Rect, B: [*c]const SDL_Rect, result: [*c]SDL_Rect) void; pub extern fn SDL_EnclosePoints(points: [*c]const SDL_Point, count: c_int, clip: [*c]const SDL_Rect, result: [*c]SDL_Rect) SDL_bool; pub extern fn SDL_IntersectRectAndLine(rect: [*c]const SDL_Rect, X1: [*c]c_int, Y1: [*c]c_int, X2: [*c]c_int, Y2: [*c]c_int) SDL_bool; pub const SDL_BLENDMODE_NONE = @enumToInt(enum_unnamed_35.SDL_BLENDMODE_NONE); pub const SDL_BLENDMODE_BLEND = @enumToInt(enum_unnamed_35.SDL_BLENDMODE_BLEND); pub const SDL_BLENDMODE_ADD = @enumToInt(enum_unnamed_35.SDL_BLENDMODE_ADD); pub const SDL_BLENDMODE_MOD = @enumToInt(enum_unnamed_35.SDL_BLENDMODE_MOD); pub const SDL_BLENDMODE_MUL = @enumToInt(enum_unnamed_35.SDL_BLENDMODE_MUL); pub const SDL_BLENDMODE_INVALID = @enumToInt(enum_unnamed_35.SDL_BLENDMODE_INVALID); const enum_unnamed_35 = enum(c_int) { SDL_BLENDMODE_NONE = 0, SDL_BLENDMODE_BLEND = 1, SDL_BLENDMODE_ADD = 2, SDL_BLENDMODE_MOD = 4, SDL_BLENDMODE_MUL = 8, SDL_BLENDMODE_INVALID = 2147483647, _, }; pub const SDL_BlendMode = enum_unnamed_35; pub const SDL_BLENDOPERATION_ADD = @enumToInt(enum_unnamed_36.SDL_BLENDOPERATION_ADD); pub const SDL_BLENDOPERATION_SUBTRACT = @enumToInt(enum_unnamed_36.SDL_BLENDOPERATION_SUBTRACT); pub const SDL_BLENDOPERATION_REV_SUBTRACT = @enumToInt(enum_unnamed_36.SDL_BLENDOPERATION_REV_SUBTRACT); pub const SDL_BLENDOPERATION_MINIMUM = @enumToInt(enum_unnamed_36.SDL_BLENDOPERATION_MINIMUM); pub const SDL_BLENDOPERATION_MAXIMUM = @enumToInt(enum_unnamed_36.SDL_BLENDOPERATION_MAXIMUM); const enum_unnamed_36 = enum(c_int) { SDL_BLENDOPERATION_ADD = 1, SDL_BLENDOPERATION_SUBTRACT = 2, SDL_BLENDOPERATION_REV_SUBTRACT = 3, SDL_BLENDOPERATION_MINIMUM = 4, SDL_BLENDOPERATION_MAXIMUM = 5, _, }; pub const SDL_BlendOperation = enum_unnamed_36; pub const SDL_BLENDFACTOR_ZERO = @enumToInt(enum_unnamed_37.SDL_BLENDFACTOR_ZERO); pub const SDL_BLENDFACTOR_ONE = @enumToInt(enum_unnamed_37.SDL_BLENDFACTOR_ONE); pub const SDL_BLENDFACTOR_SRC_COLOR = @enumToInt(enum_unnamed_37.SDL_BLENDFACTOR_SRC_COLOR); pub const SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR = @enumToInt(enum_unnamed_37.SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR); pub const SDL_BLENDFACTOR_SRC_ALPHA = @enumToInt(enum_unnamed_37.SDL_BLENDFACTOR_SRC_ALPHA); pub const SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA = @enumToInt(enum_unnamed_37.SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA); pub const SDL_BLENDFACTOR_DST_COLOR = @enumToInt(enum_unnamed_37.SDL_BLENDFACTOR_DST_COLOR); pub const SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR = @enumToInt(enum_unnamed_37.SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR); pub const SDL_BLENDFACTOR_DST_ALPHA = @enumToInt(enum_unnamed_37.SDL_BLENDFACTOR_DST_ALPHA); pub const SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA = @enumToInt(enum_unnamed_37.SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA); const enum_unnamed_37 = enum(c_int) { SDL_BLENDFACTOR_ZERO = 1, SDL_BLENDFACTOR_ONE = 2, SDL_BLENDFACTOR_SRC_COLOR = 3, SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR = 4, SDL_BLENDFACTOR_SRC_ALPHA = 5, SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA = 6, SDL_BLENDFACTOR_DST_COLOR = 7, SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR = 8, SDL_BLENDFACTOR_DST_ALPHA = 9, SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA = 10, _, }; pub const SDL_BlendFactor = enum_unnamed_37; pub extern fn SDL_ComposeCustomBlendMode(srcColorFactor: SDL_BlendFactor, dstColorFactor: SDL_BlendFactor, colorOperation: SDL_BlendOperation, srcAlphaFactor: SDL_BlendFactor, dstAlphaFactor: SDL_BlendFactor, alphaOperation: SDL_BlendOperation) SDL_BlendMode; pub const struct_SDL_BlitMap = opaque {}; pub const struct_SDL_Surface = extern struct { flags: Uint32, format: [*c]SDL_PixelFormat, w: c_int, h: c_int, pitch: c_int, pixels: ?*anyopaque, userdata: ?*anyopaque, locked: c_int, list_blitmap: ?*anyopaque, clip_rect: SDL_Rect, map: ?*struct_SDL_BlitMap, refcount: c_int, }; pub const SDL_Surface = struct_SDL_Surface; pub const SDL_blit = ?fn ([*c]struct_SDL_Surface, [*c]SDL_Rect, [*c]struct_SDL_Surface, [*c]SDL_Rect) callconv(.C) c_int; pub const SDL_YUV_CONVERSION_JPEG = @enumToInt(enum_unnamed_38.SDL_YUV_CONVERSION_JPEG); pub const SDL_YUV_CONVERSION_BT601 = @enumToInt(enum_unnamed_38.SDL_YUV_CONVERSION_BT601); pub const SDL_YUV_CONVERSION_BT709 = @enumToInt(enum_unnamed_38.SDL_YUV_CONVERSION_BT709); pub const SDL_YUV_CONVERSION_AUTOMATIC = @enumToInt(enum_unnamed_38.SDL_YUV_CONVERSION_AUTOMATIC); const enum_unnamed_38 = enum(c_int) { SDL_YUV_CONVERSION_JPEG, SDL_YUV_CONVERSION_BT601, SDL_YUV_CONVERSION_BT709, SDL_YUV_CONVERSION_AUTOMATIC, _, }; pub const SDL_YUV_CONVERSION_MODE = enum_unnamed_38; pub extern fn SDL_CreateRGBSurface(flags: Uint32, width: c_int, height: c_int, depth: c_int, Rmask: Uint32, Gmask: Uint32, Bmask: Uint32, Amask: Uint32) [*c]SDL_Surface; pub extern fn SDL_CreateRGBSurfaceWithFormat(flags: Uint32, width: c_int, height: c_int, depth: c_int, format: Uint32) [*c]SDL_Surface; pub extern fn SDL_CreateRGBSurfaceFrom(pixels: ?*anyopaque, width: c_int, height: c_int, depth: c_int, pitch: c_int, Rmask: Uint32, Gmask: Uint32, Bmask: Uint32, Amask: Uint32) [*c]SDL_Surface; pub extern fn SDL_CreateRGBSurfaceWithFormatFrom(pixels: ?*anyopaque, width: c_int, height: c_int, depth: c_int, pitch: c_int, format: Uint32) [*c]SDL_Surface; pub extern fn SDL_FreeSurface(surface: [*c]SDL_Surface) void; pub extern fn SDL_SetSurfacePalette(surface: [*c]SDL_Surface, palette: [*c]SDL_Palette) c_int; pub extern fn SDL_LockSurface(surface: [*c]SDL_Surface) c_int; pub extern fn SDL_UnlockSurface(surface: [*c]SDL_Surface) void; pub extern fn SDL_LoadBMP_RW(src: [*c]SDL_RWops, freesrc: c_int) [*c]SDL_Surface; pub extern fn SDL_SaveBMP_RW(surface: [*c]SDL_Surface, dst: [*c]SDL_RWops, freedst: c_int) c_int; pub extern fn SDL_SetSurfaceRLE(surface: [*c]SDL_Surface, flag: c_int) c_int; pub extern fn SDL_HasSurfaceRLE(surface: [*c]SDL_Surface) SDL_bool; pub extern fn SDL_SetColorKey(surface: [*c]SDL_Surface, flag: c_int, key: Uint32) c_int; pub extern fn SDL_HasColorKey(surface: [*c]SDL_Surface) SDL_bool; pub extern fn SDL_GetColorKey(surface: [*c]SDL_Surface, key: [*c]Uint32) c_int; pub extern fn SDL_SetSurfaceColorMod(surface: [*c]SDL_Surface, r: Uint8, g: Uint8, b: Uint8) c_int; pub extern fn SDL_GetSurfaceColorMod(surface: [*c]SDL_Surface, r: [*c]Uint8, g: [*c]Uint8, b: [*c]Uint8) c_int; pub extern fn SDL_SetSurfaceAlphaMod(surface: [*c]SDL_Surface, alpha: Uint8) c_int; pub extern fn SDL_GetSurfaceAlphaMod(surface: [*c]SDL_Surface, alpha: [*c]Uint8) c_int; pub extern fn SDL_SetSurfaceBlendMode(surface: [*c]SDL_Surface, blendMode: SDL_BlendMode) c_int; pub extern fn SDL_GetSurfaceBlendMode(surface: [*c]SDL_Surface, blendMode: [*c]SDL_BlendMode) c_int; pub extern fn SDL_SetClipRect(surface: [*c]SDL_Surface, rect: [*c]const SDL_Rect) SDL_bool; pub extern fn SDL_GetClipRect(surface: [*c]SDL_Surface, rect: [*c]SDL_Rect) void; pub extern fn SDL_DuplicateSurface(surface: [*c]SDL_Surface) [*c]SDL_Surface; pub extern fn SDL_ConvertSurface(src: [*c]SDL_Surface, fmt: [*c]const SDL_PixelFormat, flags: Uint32) [*c]SDL_Surface; pub extern fn SDL_ConvertSurfaceFormat(src: [*c]SDL_Surface, pixel_format: Uint32, flags: Uint32) [*c]SDL_Surface; pub extern fn SDL_ConvertPixels(width: c_int, height: c_int, src_format: Uint32, src: ?*const anyopaque, src_pitch: c_int, dst_format: Uint32, dst: ?*anyopaque, dst_pitch: c_int) c_int; pub extern fn SDL_FillRect(dst: [*c]SDL_Surface, rect: [*c]const SDL_Rect, color: Uint32) c_int; pub extern fn SDL_FillRects(dst: [*c]SDL_Surface, rects: [*c]const SDL_Rect, count: c_int, color: Uint32) c_int; pub extern fn SDL_UpperBlit(src: [*c]SDL_Surface, srcrect: [*c]const SDL_Rect, dst: [*c]SDL_Surface, dstrect: [*c]SDL_Rect) c_int; pub extern fn SDL_LowerBlit(src: [*c]SDL_Surface, srcrect: [*c]SDL_Rect, dst: [*c]SDL_Surface, dstrect: [*c]SDL_Rect) c_int; pub extern fn SDL_SoftStretch(src: [*c]SDL_Surface, srcrect: [*c]const SDL_Rect, dst: [*c]SDL_Surface, dstrect: [*c]const SDL_Rect) c_int; pub extern fn SDL_SoftStretchLinear(src: [*c]SDL_Surface, srcrect: [*c]const SDL_Rect, dst: [*c]SDL_Surface, dstrect: [*c]const SDL_Rect) c_int; pub extern fn SDL_UpperBlitScaled(src: [*c]SDL_Surface, srcrect: [*c]const SDL_Rect, dst: [*c]SDL_Surface, dstrect: [*c]SDL_Rect) c_int; pub extern fn SDL_LowerBlitScaled(src: [*c]SDL_Surface, srcrect: [*c]SDL_Rect, dst: [*c]SDL_Surface, dstrect: [*c]SDL_Rect) c_int; pub extern fn SDL_SetYUVConversionMode(mode: SDL_YUV_CONVERSION_MODE) void; pub extern fn SDL_GetYUVConversionMode() SDL_YUV_CONVERSION_MODE; pub extern fn SDL_GetYUVConversionModeForResolution(width: c_int, height: c_int) SDL_YUV_CONVERSION_MODE; pub const SDL_DisplayMode = extern struct { format: Uint32, w: c_int, h: c_int, refresh_rate: c_int, driverdata: ?*anyopaque, }; pub const struct_SDL_Window = opaque {}; pub const SDL_Window = struct_SDL_Window; pub const SDL_WINDOW_FULLSCREEN = @enumToInt(enum_unnamed_40.SDL_WINDOW_FULLSCREEN); pub const SDL_WINDOW_OPENGL = @enumToInt(enum_unnamed_40.SDL_WINDOW_OPENGL); pub const SDL_WINDOW_SHOWN = @enumToInt(enum_unnamed_40.SDL_WINDOW_SHOWN); pub const SDL_WINDOW_HIDDEN = @enumToInt(enum_unnamed_40.SDL_WINDOW_HIDDEN); pub const SDL_WINDOW_BORDERLESS = @enumToInt(enum_unnamed_40.SDL_WINDOW_BORDERLESS); pub const SDL_WINDOW_RESIZABLE = @enumToInt(enum_unnamed_40.SDL_WINDOW_RESIZABLE); pub const SDL_WINDOW_MINIMIZED = @enumToInt(enum_unnamed_40.SDL_WINDOW_MINIMIZED); pub const SDL_WINDOW_MAXIMIZED = @enumToInt(enum_unnamed_40.SDL_WINDOW_MAXIMIZED); pub const SDL_WINDOW_INPUT_GRABBED = @enumToInt(enum_unnamed_40.SDL_WINDOW_INPUT_GRABBED); pub const SDL_WINDOW_INPUT_FOCUS = @enumToInt(enum_unnamed_40.SDL_WINDOW_INPUT_FOCUS); pub const SDL_WINDOW_MOUSE_FOCUS = @enumToInt(enum_unnamed_40.SDL_WINDOW_MOUSE_FOCUS); pub const SDL_WINDOW_FULLSCREEN_DESKTOP = @enumToInt(enum_unnamed_40.SDL_WINDOW_FULLSCREEN_DESKTOP); pub const SDL_WINDOW_FOREIGN = @enumToInt(enum_unnamed_40.SDL_WINDOW_FOREIGN); pub const SDL_WINDOW_ALLOW_HIGHDPI = @enumToInt(enum_unnamed_40.SDL_WINDOW_ALLOW_HIGHDPI); pub const SDL_WINDOW_MOUSE_CAPTURE = @enumToInt(enum_unnamed_40.SDL_WINDOW_MOUSE_CAPTURE); pub const SDL_WINDOW_ALWAYS_ON_TOP = @enumToInt(enum_unnamed_40.SDL_WINDOW_ALWAYS_ON_TOP); pub const SDL_WINDOW_SKIP_TASKBAR = @enumToInt(enum_unnamed_40.SDL_WINDOW_SKIP_TASKBAR); pub const SDL_WINDOW_UTILITY = @enumToInt(enum_unnamed_40.SDL_WINDOW_UTILITY); pub const SDL_WINDOW_TOOLTIP = @enumToInt(enum_unnamed_40.SDL_WINDOW_TOOLTIP); pub const SDL_WINDOW_POPUP_MENU = @enumToInt(enum_unnamed_40.SDL_WINDOW_POPUP_MENU); pub const SDL_WINDOW_VULKAN = @enumToInt(enum_unnamed_40.SDL_WINDOW_VULKAN); pub const SDL_WINDOW_METAL = @enumToInt(enum_unnamed_40.SDL_WINDOW_METAL); const enum_unnamed_40 = enum(c_int) { SDL_WINDOW_FULLSCREEN = 1, SDL_WINDOW_OPENGL = 2, SDL_WINDOW_SHOWN = 4, SDL_WINDOW_HIDDEN = 8, SDL_WINDOW_BORDERLESS = 16, SDL_WINDOW_RESIZABLE = 32, SDL_WINDOW_MINIMIZED = 64, SDL_WINDOW_MAXIMIZED = 128, SDL_WINDOW_INPUT_GRABBED = 256, SDL_WINDOW_INPUT_FOCUS = 512, SDL_WINDOW_MOUSE_FOCUS = 1024, SDL_WINDOW_FULLSCREEN_DESKTOP = 4097, SDL_WINDOW_FOREIGN = 2048, SDL_WINDOW_ALLOW_HIGHDPI = 8192, SDL_WINDOW_MOUSE_CAPTURE = 16384, SDL_WINDOW_ALWAYS_ON_TOP = 32768, SDL_WINDOW_SKIP_TASKBAR = 65536, SDL_WINDOW_UTILITY = 131072, SDL_WINDOW_TOOLTIP = 262144, SDL_WINDOW_POPUP_MENU = 524288, SDL_WINDOW_VULKAN = 268435456, SDL_WINDOW_METAL = 536870912, _, }; pub const SDL_WindowFlags = enum_unnamed_40; pub const SDL_WINDOWEVENT_NONE = @enumToInt(enum_unnamed_41.SDL_WINDOWEVENT_NONE); pub const SDL_WINDOWEVENT_SHOWN = @enumToInt(enum_unnamed_41.SDL_WINDOWEVENT_SHOWN); pub const SDL_WINDOWEVENT_HIDDEN = @enumToInt(enum_unnamed_41.SDL_WINDOWEVENT_HIDDEN); pub const SDL_WINDOWEVENT_EXPOSED = @enumToInt(enum_unnamed_41.SDL_WINDOWEVENT_EXPOSED); pub const SDL_WINDOWEVENT_MOVED = @enumToInt(enum_unnamed_41.SDL_WINDOWEVENT_MOVED); pub const SDL_WINDOWEVENT_RESIZED = @enumToInt(enum_unnamed_41.SDL_WINDOWEVENT_RESIZED); pub const SDL_WINDOWEVENT_SIZE_CHANGED = @enumToInt(enum_unnamed_41.SDL_WINDOWEVENT_SIZE_CHANGED); pub const SDL_WINDOWEVENT_MINIMIZED = @enumToInt(enum_unnamed_41.SDL_WINDOWEVENT_MINIMIZED); pub const SDL_WINDOWEVENT_MAXIMIZED = @enumToInt(enum_unnamed_41.SDL_WINDOWEVENT_MAXIMIZED); pub const SDL_WINDOWEVENT_RESTORED = @enumToInt(enum_unnamed_41.SDL_WINDOWEVENT_RESTORED); pub const SDL_WINDOWEVENT_ENTER = @enumToInt(enum_unnamed_41.SDL_WINDOWEVENT_ENTER); pub const SDL_WINDOWEVENT_LEAVE = @enumToInt(enum_unnamed_41.SDL_WINDOWEVENT_LEAVE); pub const SDL_WINDOWEVENT_FOCUS_GAINED = @enumToInt(enum_unnamed_41.SDL_WINDOWEVENT_FOCUS_GAINED); pub const SDL_WINDOWEVENT_FOCUS_LOST = @enumToInt(enum_unnamed_41.SDL_WINDOWEVENT_FOCUS_LOST); pub const SDL_WINDOWEVENT_CLOSE = @enumToInt(enum_unnamed_41.SDL_WINDOWEVENT_CLOSE); pub const SDL_WINDOWEVENT_TAKE_FOCUS = @enumToInt(enum_unnamed_41.SDL_WINDOWEVENT_TAKE_FOCUS); pub const SDL_WINDOWEVENT_HIT_TEST = @enumToInt(enum_unnamed_41.SDL_WINDOWEVENT_HIT_TEST); const enum_unnamed_41 = enum(c_int) { SDL_WINDOWEVENT_NONE, SDL_WINDOWEVENT_SHOWN, SDL_WINDOWEVENT_HIDDEN, SDL_WINDOWEVENT_EXPOSED, SDL_WINDOWEVENT_MOVED, SDL_WINDOWEVENT_RESIZED, SDL_WINDOWEVENT_SIZE_CHANGED, SDL_WINDOWEVENT_MINIMIZED, SDL_WINDOWEVENT_MAXIMIZED, SDL_WINDOWEVENT_RESTORED, SDL_WINDOWEVENT_ENTER, SDL_WINDOWEVENT_LEAVE, SDL_WINDOWEVENT_FOCUS_GAINED, SDL_WINDOWEVENT_FOCUS_LOST, SDL_WINDOWEVENT_CLOSE, SDL_WINDOWEVENT_TAKE_FOCUS, SDL_WINDOWEVENT_HIT_TEST, _, }; pub const SDL_WindowEventID = enum_unnamed_41; pub const SDL_DISPLAYEVENT_NONE = @enumToInt(enum_unnamed_42.SDL_DISPLAYEVENT_NONE); pub const SDL_DISPLAYEVENT_ORIENTATION = @enumToInt(enum_unnamed_42.SDL_DISPLAYEVENT_ORIENTATION); pub const SDL_DISPLAYEVENT_CONNECTED = @enumToInt(enum_unnamed_42.SDL_DISPLAYEVENT_CONNECTED); pub const SDL_DISPLAYEVENT_DISCONNECTED = @enumToInt(enum_unnamed_42.SDL_DISPLAYEVENT_DISCONNECTED); const enum_unnamed_42 = enum(c_int) { SDL_DISPLAYEVENT_NONE, SDL_DISPLAYEVENT_ORIENTATION, SDL_DISPLAYEVENT_CONNECTED, SDL_DISPLAYEVENT_DISCONNECTED, _, }; pub const SDL_DisplayEventID = enum_unnamed_42; pub const SDL_ORIENTATION_UNKNOWN = @enumToInt(enum_unnamed_43.SDL_ORIENTATION_UNKNOWN); pub const SDL_ORIENTATION_LANDSCAPE = @enumToInt(enum_unnamed_43.SDL_ORIENTATION_LANDSCAPE); pub const SDL_ORIENTATION_LANDSCAPE_FLIPPED = @enumToInt(enum_unnamed_43.SDL_ORIENTATION_LANDSCAPE_FLIPPED); pub const SDL_ORIENTATION_PORTRAIT = @enumToInt(enum_unnamed_43.SDL_ORIENTATION_PORTRAIT); pub const SDL_ORIENTATION_PORTRAIT_FLIPPED = @enumToInt(enum_unnamed_43.SDL_ORIENTATION_PORTRAIT_FLIPPED); const enum_unnamed_43 = enum(c_int) { SDL_ORIENTATION_UNKNOWN, SDL_ORIENTATION_LANDSCAPE, SDL_ORIENTATION_LANDSCAPE_FLIPPED, SDL_ORIENTATION_PORTRAIT, SDL_ORIENTATION_PORTRAIT_FLIPPED, _, }; pub const SDL_DisplayOrientation = enum_unnamed_43; pub const SDL_GLContext = ?*anyopaque; pub const SDL_GL_RED_SIZE = @enumToInt(enum_unnamed_44.SDL_GL_RED_SIZE); pub const SDL_GL_GREEN_SIZE = @enumToInt(enum_unnamed_44.SDL_GL_GREEN_SIZE); pub const SDL_GL_BLUE_SIZE = @enumToInt(enum_unnamed_44.SDL_GL_BLUE_SIZE); pub const SDL_GL_ALPHA_SIZE = @enumToInt(enum_unnamed_44.SDL_GL_ALPHA_SIZE); pub const SDL_GL_BUFFER_SIZE = @enumToInt(enum_unnamed_44.SDL_GL_BUFFER_SIZE); pub const SDL_GL_DOUBLEBUFFER = @enumToInt(enum_unnamed_44.SDL_GL_DOUBLEBUFFER); pub const SDL_GL_DEPTH_SIZE = @enumToInt(enum_unnamed_44.SDL_GL_DEPTH_SIZE); pub const SDL_GL_STENCIL_SIZE = @enumToInt(enum_unnamed_44.SDL_GL_STENCIL_SIZE); pub const SDL_GL_ACCUM_RED_SIZE = @enumToInt(enum_unnamed_44.SDL_GL_ACCUM_RED_SIZE); pub const SDL_GL_ACCUM_GREEN_SIZE = @enumToInt(enum_unnamed_44.SDL_GL_ACCUM_GREEN_SIZE); pub const SDL_GL_ACCUM_BLUE_SIZE = @enumToInt(enum_unnamed_44.SDL_GL_ACCUM_BLUE_SIZE); pub const SDL_GL_ACCUM_ALPHA_SIZE = @enumToInt(enum_unnamed_44.SDL_GL_ACCUM_ALPHA_SIZE); pub const SDL_GL_STEREO = @enumToInt(enum_unnamed_44.SDL_GL_STEREO); pub const SDL_GL_MULTISAMPLEBUFFERS = @enumToInt(enum_unnamed_44.SDL_GL_MULTISAMPLEBUFFERS); pub const SDL_GL_MULTISAMPLESAMPLES = @enumToInt(enum_unnamed_44.SDL_GL_MULTISAMPLESAMPLES); pub const SDL_GL_ACCELERATED_VISUAL = @enumToInt(enum_unnamed_44.SDL_GL_ACCELERATED_VISUAL); pub const SDL_GL_RETAINED_BACKING = @enumToInt(enum_unnamed_44.SDL_GL_RETAINED_BACKING); pub const SDL_GL_CONTEXT_MAJOR_VERSION = @enumToInt(enum_unnamed_44.SDL_GL_CONTEXT_MAJOR_VERSION); pub const SDL_GL_CONTEXT_MINOR_VERSION = @enumToInt(enum_unnamed_44.SDL_GL_CONTEXT_MINOR_VERSION); pub const SDL_GL_CONTEXT_EGL = @enumToInt(enum_unnamed_44.SDL_GL_CONTEXT_EGL); pub const SDL_GL_CONTEXT_FLAGS = @enumToInt(enum_unnamed_44.SDL_GL_CONTEXT_FLAGS); pub const SDL_GL_CONTEXT_PROFILE_MASK = @enumToInt(enum_unnamed_44.SDL_GL_CONTEXT_PROFILE_MASK); pub const SDL_GL_SHARE_WITH_CURRENT_CONTEXT = @enumToInt(enum_unnamed_44.SDL_GL_SHARE_WITH_CURRENT_CONTEXT); pub const SDL_GL_FRAMEBUFFER_SRGB_CAPABLE = @enumToInt(enum_unnamed_44.SDL_GL_FRAMEBUFFER_SRGB_CAPABLE); pub const SDL_GL_CONTEXT_RELEASE_BEHAVIOR = @enumToInt(enum_unnamed_44.SDL_GL_CONTEXT_RELEASE_BEHAVIOR); pub const SDL_GL_CONTEXT_RESET_NOTIFICATION = @enumToInt(enum_unnamed_44.SDL_GL_CONTEXT_RESET_NOTIFICATION); pub const SDL_GL_CONTEXT_NO_ERROR = @enumToInt(enum_unnamed_44.SDL_GL_CONTEXT_NO_ERROR); const enum_unnamed_44 = enum(c_int) { SDL_GL_RED_SIZE, SDL_GL_GREEN_SIZE, SDL_GL_BLUE_SIZE, SDL_GL_ALPHA_SIZE, SDL_GL_BUFFER_SIZE, SDL_GL_DOUBLEBUFFER, SDL_GL_DEPTH_SIZE, SDL_GL_STENCIL_SIZE, SDL_GL_ACCUM_RED_SIZE, SDL_GL_ACCUM_GREEN_SIZE, SDL_GL_ACCUM_BLUE_SIZE, SDL_GL_ACCUM_ALPHA_SIZE, SDL_GL_STEREO, SDL_GL_MULTISAMPLEBUFFERS, SDL_GL_MULTISAMPLESAMPLES, SDL_GL_ACCELERATED_VISUAL, SDL_GL_RETAINED_BACKING, SDL_GL_CONTEXT_MAJOR_VERSION, SDL_GL_CONTEXT_MINOR_VERSION, SDL_GL_CONTEXT_EGL, SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_SHARE_WITH_CURRENT_CONTEXT, SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, SDL_GL_CONTEXT_RELEASE_BEHAVIOR, SDL_GL_CONTEXT_RESET_NOTIFICATION, SDL_GL_CONTEXT_NO_ERROR, _, }; pub const SDL_GLattr = enum_unnamed_44; pub const SDL_GL_CONTEXT_PROFILE_CORE = @enumToInt(enum_unnamed_45.SDL_GL_CONTEXT_PROFILE_CORE); pub const SDL_GL_CONTEXT_PROFILE_COMPATIBILITY = @enumToInt(enum_unnamed_45.SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); pub const SDL_GL_CONTEXT_PROFILE_ES = @enumToInt(enum_unnamed_45.SDL_GL_CONTEXT_PROFILE_ES); const enum_unnamed_45 = enum(c_int) { SDL_GL_CONTEXT_PROFILE_CORE = 1, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY = 2, SDL_GL_CONTEXT_PROFILE_ES = 4, _, }; pub const SDL_GLprofile = enum_unnamed_45; pub const SDL_GL_CONTEXT_DEBUG_FLAG = @enumToInt(enum_unnamed_46.SDL_GL_CONTEXT_DEBUG_FLAG); pub const SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG = @enumToInt(enum_unnamed_46.SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); pub const SDL_GL_CONTEXT_ROBUST_ACCESS_FLAG = @enumToInt(enum_unnamed_46.SDL_GL_CONTEXT_ROBUST_ACCESS_FLAG); pub const SDL_GL_CONTEXT_RESET_ISOLATION_FLAG = @enumToInt(enum_unnamed_46.SDL_GL_CONTEXT_RESET_ISOLATION_FLAG); const enum_unnamed_46 = enum(c_int) { SDL_GL_CONTEXT_DEBUG_FLAG = 1, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG = 2, SDL_GL_CONTEXT_ROBUST_ACCESS_FLAG = 4, SDL_GL_CONTEXT_RESET_ISOLATION_FLAG = 8, _, }; pub const SDL_GLcontextFlag = enum_unnamed_46; pub const SDL_GL_CONTEXT_RELEASE_BEHAVIOR_NONE = @enumToInt(enum_unnamed_47.SDL_GL_CONTEXT_RELEASE_BEHAVIOR_NONE); pub const SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH = @enumToInt(enum_unnamed_47.SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH); const enum_unnamed_47 = enum(c_int) { SDL_GL_CONTEXT_RELEASE_BEHAVIOR_NONE = 0, SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH = 1, _, }; pub const SDL_GLcontextReleaseFlag = enum_unnamed_47; pub const SDL_GL_CONTEXT_RESET_NO_NOTIFICATION = @enumToInt(enum_unnamed_48.SDL_GL_CONTEXT_RESET_NO_NOTIFICATION); pub const SDL_GL_CONTEXT_RESET_LOSE_CONTEXT = @enumToInt(enum_unnamed_48.SDL_GL_CONTEXT_RESET_LOSE_CONTEXT); const enum_unnamed_48 = enum(c_int) { SDL_GL_CONTEXT_RESET_NO_NOTIFICATION = 0, SDL_GL_CONTEXT_RESET_LOSE_CONTEXT = 1, _, }; pub const SDL_GLContextResetNotification = enum_unnamed_48; pub extern fn SDL_GetNumVideoDrivers() c_int; pub extern fn SDL_GetVideoDriver(index: c_int) [*c]const u8; pub extern fn SDL_VideoInit(driver_name: [*c]const u8) c_int; pub extern fn SDL_VideoQuit() void; pub extern fn SDL_GetCurrentVideoDriver() [*c]const u8; pub extern fn SDL_GetNumVideoDisplays() c_int; pub extern fn SDL_GetDisplayName(displayIndex: c_int) [*c]const u8; pub extern fn SDL_GetDisplayBounds(displayIndex: c_int, rect: [*c]SDL_Rect) c_int; pub extern fn SDL_GetDisplayUsableBounds(displayIndex: c_int, rect: [*c]SDL_Rect) c_int; pub extern fn SDL_GetDisplayDPI(displayIndex: c_int, ddpi: [*c]f32, hdpi: [*c]f32, vdpi: [*c]f32) c_int; pub extern fn SDL_GetDisplayOrientation(displayIndex: c_int) SDL_DisplayOrientation; pub extern fn SDL_GetNumDisplayModes(displayIndex: c_int) c_int; pub extern fn SDL_GetDisplayMode(displayIndex: c_int, modeIndex: c_int, mode: [*c]SDL_DisplayMode) c_int; pub extern fn SDL_GetDesktopDisplayMode(displayIndex: c_int, mode: [*c]SDL_DisplayMode) c_int; pub extern fn SDL_GetCurrentDisplayMode(displayIndex: c_int, mode: [*c]SDL_DisplayMode) c_int; pub extern fn SDL_GetClosestDisplayMode(displayIndex: c_int, mode: [*c]const SDL_DisplayMode, closest: [*c]SDL_DisplayMode) [*c]SDL_DisplayMode; pub extern fn SDL_GetWindowDisplayIndex(window: ?*SDL_Window) c_int; pub extern fn SDL_SetWindowDisplayMode(window: ?*SDL_Window, mode: [*c]const SDL_DisplayMode) c_int; pub extern fn SDL_GetWindowDisplayMode(window: ?*SDL_Window, mode: [*c]SDL_DisplayMode) c_int; pub extern fn SDL_GetWindowPixelFormat(window: ?*SDL_Window) Uint32; pub extern fn SDL_CreateWindow(title: [*c]const u8, x: c_int, y: c_int, w: c_int, h: c_int, flags: Uint32) ?*SDL_Window; pub extern fn SDL_CreateWindowFrom(data: ?*const anyopaque) ?*SDL_Window; pub extern fn SDL_GetWindowID(window: ?*SDL_Window) Uint32; pub extern fn SDL_GetWindowFromID(id: Uint32) ?*SDL_Window; pub extern fn SDL_GetWindowFlags(window: ?*SDL_Window) Uint32; pub extern fn SDL_SetWindowTitle(window: ?*SDL_Window, title: [*c]const u8) void; pub extern fn SDL_GetWindowTitle(window: ?*SDL_Window) [*c]const u8; pub extern fn SDL_SetWindowIcon(window: ?*SDL_Window, icon: [*c]SDL_Surface) void; pub extern fn SDL_SetWindowData(window: ?*SDL_Window, name: [*c]const u8, userdata: ?*anyopaque) ?*anyopaque; pub extern fn SDL_GetWindowData(window: ?*SDL_Window, name: [*c]const u8) ?*anyopaque; pub extern fn SDL_SetWindowPosition(window: ?*SDL_Window, x: c_int, y: c_int) void; pub extern fn SDL_GetWindowPosition(window: ?*SDL_Window, x: [*c]c_int, y: [*c]c_int) void; pub extern fn SDL_SetWindowSize(window: ?*SDL_Window, w: c_int, h: c_int) void; pub extern fn SDL_GetWindowSize(window: ?*SDL_Window, w: [*c]c_int, h: [*c]c_int) void; pub extern fn SDL_GetWindowBordersSize(window: ?*SDL_Window, top: [*c]c_int, left: [*c]c_int, bottom: [*c]c_int, right: [*c]c_int) c_int; pub extern fn SDL_SetWindowMinimumSize(window: ?*SDL_Window, min_w: c_int, min_h: c_int) void; pub extern fn SDL_GetWindowMinimumSize(window: ?*SDL_Window, w: [*c]c_int, h: [*c]c_int) void; pub extern fn SDL_SetWindowMaximumSize(window: ?*SDL_Window, max_w: c_int, max_h: c_int) void; pub extern fn SDL_GetWindowMaximumSize(window: ?*SDL_Window, w: [*c]c_int, h: [*c]c_int) void; pub extern fn SDL_SetWindowBordered(window: ?*SDL_Window, bordered: SDL_bool) void; pub extern fn SDL_SetWindowResizable(window: ?*SDL_Window, resizable: SDL_bool) void; pub extern fn SDL_SetWindowAlwaysOnTop(window: ?*SDL_Window, on_top: SDL_bool) void; pub extern fn SDL_ShowWindow(window: ?*SDL_Window) void; pub extern fn SDL_HideWindow(window: ?*SDL_Window) void; pub extern fn SDL_RaiseWindow(window: ?*SDL_Window) void; pub extern fn SDL_MaximizeWindow(window: ?*SDL_Window) void; pub extern fn SDL_MinimizeWindow(window: ?*SDL_Window) void; pub extern fn SDL_RestoreWindow(window: ?*SDL_Window) void; pub extern fn SDL_SetWindowFullscreen(window: ?*SDL_Window, flags: Uint32) c_int; pub extern fn SDL_GetWindowSurface(window: ?*SDL_Window) [*c]SDL_Surface; pub extern fn SDL_UpdateWindowSurface(window: ?*SDL_Window) c_int; pub extern fn SDL_UpdateWindowSurfaceRects(window: ?*SDL_Window, rects: [*c]const SDL_Rect, numrects: c_int) c_int; pub extern fn SDL_SetWindowGrab(window: ?*SDL_Window, grabbed: SDL_bool) void; pub extern fn SDL_SetWindowKeyboardGrab(window: ?*SDL_Window, grabbed: SDL_bool) void; pub extern fn SDL_SetWindowMouseGrab(window: ?*SDL_Window, grabbed: SDL_bool) void; pub extern fn SDL_GetWindowGrab(window: ?*SDL_Window) SDL_bool; pub extern fn SDL_GetWindowKeyboardGrab(window: ?*SDL_Window) SDL_bool; pub extern fn SDL_GetWindowMouseGrab(window: ?*SDL_Window) SDL_bool; pub extern fn SDL_GetGrabbedWindow() ?*SDL_Window; pub extern fn SDL_SetWindowBrightness(window: ?*SDL_Window, brightness: f32) c_int; pub extern fn SDL_GetWindowBrightness(window: ?*SDL_Window) f32; pub extern fn SDL_SetWindowOpacity(window: ?*SDL_Window, opacity: f32) c_int; pub extern fn SDL_GetWindowOpacity(window: ?*SDL_Window, out_opacity: [*c]f32) c_int; pub extern fn SDL_SetWindowModalFor(modal_window: ?*SDL_Window, parent_window: ?*SDL_Window) c_int; pub extern fn SDL_SetWindowInputFocus(window: ?*SDL_Window) c_int; pub extern fn SDL_SetWindowGammaRamp(window: ?*SDL_Window, red: [*c]const Uint16, green: [*c]const Uint16, blue: [*c]const Uint16) c_int; pub extern fn SDL_GetWindowGammaRamp(window: ?*SDL_Window, red: [*c]Uint16, green: [*c]Uint16, blue: [*c]Uint16) c_int; pub const SDL_HITTEST_NORMAL = @enumToInt(enum_unnamed_49.SDL_HITTEST_NORMAL); pub const SDL_HITTEST_DRAGGABLE = @enumToInt(enum_unnamed_49.SDL_HITTEST_DRAGGABLE); pub const SDL_HITTEST_RESIZE_TOPLEFT = @enumToInt(enum_unnamed_49.SDL_HITTEST_RESIZE_TOPLEFT); pub const SDL_HITTEST_RESIZE_TOP = @enumToInt(enum_unnamed_49.SDL_HITTEST_RESIZE_TOP); pub const SDL_HITTEST_RESIZE_TOPRIGHT = @enumToInt(enum_unnamed_49.SDL_HITTEST_RESIZE_TOPRIGHT); pub const SDL_HITTEST_RESIZE_RIGHT = @enumToInt(enum_unnamed_49.SDL_HITTEST_RESIZE_RIGHT); pub const SDL_HITTEST_RESIZE_BOTTOMRIGHT = @enumToInt(enum_unnamed_49.SDL_HITTEST_RESIZE_BOTTOMRIGHT); pub const SDL_HITTEST_RESIZE_BOTTOM = @enumToInt(enum_unnamed_49.SDL_HITTEST_RESIZE_BOTTOM); pub const SDL_HITTEST_RESIZE_BOTTOMLEFT = @enumToInt(enum_unnamed_49.SDL_HITTEST_RESIZE_BOTTOMLEFT); pub const SDL_HITTEST_RESIZE_LEFT = @enumToInt(enum_unnamed_49.SDL_HITTEST_RESIZE_LEFT); const enum_unnamed_49 = enum(c_int) { SDL_HITTEST_NORMAL, SDL_HITTEST_DRAGGABLE, SDL_HITTEST_RESIZE_TOPLEFT, SDL_HITTEST_RESIZE_TOP, SDL_HITTEST_RESIZE_TOPRIGHT, SDL_HITTEST_RESIZE_RIGHT, SDL_HITTEST_RESIZE_BOTTOMRIGHT, SDL_HITTEST_RESIZE_BOTTOM, SDL_HITTEST_RESIZE_BOTTOMLEFT, SDL_HITTEST_RESIZE_LEFT, _, }; pub const SDL_HitTestResult = enum_unnamed_49; pub const SDL_HitTest = ?fn (?*SDL_Window, [*c]const SDL_Point, ?*anyopaque) callconv(.C) SDL_HitTestResult; pub extern fn SDL_SetWindowHitTest(window: ?*SDL_Window, callback: SDL_HitTest, callback_data: ?*anyopaque) c_int; // pub extern fn SDL_FlashWindow(window: ?*SDL_Window, operation: SDL_FlashOperation) c_int; pub extern fn SDL_DestroyWindow(window: ?*SDL_Window) void; pub extern fn SDL_IsScreenSaverEnabled() SDL_bool; pub extern fn SDL_EnableScreenSaver() void; pub extern fn SDL_DisableScreenSaver() void; pub extern fn SDL_GL_LoadLibrary(path: [*c]const u8) c_int; pub extern fn SDL_GL_GetProcAddress(proc: [*c]const u8) ?*anyopaque; pub extern fn SDL_GL_UnloadLibrary() void; pub extern fn SDL_GL_ExtensionSupported(extension: [*c]const u8) SDL_bool; pub extern fn SDL_GL_ResetAttributes() void; pub extern fn SDL_GL_SetAttribute(attr: SDL_GLattr, value: c_int) c_int; pub extern fn SDL_GL_GetAttribute(attr: SDL_GLattr, value: [*c]c_int) c_int; pub extern fn SDL_GL_CreateContext(window: ?*SDL_Window) SDL_GLContext; pub extern fn SDL_GL_MakeCurrent(window: ?*SDL_Window, context: SDL_GLContext) c_int; pub extern fn SDL_GL_GetCurrentWindow() ?*SDL_Window; pub extern fn SDL_GL_GetCurrentContext() SDL_GLContext; pub extern fn SDL_GL_GetDrawableSize(window: ?*SDL_Window, w: [*c]c_int, h: [*c]c_int) void; pub extern fn SDL_GL_SetSwapInterval(interval: c_int) c_int; pub extern fn SDL_GL_GetSwapInterval() c_int; pub extern fn SDL_GL_SwapWindow(window: ?*SDL_Window) void; pub extern fn SDL_GL_DeleteContext(context: SDL_GLContext) void; pub const SDL_SCANCODE_UNKNOWN = @enumToInt(enum_unnamed_50.SDL_SCANCODE_UNKNOWN); pub const SDL_SCANCODE_A = @enumToInt(enum_unnamed_50.SDL_SCANCODE_A); pub const SDL_SCANCODE_B = @enumToInt(enum_unnamed_50.SDL_SCANCODE_B); pub const SDL_SCANCODE_C = @enumToInt(enum_unnamed_50.SDL_SCANCODE_C); pub const SDL_SCANCODE_D = @enumToInt(enum_unnamed_50.SDL_SCANCODE_D); pub const SDL_SCANCODE_E = @enumToInt(enum_unnamed_50.SDL_SCANCODE_E); pub const SDL_SCANCODE_F = @enumToInt(enum_unnamed_50.SDL_SCANCODE_F); pub const SDL_SCANCODE_G = @enumToInt(enum_unnamed_50.SDL_SCANCODE_G); pub const SDL_SCANCODE_H = @enumToInt(enum_unnamed_50.SDL_SCANCODE_H); pub const SDL_SCANCODE_I = @enumToInt(enum_unnamed_50.SDL_SCANCODE_I); pub const SDL_SCANCODE_J = @enumToInt(enum_unnamed_50.SDL_SCANCODE_J); pub const SDL_SCANCODE_K = @enumToInt(enum_unnamed_50.SDL_SCANCODE_K); pub const SDL_SCANCODE_L = @enumToInt(enum_unnamed_50.SDL_SCANCODE_L); pub const SDL_SCANCODE_M = @enumToInt(enum_unnamed_50.SDL_SCANCODE_M); pub const SDL_SCANCODE_N = @enumToInt(enum_unnamed_50.SDL_SCANCODE_N); pub const SDL_SCANCODE_O = @enumToInt(enum_unnamed_50.SDL_SCANCODE_O); pub const SDL_SCANCODE_P = @enumToInt(enum_unnamed_50.SDL_SCANCODE_P); pub const SDL_SCANCODE_Q = @enumToInt(enum_unnamed_50.SDL_SCANCODE_Q); pub const SDL_SCANCODE_R = @enumToInt(enum_unnamed_50.SDL_SCANCODE_R); pub const SDL_SCANCODE_S = @enumToInt(enum_unnamed_50.SDL_SCANCODE_S); pub const SDL_SCANCODE_T = @enumToInt(enum_unnamed_50.SDL_SCANCODE_T); pub const SDL_SCANCODE_U = @enumToInt(enum_unnamed_50.SDL_SCANCODE_U); pub const SDL_SCANCODE_V = @enumToInt(enum_unnamed_50.SDL_SCANCODE_V); pub const SDL_SCANCODE_W = @enumToInt(enum_unnamed_50.SDL_SCANCODE_W); pub const SDL_SCANCODE_X = @enumToInt(enum_unnamed_50.SDL_SCANCODE_X); pub const SDL_SCANCODE_Y = @enumToInt(enum_unnamed_50.SDL_SCANCODE_Y); pub const SDL_SCANCODE_Z = @enumToInt(enum_unnamed_50.SDL_SCANCODE_Z); pub const SDL_SCANCODE_1 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_1); pub const SDL_SCANCODE_2 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_2); pub const SDL_SCANCODE_3 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_3); pub const SDL_SCANCODE_4 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_4); pub const SDL_SCANCODE_5 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_5); pub const SDL_SCANCODE_6 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_6); pub const SDL_SCANCODE_7 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_7); pub const SDL_SCANCODE_8 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_8); pub const SDL_SCANCODE_9 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_9); pub const SDL_SCANCODE_0 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_0); pub const SDL_SCANCODE_RETURN = @enumToInt(enum_unnamed_50.SDL_SCANCODE_RETURN); pub const SDL_SCANCODE_ESCAPE = @enumToInt(enum_unnamed_50.SDL_SCANCODE_ESCAPE); pub const SDL_SCANCODE_BACKSPACE = @enumToInt(enum_unnamed_50.SDL_SCANCODE_BACKSPACE); pub const SDL_SCANCODE_TAB = @enumToInt(enum_unnamed_50.SDL_SCANCODE_TAB); pub const SDL_SCANCODE_SPACE = @enumToInt(enum_unnamed_50.SDL_SCANCODE_SPACE); pub const SDL_SCANCODE_MINUS = @enumToInt(enum_unnamed_50.SDL_SCANCODE_MINUS); pub const SDL_SCANCODE_EQUALS = @enumToInt(enum_unnamed_50.SDL_SCANCODE_EQUALS); pub const SDL_SCANCODE_LEFTBRACKET = @enumToInt(enum_unnamed_50.SDL_SCANCODE_LEFTBRACKET); pub const SDL_SCANCODE_RIGHTBRACKET = @enumToInt(enum_unnamed_50.SDL_SCANCODE_RIGHTBRACKET); pub const SDL_SCANCODE_BACKSLASH = @enumToInt(enum_unnamed_50.SDL_SCANCODE_BACKSLASH); pub const SDL_SCANCODE_NONUSHASH = @enumToInt(enum_unnamed_50.SDL_SCANCODE_NONUSHASH); pub const SDL_SCANCODE_SEMICOLON = @enumToInt(enum_unnamed_50.SDL_SCANCODE_SEMICOLON); pub const SDL_SCANCODE_APOSTROPHE = @enumToInt(enum_unnamed_50.SDL_SCANCODE_APOSTROPHE); pub const SDL_SCANCODE_GRAVE = @enumToInt(enum_unnamed_50.SDL_SCANCODE_GRAVE); pub const SDL_SCANCODE_COMMA = @enumToInt(enum_unnamed_50.SDL_SCANCODE_COMMA); pub const SDL_SCANCODE_PERIOD = @enumToInt(enum_unnamed_50.SDL_SCANCODE_PERIOD); pub const SDL_SCANCODE_SLASH = @enumToInt(enum_unnamed_50.SDL_SCANCODE_SLASH); pub const SDL_SCANCODE_CAPSLOCK = @enumToInt(enum_unnamed_50.SDL_SCANCODE_CAPSLOCK); pub const SDL_SCANCODE_F1 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_F1); pub const SDL_SCANCODE_F2 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_F2); pub const SDL_SCANCODE_F3 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_F3); pub const SDL_SCANCODE_F4 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_F4); pub const SDL_SCANCODE_F5 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_F5); pub const SDL_SCANCODE_F6 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_F6); pub const SDL_SCANCODE_F7 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_F7); pub const SDL_SCANCODE_F8 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_F8); pub const SDL_SCANCODE_F9 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_F9); pub const SDL_SCANCODE_F10 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_F10); pub const SDL_SCANCODE_F11 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_F11); pub const SDL_SCANCODE_F12 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_F12); pub const SDL_SCANCODE_PRINTSCREEN = @enumToInt(enum_unnamed_50.SDL_SCANCODE_PRINTSCREEN); pub const SDL_SCANCODE_SCROLLLOCK = @enumToInt(enum_unnamed_50.SDL_SCANCODE_SCROLLLOCK); pub const SDL_SCANCODE_PAUSE = @enumToInt(enum_unnamed_50.SDL_SCANCODE_PAUSE); pub const SDL_SCANCODE_INSERT = @enumToInt(enum_unnamed_50.SDL_SCANCODE_INSERT); pub const SDL_SCANCODE_HOME = @enumToInt(enum_unnamed_50.SDL_SCANCODE_HOME); pub const SDL_SCANCODE_PAGEUP = @enumToInt(enum_unnamed_50.SDL_SCANCODE_PAGEUP); pub const SDL_SCANCODE_DELETE = @enumToInt(enum_unnamed_50.SDL_SCANCODE_DELETE); pub const SDL_SCANCODE_END = @enumToInt(enum_unnamed_50.SDL_SCANCODE_END); pub const SDL_SCANCODE_PAGEDOWN = @enumToInt(enum_unnamed_50.SDL_SCANCODE_PAGEDOWN); pub const SDL_SCANCODE_RIGHT = @enumToInt(enum_unnamed_50.SDL_SCANCODE_RIGHT); pub const SDL_SCANCODE_LEFT = @enumToInt(enum_unnamed_50.SDL_SCANCODE_LEFT); pub const SDL_SCANCODE_DOWN = @enumToInt(enum_unnamed_50.SDL_SCANCODE_DOWN); pub const SDL_SCANCODE_UP = @enumToInt(enum_unnamed_50.SDL_SCANCODE_UP); pub const SDL_SCANCODE_NUMLOCKCLEAR = @enumToInt(enum_unnamed_50.SDL_SCANCODE_NUMLOCKCLEAR); pub const SDL_SCANCODE_KP_DIVIDE = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_DIVIDE); pub const SDL_SCANCODE_KP_MULTIPLY = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_MULTIPLY); pub const SDL_SCANCODE_KP_MINUS = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_MINUS); pub const SDL_SCANCODE_KP_PLUS = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_PLUS); pub const SDL_SCANCODE_KP_ENTER = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_ENTER); pub const SDL_SCANCODE_KP_1 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_1); pub const SDL_SCANCODE_KP_2 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_2); pub const SDL_SCANCODE_KP_3 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_3); pub const SDL_SCANCODE_KP_4 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_4); pub const SDL_SCANCODE_KP_5 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_5); pub const SDL_SCANCODE_KP_6 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_6); pub const SDL_SCANCODE_KP_7 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_7); pub const SDL_SCANCODE_KP_8 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_8); pub const SDL_SCANCODE_KP_9 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_9); pub const SDL_SCANCODE_KP_0 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_0); pub const SDL_SCANCODE_KP_PERIOD = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_PERIOD); pub const SDL_SCANCODE_NONUSBACKSLASH = @enumToInt(enum_unnamed_50.SDL_SCANCODE_NONUSBACKSLASH); pub const SDL_SCANCODE_APPLICATION = @enumToInt(enum_unnamed_50.SDL_SCANCODE_APPLICATION); pub const SDL_SCANCODE_POWER = @enumToInt(enum_unnamed_50.SDL_SCANCODE_POWER); pub const SDL_SCANCODE_KP_EQUALS = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_EQUALS); pub const SDL_SCANCODE_F13 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_F13); pub const SDL_SCANCODE_F14 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_F14); pub const SDL_SCANCODE_F15 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_F15); pub const SDL_SCANCODE_F16 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_F16); pub const SDL_SCANCODE_F17 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_F17); pub const SDL_SCANCODE_F18 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_F18); pub const SDL_SCANCODE_F19 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_F19); pub const SDL_SCANCODE_F20 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_F20); pub const SDL_SCANCODE_F21 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_F21); pub const SDL_SCANCODE_F22 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_F22); pub const SDL_SCANCODE_F23 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_F23); pub const SDL_SCANCODE_F24 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_F24); pub const SDL_SCANCODE_EXECUTE = @enumToInt(enum_unnamed_50.SDL_SCANCODE_EXECUTE); pub const SDL_SCANCODE_HELP = @enumToInt(enum_unnamed_50.SDL_SCANCODE_HELP); pub const SDL_SCANCODE_MENU = @enumToInt(enum_unnamed_50.SDL_SCANCODE_MENU); pub const SDL_SCANCODE_SELECT = @enumToInt(enum_unnamed_50.SDL_SCANCODE_SELECT); pub const SDL_SCANCODE_STOP = @enumToInt(enum_unnamed_50.SDL_SCANCODE_STOP); pub const SDL_SCANCODE_AGAIN = @enumToInt(enum_unnamed_50.SDL_SCANCODE_AGAIN); pub const SDL_SCANCODE_UNDO = @enumToInt(enum_unnamed_50.SDL_SCANCODE_UNDO); pub const SDL_SCANCODE_CUT = @enumToInt(enum_unnamed_50.SDL_SCANCODE_CUT); pub const SDL_SCANCODE_COPY = @enumToInt(enum_unnamed_50.SDL_SCANCODE_COPY); pub const SDL_SCANCODE_PASTE = @enumToInt(enum_unnamed_50.SDL_SCANCODE_PASTE); pub const SDL_SCANCODE_FIND = @enumToInt(enum_unnamed_50.SDL_SCANCODE_FIND); pub const SDL_SCANCODE_MUTE = @enumToInt(enum_unnamed_50.SDL_SCANCODE_MUTE); pub const SDL_SCANCODE_VOLUMEUP = @enumToInt(enum_unnamed_50.SDL_SCANCODE_VOLUMEUP); pub const SDL_SCANCODE_VOLUMEDOWN = @enumToInt(enum_unnamed_50.SDL_SCANCODE_VOLUMEDOWN); pub const SDL_SCANCODE_KP_COMMA = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_COMMA); pub const SDL_SCANCODE_KP_EQUALSAS400 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_EQUALSAS400); pub const SDL_SCANCODE_INTERNATIONAL1 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_INTERNATIONAL1); pub const SDL_SCANCODE_INTERNATIONAL2 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_INTERNATIONAL2); pub const SDL_SCANCODE_INTERNATIONAL3 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_INTERNATIONAL3); pub const SDL_SCANCODE_INTERNATIONAL4 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_INTERNATIONAL4); pub const SDL_SCANCODE_INTERNATIONAL5 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_INTERNATIONAL5); pub const SDL_SCANCODE_INTERNATIONAL6 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_INTERNATIONAL6); pub const SDL_SCANCODE_INTERNATIONAL7 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_INTERNATIONAL7); pub const SDL_SCANCODE_INTERNATIONAL8 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_INTERNATIONAL8); pub const SDL_SCANCODE_INTERNATIONAL9 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_INTERNATIONAL9); pub const SDL_SCANCODE_LANG1 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_LANG1); pub const SDL_SCANCODE_LANG2 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_LANG2); pub const SDL_SCANCODE_LANG3 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_LANG3); pub const SDL_SCANCODE_LANG4 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_LANG4); pub const SDL_SCANCODE_LANG5 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_LANG5); pub const SDL_SCANCODE_LANG6 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_LANG6); pub const SDL_SCANCODE_LANG7 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_LANG7); pub const SDL_SCANCODE_LANG8 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_LANG8); pub const SDL_SCANCODE_LANG9 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_LANG9); pub const SDL_SCANCODE_ALTERASE = @enumToInt(enum_unnamed_50.SDL_SCANCODE_ALTERASE); pub const SDL_SCANCODE_SYSREQ = @enumToInt(enum_unnamed_50.SDL_SCANCODE_SYSREQ); pub const SDL_SCANCODE_CANCEL = @enumToInt(enum_unnamed_50.SDL_SCANCODE_CANCEL); pub const SDL_SCANCODE_CLEAR = @enumToInt(enum_unnamed_50.SDL_SCANCODE_CLEAR); pub const SDL_SCANCODE_PRIOR = @enumToInt(enum_unnamed_50.SDL_SCANCODE_PRIOR); pub const SDL_SCANCODE_RETURN2 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_RETURN2); pub const SDL_SCANCODE_SEPARATOR = @enumToInt(enum_unnamed_50.SDL_SCANCODE_SEPARATOR); pub const SDL_SCANCODE_OUT = @enumToInt(enum_unnamed_50.SDL_SCANCODE_OUT); pub const SDL_SCANCODE_OPER = @enumToInt(enum_unnamed_50.SDL_SCANCODE_OPER); pub const SDL_SCANCODE_CLEARAGAIN = @enumToInt(enum_unnamed_50.SDL_SCANCODE_CLEARAGAIN); pub const SDL_SCANCODE_CRSEL = @enumToInt(enum_unnamed_50.SDL_SCANCODE_CRSEL); pub const SDL_SCANCODE_EXSEL = @enumToInt(enum_unnamed_50.SDL_SCANCODE_EXSEL); pub const SDL_SCANCODE_KP_00 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_00); pub const SDL_SCANCODE_KP_000 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_000); pub const SDL_SCANCODE_THOUSANDSSEPARATOR = @enumToInt(enum_unnamed_50.SDL_SCANCODE_THOUSANDSSEPARATOR); pub const SDL_SCANCODE_DECIMALSEPARATOR = @enumToInt(enum_unnamed_50.SDL_SCANCODE_DECIMALSEPARATOR); pub const SDL_SCANCODE_CURRENCYUNIT = @enumToInt(enum_unnamed_50.SDL_SCANCODE_CURRENCYUNIT); pub const SDL_SCANCODE_CURRENCYSUBUNIT = @enumToInt(enum_unnamed_50.SDL_SCANCODE_CURRENCYSUBUNIT); pub const SDL_SCANCODE_KP_LEFTPAREN = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_LEFTPAREN); pub const SDL_SCANCODE_KP_RIGHTPAREN = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_RIGHTPAREN); pub const SDL_SCANCODE_KP_LEFTBRACE = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_LEFTBRACE); pub const SDL_SCANCODE_KP_RIGHTBRACE = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_RIGHTBRACE); pub const SDL_SCANCODE_KP_TAB = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_TAB); pub const SDL_SCANCODE_KP_BACKSPACE = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_BACKSPACE); pub const SDL_SCANCODE_KP_A = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_A); pub const SDL_SCANCODE_KP_B = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_B); pub const SDL_SCANCODE_KP_C = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_C); pub const SDL_SCANCODE_KP_D = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_D); pub const SDL_SCANCODE_KP_E = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_E); pub const SDL_SCANCODE_KP_F = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_F); pub const SDL_SCANCODE_KP_XOR = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_XOR); pub const SDL_SCANCODE_KP_POWER = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_POWER); pub const SDL_SCANCODE_KP_PERCENT = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_PERCENT); pub const SDL_SCANCODE_KP_LESS = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_LESS); pub const SDL_SCANCODE_KP_GREATER = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_GREATER); pub const SDL_SCANCODE_KP_AMPERSAND = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_AMPERSAND); pub const SDL_SCANCODE_KP_DBLAMPERSAND = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_DBLAMPERSAND); pub const SDL_SCANCODE_KP_VERTICALBAR = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_VERTICALBAR); pub const SDL_SCANCODE_KP_DBLVERTICALBAR = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_DBLVERTICALBAR); pub const SDL_SCANCODE_KP_COLON = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_COLON); pub const SDL_SCANCODE_KP_HASH = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_HASH); pub const SDL_SCANCODE_KP_SPACE = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_SPACE); pub const SDL_SCANCODE_KP_AT = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_AT); pub const SDL_SCANCODE_KP_EXCLAM = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_EXCLAM); pub const SDL_SCANCODE_KP_MEMSTORE = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_MEMSTORE); pub const SDL_SCANCODE_KP_MEMRECALL = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_MEMRECALL); pub const SDL_SCANCODE_KP_MEMCLEAR = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_MEMCLEAR); pub const SDL_SCANCODE_KP_MEMADD = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_MEMADD); pub const SDL_SCANCODE_KP_MEMSUBTRACT = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_MEMSUBTRACT); pub const SDL_SCANCODE_KP_MEMMULTIPLY = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_MEMMULTIPLY); pub const SDL_SCANCODE_KP_MEMDIVIDE = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_MEMDIVIDE); pub const SDL_SCANCODE_KP_PLUSMINUS = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_PLUSMINUS); pub const SDL_SCANCODE_KP_CLEAR = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_CLEAR); pub const SDL_SCANCODE_KP_CLEARENTRY = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_CLEARENTRY); pub const SDL_SCANCODE_KP_BINARY = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_BINARY); pub const SDL_SCANCODE_KP_OCTAL = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_OCTAL); pub const SDL_SCANCODE_KP_DECIMAL = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_DECIMAL); pub const SDL_SCANCODE_KP_HEXADECIMAL = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KP_HEXADECIMAL); pub const SDL_SCANCODE_LCTRL = @enumToInt(enum_unnamed_50.SDL_SCANCODE_LCTRL); pub const SDL_SCANCODE_LSHIFT = @enumToInt(enum_unnamed_50.SDL_SCANCODE_LSHIFT); pub const SDL_SCANCODE_LALT = @enumToInt(enum_unnamed_50.SDL_SCANCODE_LALT); pub const SDL_SCANCODE_LGUI = @enumToInt(enum_unnamed_50.SDL_SCANCODE_LGUI); pub const SDL_SCANCODE_RCTRL = @enumToInt(enum_unnamed_50.SDL_SCANCODE_RCTRL); pub const SDL_SCANCODE_RSHIFT = @enumToInt(enum_unnamed_50.SDL_SCANCODE_RSHIFT); pub const SDL_SCANCODE_RALT = @enumToInt(enum_unnamed_50.SDL_SCANCODE_RALT); pub const SDL_SCANCODE_RGUI = @enumToInt(enum_unnamed_50.SDL_SCANCODE_RGUI); pub const SDL_SCANCODE_MODE = @enumToInt(enum_unnamed_50.SDL_SCANCODE_MODE); pub const SDL_SCANCODE_AUDIONEXT = @enumToInt(enum_unnamed_50.SDL_SCANCODE_AUDIONEXT); pub const SDL_SCANCODE_AUDIOPREV = @enumToInt(enum_unnamed_50.SDL_SCANCODE_AUDIOPREV); pub const SDL_SCANCODE_AUDIOSTOP = @enumToInt(enum_unnamed_50.SDL_SCANCODE_AUDIOSTOP); pub const SDL_SCANCODE_AUDIOPLAY = @enumToInt(enum_unnamed_50.SDL_SCANCODE_AUDIOPLAY); pub const SDL_SCANCODE_AUDIOMUTE = @enumToInt(enum_unnamed_50.SDL_SCANCODE_AUDIOMUTE); pub const SDL_SCANCODE_MEDIASELECT = @enumToInt(enum_unnamed_50.SDL_SCANCODE_MEDIASELECT); pub const SDL_SCANCODE_WWW = @enumToInt(enum_unnamed_50.SDL_SCANCODE_WWW); pub const SDL_SCANCODE_MAIL = @enumToInt(enum_unnamed_50.SDL_SCANCODE_MAIL); pub const SDL_SCANCODE_CALCULATOR = @enumToInt(enum_unnamed_50.SDL_SCANCODE_CALCULATOR); pub const SDL_SCANCODE_COMPUTER = @enumToInt(enum_unnamed_50.SDL_SCANCODE_COMPUTER); pub const SDL_SCANCODE_AC_SEARCH = @enumToInt(enum_unnamed_50.SDL_SCANCODE_AC_SEARCH); pub const SDL_SCANCODE_AC_HOME = @enumToInt(enum_unnamed_50.SDL_SCANCODE_AC_HOME); pub const SDL_SCANCODE_AC_BACK = @enumToInt(enum_unnamed_50.SDL_SCANCODE_AC_BACK); pub const SDL_SCANCODE_AC_FORWARD = @enumToInt(enum_unnamed_50.SDL_SCANCODE_AC_FORWARD); pub const SDL_SCANCODE_AC_STOP = @enumToInt(enum_unnamed_50.SDL_SCANCODE_AC_STOP); pub const SDL_SCANCODE_AC_REFRESH = @enumToInt(enum_unnamed_50.SDL_SCANCODE_AC_REFRESH); pub const SDL_SCANCODE_AC_BOOKMARKS = @enumToInt(enum_unnamed_50.SDL_SCANCODE_AC_BOOKMARKS); pub const SDL_SCANCODE_BRIGHTNESSDOWN = @enumToInt(enum_unnamed_50.SDL_SCANCODE_BRIGHTNESSDOWN); pub const SDL_SCANCODE_BRIGHTNESSUP = @enumToInt(enum_unnamed_50.SDL_SCANCODE_BRIGHTNESSUP); pub const SDL_SCANCODE_DISPLAYSWITCH = @enumToInt(enum_unnamed_50.SDL_SCANCODE_DISPLAYSWITCH); pub const SDL_SCANCODE_KBDILLUMTOGGLE = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KBDILLUMTOGGLE); pub const SDL_SCANCODE_KBDILLUMDOWN = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KBDILLUMDOWN); pub const SDL_SCANCODE_KBDILLUMUP = @enumToInt(enum_unnamed_50.SDL_SCANCODE_KBDILLUMUP); pub const SDL_SCANCODE_EJECT = @enumToInt(enum_unnamed_50.SDL_SCANCODE_EJECT); pub const SDL_SCANCODE_SLEEP = @enumToInt(enum_unnamed_50.SDL_SCANCODE_SLEEP); pub const SDL_SCANCODE_APP1 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_APP1); pub const SDL_SCANCODE_APP2 = @enumToInt(enum_unnamed_50.SDL_SCANCODE_APP2); pub const SDL_SCANCODE_AUDIOREWIND = @enumToInt(enum_unnamed_50.SDL_SCANCODE_AUDIOREWIND); pub const SDL_SCANCODE_AUDIOFASTFORWARD = @enumToInt(enum_unnamed_50.SDL_SCANCODE_AUDIOFASTFORWARD); pub const SDL_NUM_SCANCODES = @enumToInt(enum_unnamed_50.SDL_NUM_SCANCODES); const enum_unnamed_50 = enum(c_int) { SDL_SCANCODE_UNKNOWN = 0, SDL_SCANCODE_A = 4, SDL_SCANCODE_B = 5, SDL_SCANCODE_C = 6, SDL_SCANCODE_D = 7, SDL_SCANCODE_E = 8, SDL_SCANCODE_F = 9, SDL_SCANCODE_G = 10, SDL_SCANCODE_H = 11, SDL_SCANCODE_I = 12, SDL_SCANCODE_J = 13, SDL_SCANCODE_K = 14, SDL_SCANCODE_L = 15, SDL_SCANCODE_M = 16, SDL_SCANCODE_N = 17, SDL_SCANCODE_O = 18, SDL_SCANCODE_P = 19, SDL_SCANCODE_Q = 20, SDL_SCANCODE_R = 21, SDL_SCANCODE_S = 22, SDL_SCANCODE_T = 23, SDL_SCANCODE_U = 24, SDL_SCANCODE_V = 25, SDL_SCANCODE_W = 26, SDL_SCANCODE_X = 27, SDL_SCANCODE_Y = 28, SDL_SCANCODE_Z = 29, SDL_SCANCODE_1 = 30, SDL_SCANCODE_2 = 31, SDL_SCANCODE_3 = 32, SDL_SCANCODE_4 = 33, SDL_SCANCODE_5 = 34, SDL_SCANCODE_6 = 35, SDL_SCANCODE_7 = 36, SDL_SCANCODE_8 = 37, SDL_SCANCODE_9 = 38, SDL_SCANCODE_0 = 39, SDL_SCANCODE_RETURN = 40, SDL_SCANCODE_ESCAPE = 41, SDL_SCANCODE_BACKSPACE = 42, SDL_SCANCODE_TAB = 43, SDL_SCANCODE_SPACE = 44, SDL_SCANCODE_MINUS = 45, SDL_SCANCODE_EQUALS = 46, SDL_SCANCODE_LEFTBRACKET = 47, SDL_SCANCODE_RIGHTBRACKET = 48, SDL_SCANCODE_BACKSLASH = 49, SDL_SCANCODE_NONUSHASH = 50, SDL_SCANCODE_SEMICOLON = 51, SDL_SCANCODE_APOSTROPHE = 52, SDL_SCANCODE_GRAVE = 53, SDL_SCANCODE_COMMA = 54, SDL_SCANCODE_PERIOD = 55, SDL_SCANCODE_SLASH = 56, SDL_SCANCODE_CAPSLOCK = 57, SDL_SCANCODE_F1 = 58, SDL_SCANCODE_F2 = 59, SDL_SCANCODE_F3 = 60, SDL_SCANCODE_F4 = 61, SDL_SCANCODE_F5 = 62, SDL_SCANCODE_F6 = 63, SDL_SCANCODE_F7 = 64, SDL_SCANCODE_F8 = 65, SDL_SCANCODE_F9 = 66, SDL_SCANCODE_F10 = 67, SDL_SCANCODE_F11 = 68, SDL_SCANCODE_F12 = 69, SDL_SCANCODE_PRINTSCREEN = 70, SDL_SCANCODE_SCROLLLOCK = 71, SDL_SCANCODE_PAUSE = 72, SDL_SCANCODE_INSERT = 73, SDL_SCANCODE_HOME = 74, SDL_SCANCODE_PAGEUP = 75, SDL_SCANCODE_DELETE = 76, SDL_SCANCODE_END = 77, SDL_SCANCODE_PAGEDOWN = 78, SDL_SCANCODE_RIGHT = 79, SDL_SCANCODE_LEFT = 80, SDL_SCANCODE_DOWN = 81, SDL_SCANCODE_UP = 82, SDL_SCANCODE_NUMLOCKCLEAR = 83, SDL_SCANCODE_KP_DIVIDE = 84, SDL_SCANCODE_KP_MULTIPLY = 85, SDL_SCANCODE_KP_MINUS = 86, SDL_SCANCODE_KP_PLUS = 87, SDL_SCANCODE_KP_ENTER = 88, SDL_SCANCODE_KP_1 = 89, SDL_SCANCODE_KP_2 = 90, SDL_SCANCODE_KP_3 = 91, SDL_SCANCODE_KP_4 = 92, SDL_SCANCODE_KP_5 = 93, SDL_SCANCODE_KP_6 = 94, SDL_SCANCODE_KP_7 = 95, SDL_SCANCODE_KP_8 = 96, SDL_SCANCODE_KP_9 = 97, SDL_SCANCODE_KP_0 = 98, SDL_SCANCODE_KP_PERIOD = 99, SDL_SCANCODE_NONUSBACKSLASH = 100, SDL_SCANCODE_APPLICATION = 101, SDL_SCANCODE_POWER = 102, SDL_SCANCODE_KP_EQUALS = 103, SDL_SCANCODE_F13 = 104, SDL_SCANCODE_F14 = 105, SDL_SCANCODE_F15 = 106, SDL_SCANCODE_F16 = 107, SDL_SCANCODE_F17 = 108, SDL_SCANCODE_F18 = 109, SDL_SCANCODE_F19 = 110, SDL_SCANCODE_F20 = 111, SDL_SCANCODE_F21 = 112, SDL_SCANCODE_F22 = 113, SDL_SCANCODE_F23 = 114, SDL_SCANCODE_F24 = 115, SDL_SCANCODE_EXECUTE = 116, SDL_SCANCODE_HELP = 117, SDL_SCANCODE_MENU = 118, SDL_SCANCODE_SELECT = 119, SDL_SCANCODE_STOP = 120, SDL_SCANCODE_AGAIN = 121, SDL_SCANCODE_UNDO = 122, SDL_SCANCODE_CUT = 123, SDL_SCANCODE_COPY = 124, SDL_SCANCODE_PASTE = 125, SDL_SCANCODE_FIND = 126, SDL_SCANCODE_MUTE = 127, SDL_SCANCODE_VOLUMEUP = 128, SDL_SCANCODE_VOLUMEDOWN = 129, SDL_SCANCODE_KP_COMMA = 133, SDL_SCANCODE_KP_EQUALSAS400 = 134, SDL_SCANCODE_INTERNATIONAL1 = 135, SDL_SCANCODE_INTERNATIONAL2 = 136, SDL_SCANCODE_INTERNATIONAL3 = 137, SDL_SCANCODE_INTERNATIONAL4 = 138, SDL_SCANCODE_INTERNATIONAL5 = 139, SDL_SCANCODE_INTERNATIONAL6 = 140, SDL_SCANCODE_INTERNATIONAL7 = 141, SDL_SCANCODE_INTERNATIONAL8 = 142, SDL_SCANCODE_INTERNATIONAL9 = 143, SDL_SCANCODE_LANG1 = 144, SDL_SCANCODE_LANG2 = 145, SDL_SCANCODE_LANG3 = 146, SDL_SCANCODE_LANG4 = 147, SDL_SCANCODE_LANG5 = 148, SDL_SCANCODE_LANG6 = 149, SDL_SCANCODE_LANG7 = 150, SDL_SCANCODE_LANG8 = 151, SDL_SCANCODE_LANG9 = 152, SDL_SCANCODE_ALTERASE = 153, SDL_SCANCODE_SYSREQ = 154, SDL_SCANCODE_CANCEL = 155, SDL_SCANCODE_CLEAR = 156, SDL_SCANCODE_PRIOR = 157, SDL_SCANCODE_RETURN2 = 158, SDL_SCANCODE_SEPARATOR = 159, SDL_SCANCODE_OUT = 160, SDL_SCANCODE_OPER = 161, SDL_SCANCODE_CLEARAGAIN = 162, SDL_SCANCODE_CRSEL = 163, SDL_SCANCODE_EXSEL = 164, SDL_SCANCODE_KP_00 = 176, SDL_SCANCODE_KP_000 = 177, SDL_SCANCODE_THOUSANDSSEPARATOR = 178, SDL_SCANCODE_DECIMALSEPARATOR = 179, SDL_SCANCODE_CURRENCYUNIT = 180, SDL_SCANCODE_CURRENCYSUBUNIT = 181, SDL_SCANCODE_KP_LEFTPAREN = 182, SDL_SCANCODE_KP_RIGHTPAREN = 183, SDL_SCANCODE_KP_LEFTBRACE = 184, SDL_SCANCODE_KP_RIGHTBRACE = 185, SDL_SCANCODE_KP_TAB = 186, SDL_SCANCODE_KP_BACKSPACE = 187, SDL_SCANCODE_KP_A = 188, SDL_SCANCODE_KP_B = 189, SDL_SCANCODE_KP_C = 190, SDL_SCANCODE_KP_D = 191, SDL_SCANCODE_KP_E = 192, SDL_SCANCODE_KP_F = 193, SDL_SCANCODE_KP_XOR = 194, SDL_SCANCODE_KP_POWER = 195, SDL_SCANCODE_KP_PERCENT = 196, SDL_SCANCODE_KP_LESS = 197, SDL_SCANCODE_KP_GREATER = 198, SDL_SCANCODE_KP_AMPERSAND = 199, SDL_SCANCODE_KP_DBLAMPERSAND = 200, SDL_SCANCODE_KP_VERTICALBAR = 201, SDL_SCANCODE_KP_DBLVERTICALBAR = 202, SDL_SCANCODE_KP_COLON = 203, SDL_SCANCODE_KP_HASH = 204, SDL_SCANCODE_KP_SPACE = 205, SDL_SCANCODE_KP_AT = 206, SDL_SCANCODE_KP_EXCLAM = 207, SDL_SCANCODE_KP_MEMSTORE = 208, SDL_SCANCODE_KP_MEMRECALL = 209, SDL_SCANCODE_KP_MEMCLEAR = 210, SDL_SCANCODE_KP_MEMADD = 211, SDL_SCANCODE_KP_MEMSUBTRACT = 212, SDL_SCANCODE_KP_MEMMULTIPLY = 213, SDL_SCANCODE_KP_MEMDIVIDE = 214, SDL_SCANCODE_KP_PLUSMINUS = 215, SDL_SCANCODE_KP_CLEAR = 216, SDL_SCANCODE_KP_CLEARENTRY = 217, SDL_SCANCODE_KP_BINARY = 218, SDL_SCANCODE_KP_OCTAL = 219, SDL_SCANCODE_KP_DECIMAL = 220, SDL_SCANCODE_KP_HEXADECIMAL = 221, SDL_SCANCODE_LCTRL = 224, SDL_SCANCODE_LSHIFT = 225, SDL_SCANCODE_LALT = 226, SDL_SCANCODE_LGUI = 227, SDL_SCANCODE_RCTRL = 228, SDL_SCANCODE_RSHIFT = 229, SDL_SCANCODE_RALT = 230, SDL_SCANCODE_RGUI = 231, SDL_SCANCODE_MODE = 257, SDL_SCANCODE_AUDIONEXT = 258, SDL_SCANCODE_AUDIOPREV = 259, SDL_SCANCODE_AUDIOSTOP = 260, SDL_SCANCODE_AUDIOPLAY = 261, SDL_SCANCODE_AUDIOMUTE = 262, SDL_SCANCODE_MEDIASELECT = 263, SDL_SCANCODE_WWW = 264, SDL_SCANCODE_MAIL = 265, SDL_SCANCODE_CALCULATOR = 266, SDL_SCANCODE_COMPUTER = 267, SDL_SCANCODE_AC_SEARCH = 268, SDL_SCANCODE_AC_HOME = 269, SDL_SCANCODE_AC_BACK = 270, SDL_SCANCODE_AC_FORWARD = 271, SDL_SCANCODE_AC_STOP = 272, SDL_SCANCODE_AC_REFRESH = 273, SDL_SCANCODE_AC_BOOKMARKS = 274, SDL_SCANCODE_BRIGHTNESSDOWN = 275, SDL_SCANCODE_BRIGHTNESSUP = 276, SDL_SCANCODE_DISPLAYSWITCH = 277, SDL_SCANCODE_KBDILLUMTOGGLE = 278, SDL_SCANCODE_KBDILLUMDOWN = 279, SDL_SCANCODE_KBDILLUMUP = 280, SDL_SCANCODE_EJECT = 281, SDL_SCANCODE_SLEEP = 282, SDL_SCANCODE_APP1 = 283, SDL_SCANCODE_APP2 = 284, SDL_SCANCODE_AUDIOREWIND = 285, SDL_SCANCODE_AUDIOFASTFORWARD = 286, SDL_NUM_SCANCODES = 512, _, }; pub const SDL_Scancode = enum_unnamed_50; pub const SDL_Keycode = Sint32; pub const SDLK_UNKNOWN = @enumToInt(enum_unnamed_51.SDLK_UNKNOWN); pub const SDLK_RETURN = @enumToInt(enum_unnamed_51.SDLK_RETURN); pub const SDLK_ESCAPE = @enumToInt(enum_unnamed_51.SDLK_ESCAPE); pub const SDLK_BACKSPACE = @enumToInt(enum_unnamed_51.SDLK_BACKSPACE); pub const SDLK_TAB = @enumToInt(enum_unnamed_51.SDLK_TAB); pub const SDLK_SPACE = @enumToInt(enum_unnamed_51.SDLK_SPACE); pub const SDLK_EXCLAIM = @enumToInt(enum_unnamed_51.SDLK_EXCLAIM); pub const SDLK_QUOTEDBL = @enumToInt(enum_unnamed_51.SDLK_QUOTEDBL); pub const SDLK_HASH = @enumToInt(enum_unnamed_51.SDLK_HASH); pub const SDLK_PERCENT = @enumToInt(enum_unnamed_51.SDLK_PERCENT); pub const SDLK_DOLLAR = @enumToInt(enum_unnamed_51.SDLK_DOLLAR); pub const SDLK_AMPERSAND = @enumToInt(enum_unnamed_51.SDLK_AMPERSAND); pub const SDLK_QUOTE = @enumToInt(enum_unnamed_51.SDLK_QUOTE); pub const SDLK_LEFTPAREN = @enumToInt(enum_unnamed_51.SDLK_LEFTPAREN); pub const SDLK_RIGHTPAREN = @enumToInt(enum_unnamed_51.SDLK_RIGHTPAREN); pub const SDLK_ASTERISK = @enumToInt(enum_unnamed_51.SDLK_ASTERISK); pub const SDLK_PLUS = @enumToInt(enum_unnamed_51.SDLK_PLUS); pub const SDLK_COMMA = @enumToInt(enum_unnamed_51.SDLK_COMMA); pub const SDLK_MINUS = @enumToInt(enum_unnamed_51.SDLK_MINUS); pub const SDLK_PERIOD = @enumToInt(enum_unnamed_51.SDLK_PERIOD); pub const SDLK_SLASH = @enumToInt(enum_unnamed_51.SDLK_SLASH); pub const SDLK_0 = @enumToInt(enum_unnamed_51.SDLK_0); pub const SDLK_1 = @enumToInt(enum_unnamed_51.SDLK_1); pub const SDLK_2 = @enumToInt(enum_unnamed_51.SDLK_2); pub const SDLK_3 = @enumToInt(enum_unnamed_51.SDLK_3); pub const SDLK_4 = @enumToInt(enum_unnamed_51.SDLK_4); pub const SDLK_5 = @enumToInt(enum_unnamed_51.SDLK_5); pub const SDLK_6 = @enumToInt(enum_unnamed_51.SDLK_6); pub const SDLK_7 = @enumToInt(enum_unnamed_51.SDLK_7); pub const SDLK_8 = @enumToInt(enum_unnamed_51.SDLK_8); pub const SDLK_9 = @enumToInt(enum_unnamed_51.SDLK_9); pub const SDLK_COLON = @enumToInt(enum_unnamed_51.SDLK_COLON); pub const SDLK_SEMICOLON = @enumToInt(enum_unnamed_51.SDLK_SEMICOLON); pub const SDLK_LESS = @enumToInt(enum_unnamed_51.SDLK_LESS); pub const SDLK_EQUALS = @enumToInt(enum_unnamed_51.SDLK_EQUALS); pub const SDLK_GREATER = @enumToInt(enum_unnamed_51.SDLK_GREATER); pub const SDLK_QUESTION = @enumToInt(enum_unnamed_51.SDLK_QUESTION); pub const SDLK_AT = @enumToInt(enum_unnamed_51.SDLK_AT); pub const SDLK_LEFTBRACKET = @enumToInt(enum_unnamed_51.SDLK_LEFTBRACKET); pub const SDLK_BACKSLASH = @enumToInt(enum_unnamed_51.SDLK_BACKSLASH); pub const SDLK_RIGHTBRACKET = @enumToInt(enum_unnamed_51.SDLK_RIGHTBRACKET); pub const SDLK_CARET = @enumToInt(enum_unnamed_51.SDLK_CARET); pub const SDLK_UNDERSCORE = @enumToInt(enum_unnamed_51.SDLK_UNDERSCORE); pub const SDLK_BACKQUOTE = @enumToInt(enum_unnamed_51.SDLK_BACKQUOTE); pub const SDLK_a = @enumToInt(enum_unnamed_51.SDLK_a); pub const SDLK_b = @enumToInt(enum_unnamed_51.SDLK_b); pub const SDLK_c = @enumToInt(enum_unnamed_51.SDLK_c); pub const SDLK_d = @enumToInt(enum_unnamed_51.SDLK_d); pub const SDLK_e = @enumToInt(enum_unnamed_51.SDLK_e); pub const SDLK_f = @enumToInt(enum_unnamed_51.SDLK_f); pub const SDLK_g = @enumToInt(enum_unnamed_51.SDLK_g); pub const SDLK_h = @enumToInt(enum_unnamed_51.SDLK_h); pub const SDLK_i = @enumToInt(enum_unnamed_51.SDLK_i); pub const SDLK_j = @enumToInt(enum_unnamed_51.SDLK_j); pub const SDLK_k = @enumToInt(enum_unnamed_51.SDLK_k); pub const SDLK_l = @enumToInt(enum_unnamed_51.SDLK_l); pub const SDLK_m = @enumToInt(enum_unnamed_51.SDLK_m); pub const SDLK_n = @enumToInt(enum_unnamed_51.SDLK_n); pub const SDLK_o = @enumToInt(enum_unnamed_51.SDLK_o); pub const SDLK_p = @enumToInt(enum_unnamed_51.SDLK_p); pub const SDLK_q = @enumToInt(enum_unnamed_51.SDLK_q); pub const SDLK_r = @enumToInt(enum_unnamed_51.SDLK_r); pub const SDLK_s = @enumToInt(enum_unnamed_51.SDLK_s); pub const SDLK_t = @enumToInt(enum_unnamed_51.SDLK_t); pub const SDLK_u = @enumToInt(enum_unnamed_51.SDLK_u); pub const SDLK_v = @enumToInt(enum_unnamed_51.SDLK_v); pub const SDLK_w = @enumToInt(enum_unnamed_51.SDLK_w); pub const SDLK_x = @enumToInt(enum_unnamed_51.SDLK_x); pub const SDLK_y = @enumToInt(enum_unnamed_51.SDLK_y); pub const SDLK_z = @enumToInt(enum_unnamed_51.SDLK_z); pub const SDLK_CAPSLOCK = @enumToInt(enum_unnamed_51.SDLK_CAPSLOCK); pub const SDLK_F1 = @enumToInt(enum_unnamed_51.SDLK_F1); pub const SDLK_F2 = @enumToInt(enum_unnamed_51.SDLK_F2); pub const SDLK_F3 = @enumToInt(enum_unnamed_51.SDLK_F3); pub const SDLK_F4 = @enumToInt(enum_unnamed_51.SDLK_F4); pub const SDLK_F5 = @enumToInt(enum_unnamed_51.SDLK_F5); pub const SDLK_F6 = @enumToInt(enum_unnamed_51.SDLK_F6); pub const SDLK_F7 = @enumToInt(enum_unnamed_51.SDLK_F7); pub const SDLK_F8 = @enumToInt(enum_unnamed_51.SDLK_F8); pub const SDLK_F9 = @enumToInt(enum_unnamed_51.SDLK_F9); pub const SDLK_F10 = @enumToInt(enum_unnamed_51.SDLK_F10); pub const SDLK_F11 = @enumToInt(enum_unnamed_51.SDLK_F11); pub const SDLK_F12 = @enumToInt(enum_unnamed_51.SDLK_F12); pub const SDLK_PRINTSCREEN = @enumToInt(enum_unnamed_51.SDLK_PRINTSCREEN); pub const SDLK_SCROLLLOCK = @enumToInt(enum_unnamed_51.SDLK_SCROLLLOCK); pub const SDLK_PAUSE = @enumToInt(enum_unnamed_51.SDLK_PAUSE); pub const SDLK_INSERT = @enumToInt(enum_unnamed_51.SDLK_INSERT); pub const SDLK_HOME = @enumToInt(enum_unnamed_51.SDLK_HOME); pub const SDLK_PAGEUP = @enumToInt(enum_unnamed_51.SDLK_PAGEUP); pub const SDLK_DELETE = @enumToInt(enum_unnamed_51.SDLK_DELETE); pub const SDLK_END = @enumToInt(enum_unnamed_51.SDLK_END); pub const SDLK_PAGEDOWN = @enumToInt(enum_unnamed_51.SDLK_PAGEDOWN); pub const SDLK_RIGHT = @enumToInt(enum_unnamed_51.SDLK_RIGHT); pub const SDLK_LEFT = @enumToInt(enum_unnamed_51.SDLK_LEFT); pub const SDLK_DOWN = @enumToInt(enum_unnamed_51.SDLK_DOWN); pub const SDLK_UP = @enumToInt(enum_unnamed_51.SDLK_UP); pub const SDLK_NUMLOCKCLEAR = @enumToInt(enum_unnamed_51.SDLK_NUMLOCKCLEAR); pub const SDLK_KP_DIVIDE = @enumToInt(enum_unnamed_51.SDLK_KP_DIVIDE); pub const SDLK_KP_MULTIPLY = @enumToInt(enum_unnamed_51.SDLK_KP_MULTIPLY); pub const SDLK_KP_MINUS = @enumToInt(enum_unnamed_51.SDLK_KP_MINUS); pub const SDLK_KP_PLUS = @enumToInt(enum_unnamed_51.SDLK_KP_PLUS); pub const SDLK_KP_ENTER = @enumToInt(enum_unnamed_51.SDLK_KP_ENTER); pub const SDLK_KP_1 = @enumToInt(enum_unnamed_51.SDLK_KP_1); pub const SDLK_KP_2 = @enumToInt(enum_unnamed_51.SDLK_KP_2); pub const SDLK_KP_3 = @enumToInt(enum_unnamed_51.SDLK_KP_3); pub const SDLK_KP_4 = @enumToInt(enum_unnamed_51.SDLK_KP_4); pub const SDLK_KP_5 = @enumToInt(enum_unnamed_51.SDLK_KP_5); pub const SDLK_KP_6 = @enumToInt(enum_unnamed_51.SDLK_KP_6); pub const SDLK_KP_7 = @enumToInt(enum_unnamed_51.SDLK_KP_7); pub const SDLK_KP_8 = @enumToInt(enum_unnamed_51.SDLK_KP_8); pub const SDLK_KP_9 = @enumToInt(enum_unnamed_51.SDLK_KP_9); pub const SDLK_KP_0 = @enumToInt(enum_unnamed_51.SDLK_KP_0); pub const SDLK_KP_PERIOD = @enumToInt(enum_unnamed_51.SDLK_KP_PERIOD); pub const SDLK_APPLICATION = @enumToInt(enum_unnamed_51.SDLK_APPLICATION); pub const SDLK_POWER = @enumToInt(enum_unnamed_51.SDLK_POWER); pub const SDLK_KP_EQUALS = @enumToInt(enum_unnamed_51.SDLK_KP_EQUALS); pub const SDLK_F13 = @enumToInt(enum_unnamed_51.SDLK_F13); pub const SDLK_F14 = @enumToInt(enum_unnamed_51.SDLK_F14); pub const SDLK_F15 = @enumToInt(enum_unnamed_51.SDLK_F15); pub const SDLK_F16 = @enumToInt(enum_unnamed_51.SDLK_F16); pub const SDLK_F17 = @enumToInt(enum_unnamed_51.SDLK_F17); pub const SDLK_F18 = @enumToInt(enum_unnamed_51.SDLK_F18); pub const SDLK_F19 = @enumToInt(enum_unnamed_51.SDLK_F19); pub const SDLK_F20 = @enumToInt(enum_unnamed_51.SDLK_F20); pub const SDLK_F21 = @enumToInt(enum_unnamed_51.SDLK_F21); pub const SDLK_F22 = @enumToInt(enum_unnamed_51.SDLK_F22); pub const SDLK_F23 = @enumToInt(enum_unnamed_51.SDLK_F23); pub const SDLK_F24 = @enumToInt(enum_unnamed_51.SDLK_F24); pub const SDLK_EXECUTE = @enumToInt(enum_unnamed_51.SDLK_EXECUTE); pub const SDLK_HELP = @enumToInt(enum_unnamed_51.SDLK_HELP); pub const SDLK_MENU = @enumToInt(enum_unnamed_51.SDLK_MENU); pub const SDLK_SELECT = @enumToInt(enum_unnamed_51.SDLK_SELECT); pub const SDLK_STOP = @enumToInt(enum_unnamed_51.SDLK_STOP); pub const SDLK_AGAIN = @enumToInt(enum_unnamed_51.SDLK_AGAIN); pub const SDLK_UNDO = @enumToInt(enum_unnamed_51.SDLK_UNDO); pub const SDLK_CUT = @enumToInt(enum_unnamed_51.SDLK_CUT); pub const SDLK_COPY = @enumToInt(enum_unnamed_51.SDLK_COPY); pub const SDLK_PASTE = @enumToInt(enum_unnamed_51.SDLK_PASTE); pub const SDLK_FIND = @enumToInt(enum_unnamed_51.SDLK_FIND); pub const SDLK_MUTE = @enumToInt(enum_unnamed_51.SDLK_MUTE); pub const SDLK_VOLUMEUP = @enumToInt(enum_unnamed_51.SDLK_VOLUMEUP); pub const SDLK_VOLUMEDOWN = @enumToInt(enum_unnamed_51.SDLK_VOLUMEDOWN); pub const SDLK_KP_COMMA = @enumToInt(enum_unnamed_51.SDLK_KP_COMMA); pub const SDLK_KP_EQUALSAS400 = @enumToInt(enum_unnamed_51.SDLK_KP_EQUALSAS400); pub const SDLK_ALTERASE = @enumToInt(enum_unnamed_51.SDLK_ALTERASE); pub const SDLK_SYSREQ = @enumToInt(enum_unnamed_51.SDLK_SYSREQ); pub const SDLK_CANCEL = @enumToInt(enum_unnamed_51.SDLK_CANCEL); pub const SDLK_CLEAR = @enumToInt(enum_unnamed_51.SDLK_CLEAR); pub const SDLK_PRIOR = @enumToInt(enum_unnamed_51.SDLK_PRIOR); pub const SDLK_RETURN2 = @enumToInt(enum_unnamed_51.SDLK_RETURN2); pub const SDLK_SEPARATOR = @enumToInt(enum_unnamed_51.SDLK_SEPARATOR); pub const SDLK_OUT = @enumToInt(enum_unnamed_51.SDLK_OUT); pub const SDLK_OPER = @enumToInt(enum_unnamed_51.SDLK_OPER); pub const SDLK_CLEARAGAIN = @enumToInt(enum_unnamed_51.SDLK_CLEARAGAIN); pub const SDLK_CRSEL = @enumToInt(enum_unnamed_51.SDLK_CRSEL); pub const SDLK_EXSEL = @enumToInt(enum_unnamed_51.SDLK_EXSEL); pub const SDLK_KP_00 = @enumToInt(enum_unnamed_51.SDLK_KP_00); pub const SDLK_KP_000 = @enumToInt(enum_unnamed_51.SDLK_KP_000); pub const SDLK_THOUSANDSSEPARATOR = @enumToInt(enum_unnamed_51.SDLK_THOUSANDSSEPARATOR); pub const SDLK_DECIMALSEPARATOR = @enumToInt(enum_unnamed_51.SDLK_DECIMALSEPARATOR); pub const SDLK_CURRENCYUNIT = @enumToInt(enum_unnamed_51.SDLK_CURRENCYUNIT); pub const SDLK_CURRENCYSUBUNIT = @enumToInt(enum_unnamed_51.SDLK_CURRENCYSUBUNIT); pub const SDLK_KP_LEFTPAREN = @enumToInt(enum_unnamed_51.SDLK_KP_LEFTPAREN); pub const SDLK_KP_RIGHTPAREN = @enumToInt(enum_unnamed_51.SDLK_KP_RIGHTPAREN); pub const SDLK_KP_LEFTBRACE = @enumToInt(enum_unnamed_51.SDLK_KP_LEFTBRACE); pub const SDLK_KP_RIGHTBRACE = @enumToInt(enum_unnamed_51.SDLK_KP_RIGHTBRACE); pub const SDLK_KP_TAB = @enumToInt(enum_unnamed_51.SDLK_KP_TAB); pub const SDLK_KP_BACKSPACE = @enumToInt(enum_unnamed_51.SDLK_KP_BACKSPACE); pub const SDLK_KP_A = @enumToInt(enum_unnamed_51.SDLK_KP_A); pub const SDLK_KP_B = @enumToInt(enum_unnamed_51.SDLK_KP_B); pub const SDLK_KP_C = @enumToInt(enum_unnamed_51.SDLK_KP_C); pub const SDLK_KP_D = @enumToInt(enum_unnamed_51.SDLK_KP_D); pub const SDLK_KP_E = @enumToInt(enum_unnamed_51.SDLK_KP_E); pub const SDLK_KP_F = @enumToInt(enum_unnamed_51.SDLK_KP_F); pub const SDLK_KP_XOR = @enumToInt(enum_unnamed_51.SDLK_KP_XOR); pub const SDLK_KP_POWER = @enumToInt(enum_unnamed_51.SDLK_KP_POWER); pub const SDLK_KP_PERCENT = @enumToInt(enum_unnamed_51.SDLK_KP_PERCENT); pub const SDLK_KP_LESS = @enumToInt(enum_unnamed_51.SDLK_KP_LESS); pub const SDLK_KP_GREATER = @enumToInt(enum_unnamed_51.SDLK_KP_GREATER); pub const SDLK_KP_AMPERSAND = @enumToInt(enum_unnamed_51.SDLK_KP_AMPERSAND); pub const SDLK_KP_DBLAMPERSAND = @enumToInt(enum_unnamed_51.SDLK_KP_DBLAMPERSAND); pub const SDLK_KP_VERTICALBAR = @enumToInt(enum_unnamed_51.SDLK_KP_VERTICALBAR); pub const SDLK_KP_DBLVERTICALBAR = @enumToInt(enum_unnamed_51.SDLK_KP_DBLVERTICALBAR); pub const SDLK_KP_COLON = @enumToInt(enum_unnamed_51.SDLK_KP_COLON); pub const SDLK_KP_HASH = @enumToInt(enum_unnamed_51.SDLK_KP_HASH); pub const SDLK_KP_SPACE = @enumToInt(enum_unnamed_51.SDLK_KP_SPACE); pub const SDLK_KP_AT = @enumToInt(enum_unnamed_51.SDLK_KP_AT); pub const SDLK_KP_EXCLAM = @enumToInt(enum_unnamed_51.SDLK_KP_EXCLAM); pub const SDLK_KP_MEMSTORE = @enumToInt(enum_unnamed_51.SDLK_KP_MEMSTORE); pub const SDLK_KP_MEMRECALL = @enumToInt(enum_unnamed_51.SDLK_KP_MEMRECALL); pub const SDLK_KP_MEMCLEAR = @enumToInt(enum_unnamed_51.SDLK_KP_MEMCLEAR); pub const SDLK_KP_MEMADD = @enumToInt(enum_unnamed_51.SDLK_KP_MEMADD); pub const SDLK_KP_MEMSUBTRACT = @enumToInt(enum_unnamed_51.SDLK_KP_MEMSUBTRACT); pub const SDLK_KP_MEMMULTIPLY = @enumToInt(enum_unnamed_51.SDLK_KP_MEMMULTIPLY); pub const SDLK_KP_MEMDIVIDE = @enumToInt(enum_unnamed_51.SDLK_KP_MEMDIVIDE); pub const SDLK_KP_PLUSMINUS = @enumToInt(enum_unnamed_51.SDLK_KP_PLUSMINUS); pub const SDLK_KP_CLEAR = @enumToInt(enum_unnamed_51.SDLK_KP_CLEAR); pub const SDLK_KP_CLEARENTRY = @enumToInt(enum_unnamed_51.SDLK_KP_CLEARENTRY); pub const SDLK_KP_BINARY = @enumToInt(enum_unnamed_51.SDLK_KP_BINARY); pub const SDLK_KP_OCTAL = @enumToInt(enum_unnamed_51.SDLK_KP_OCTAL); pub const SDLK_KP_DECIMAL = @enumToInt(enum_unnamed_51.SDLK_KP_DECIMAL); pub const SDLK_KP_HEXADECIMAL = @enumToInt(enum_unnamed_51.SDLK_KP_HEXADECIMAL); pub const SDLK_LCTRL = @enumToInt(enum_unnamed_51.SDLK_LCTRL); pub const SDLK_LSHIFT = @enumToInt(enum_unnamed_51.SDLK_LSHIFT); pub const SDLK_LALT = @enumToInt(enum_unnamed_51.SDLK_LALT); pub const SDLK_LGUI = @enumToInt(enum_unnamed_51.SDLK_LGUI); pub const SDLK_RCTRL = @enumToInt(enum_unnamed_51.SDLK_RCTRL); pub const SDLK_RSHIFT = @enumToInt(enum_unnamed_51.SDLK_RSHIFT); pub const SDLK_RALT = @enumToInt(enum_unnamed_51.SDLK_RALT); pub const SDLK_RGUI = @enumToInt(enum_unnamed_51.SDLK_RGUI); pub const SDLK_MODE = @enumToInt(enum_unnamed_51.SDLK_MODE); pub const SDLK_AUDIONEXT = @enumToInt(enum_unnamed_51.SDLK_AUDIONEXT); pub const SDLK_AUDIOPREV = @enumToInt(enum_unnamed_51.SDLK_AUDIOPREV); pub const SDLK_AUDIOSTOP = @enumToInt(enum_unnamed_51.SDLK_AUDIOSTOP); pub const SDLK_AUDIOPLAY = @enumToInt(enum_unnamed_51.SDLK_AUDIOPLAY); pub const SDLK_AUDIOMUTE = @enumToInt(enum_unnamed_51.SDLK_AUDIOMUTE); pub const SDLK_MEDIASELECT = @enumToInt(enum_unnamed_51.SDLK_MEDIASELECT); pub const SDLK_WWW = @enumToInt(enum_unnamed_51.SDLK_WWW); pub const SDLK_MAIL = @enumToInt(enum_unnamed_51.SDLK_MAIL); pub const SDLK_CALCULATOR = @enumToInt(enum_unnamed_51.SDLK_CALCULATOR); pub const SDLK_COMPUTER = @enumToInt(enum_unnamed_51.SDLK_COMPUTER); pub const SDLK_AC_SEARCH = @enumToInt(enum_unnamed_51.SDLK_AC_SEARCH); pub const SDLK_AC_HOME = @enumToInt(enum_unnamed_51.SDLK_AC_HOME); pub const SDLK_AC_BACK = @enumToInt(enum_unnamed_51.SDLK_AC_BACK); pub const SDLK_AC_FORWARD = @enumToInt(enum_unnamed_51.SDLK_AC_FORWARD); pub const SDLK_AC_STOP = @enumToInt(enum_unnamed_51.SDLK_AC_STOP); pub const SDLK_AC_REFRESH = @enumToInt(enum_unnamed_51.SDLK_AC_REFRESH); pub const SDLK_AC_BOOKMARKS = @enumToInt(enum_unnamed_51.SDLK_AC_BOOKMARKS); pub const SDLK_BRIGHTNESSDOWN = @enumToInt(enum_unnamed_51.SDLK_BRIGHTNESSDOWN); pub const SDLK_BRIGHTNESSUP = @enumToInt(enum_unnamed_51.SDLK_BRIGHTNESSUP); pub const SDLK_DISPLAYSWITCH = @enumToInt(enum_unnamed_51.SDLK_DISPLAYSWITCH); pub const SDLK_KBDILLUMTOGGLE = @enumToInt(enum_unnamed_51.SDLK_KBDILLUMTOGGLE); pub const SDLK_KBDILLUMDOWN = @enumToInt(enum_unnamed_51.SDLK_KBDILLUMDOWN); pub const SDLK_KBDILLUMUP = @enumToInt(enum_unnamed_51.SDLK_KBDILLUMUP); pub const SDLK_EJECT = @enumToInt(enum_unnamed_51.SDLK_EJECT); pub const SDLK_SLEEP = @enumToInt(enum_unnamed_51.SDLK_SLEEP); pub const SDLK_APP1 = @enumToInt(enum_unnamed_51.SDLK_APP1); pub const SDLK_APP2 = @enumToInt(enum_unnamed_51.SDLK_APP2); pub const SDLK_AUDIOREWIND = @enumToInt(enum_unnamed_51.SDLK_AUDIOREWIND); pub const SDLK_AUDIOFASTFORWARD = @enumToInt(enum_unnamed_51.SDLK_AUDIOFASTFORWARD); const enum_unnamed_51 = enum(c_int) { SDLK_UNKNOWN = 0, SDLK_RETURN = 13, SDLK_ESCAPE = 27, SDLK_BACKSPACE = 8, SDLK_TAB = 9, SDLK_SPACE = 32, SDLK_EXCLAIM = 33, SDLK_QUOTEDBL = 34, SDLK_HASH = 35, SDLK_PERCENT = 37, SDLK_DOLLAR = 36, SDLK_AMPERSAND = 38, SDLK_QUOTE = 39, SDLK_LEFTPAREN = 40, SDLK_RIGHTPAREN = 41, SDLK_ASTERISK = 42, SDLK_PLUS = 43, SDLK_COMMA = 44, SDLK_MINUS = 45, SDLK_PERIOD = 46, SDLK_SLASH = 47, SDLK_0 = 48, SDLK_1 = 49, SDLK_2 = 50, SDLK_3 = 51, SDLK_4 = 52, SDLK_5 = 53, SDLK_6 = 54, SDLK_7 = 55, SDLK_8 = 56, SDLK_9 = 57, SDLK_COLON = 58, SDLK_SEMICOLON = 59, SDLK_LESS = 60, SDLK_EQUALS = 61, SDLK_GREATER = 62, SDLK_QUESTION = 63, SDLK_AT = 64, SDLK_LEFTBRACKET = 91, SDLK_BACKSLASH = 92, SDLK_RIGHTBRACKET = 93, SDLK_CARET = 94, SDLK_UNDERSCORE = 95, SDLK_BACKQUOTE = 96, SDLK_a = 97, SDLK_b = 98, SDLK_c = 99, SDLK_d = 100, SDLK_e = 101, SDLK_f = 102, SDLK_g = 103, SDLK_h = 104, SDLK_i = 105, SDLK_j = 106, SDLK_k = 107, SDLK_l = 108, SDLK_m = 109, SDLK_n = 110, SDLK_o = 111, SDLK_p = 112, SDLK_q = 113, SDLK_r = 114, SDLK_s = 115, SDLK_t = 116, SDLK_u = 117, SDLK_v = 118, SDLK_w = 119, SDLK_x = 120, SDLK_y = 121, SDLK_z = 122, SDLK_CAPSLOCK = 1073741881, SDLK_F1 = 1073741882, SDLK_F2 = 1073741883, SDLK_F3 = 1073741884, SDLK_F4 = 1073741885, SDLK_F5 = 1073741886, SDLK_F6 = 1073741887, SDLK_F7 = 1073741888, SDLK_F8 = 1073741889, SDLK_F9 = 1073741890, SDLK_F10 = 1073741891, SDLK_F11 = 1073741892, SDLK_F12 = 1073741893, SDLK_PRINTSCREEN = 1073741894, SDLK_SCROLLLOCK = 1073741895, SDLK_PAUSE = 1073741896, SDLK_INSERT = 1073741897, SDLK_HOME = 1073741898, SDLK_PAGEUP = 1073741899, SDLK_DELETE = 127, SDLK_END = 1073741901, SDLK_PAGEDOWN = 1073741902, SDLK_RIGHT = 1073741903, SDLK_LEFT = 1073741904, SDLK_DOWN = 1073741905, SDLK_UP = 1073741906, SDLK_NUMLOCKCLEAR = 1073741907, SDLK_KP_DIVIDE = 1073741908, SDLK_KP_MULTIPLY = 1073741909, SDLK_KP_MINUS = 1073741910, SDLK_KP_PLUS = 1073741911, SDLK_KP_ENTER = 1073741912, SDLK_KP_1 = 1073741913, SDLK_KP_2 = 1073741914, SDLK_KP_3 = 1073741915, SDLK_KP_4 = 1073741916, SDLK_KP_5 = 1073741917, SDLK_KP_6 = 1073741918, SDLK_KP_7 = 1073741919, SDLK_KP_8 = 1073741920, SDLK_KP_9 = 1073741921, SDLK_KP_0 = 1073741922, SDLK_KP_PERIOD = 1073741923, SDLK_APPLICATION = 1073741925, SDLK_POWER = 1073741926, SDLK_KP_EQUALS = 1073741927, SDLK_F13 = 1073741928, SDLK_F14 = 1073741929, SDLK_F15 = 1073741930, SDLK_F16 = 1073741931, SDLK_F17 = 1073741932, SDLK_F18 = 1073741933, SDLK_F19 = 1073741934, SDLK_F20 = 1073741935, SDLK_F21 = 1073741936, SDLK_F22 = 1073741937, SDLK_F23 = 1073741938, SDLK_F24 = 1073741939, SDLK_EXECUTE = 1073741940, SDLK_HELP = 1073741941, SDLK_MENU = 1073741942, SDLK_SELECT = 1073741943, SDLK_STOP = 1073741944, SDLK_AGAIN = 1073741945, SDLK_UNDO = 1073741946, SDLK_CUT = 1073741947, SDLK_COPY = 1073741948, SDLK_PASTE = 1073741949, SDLK_FIND = 1073741950, SDLK_MUTE = 1073741951, SDLK_VOLUMEUP = 1073741952, SDLK_VOLUMEDOWN = 1073741953, SDLK_KP_COMMA = 1073741957, SDLK_KP_EQUALSAS400 = 1073741958, SDLK_ALTERASE = 1073741977, SDLK_SYSREQ = 1073741978, SDLK_CANCEL = 1073741979, SDLK_CLEAR = 1073741980, SDLK_PRIOR = 1073741981, SDLK_RETURN2 = 1073741982, SDLK_SEPARATOR = 1073741983, SDLK_OUT = 1073741984, SDLK_OPER = 1073741985, SDLK_CLEARAGAIN = 1073741986, SDLK_CRSEL = 1073741987, SDLK_EXSEL = 1073741988, SDLK_KP_00 = 1073742000, SDLK_KP_000 = 1073742001, SDLK_THOUSANDSSEPARATOR = 1073742002, SDLK_DECIMALSEPARATOR = 1073742003, SDLK_CURRENCYUNIT = 1073742004, SDLK_CURRENCYSUBUNIT = 1073742005, SDLK_KP_LEFTPAREN = 1073742006, SDLK_KP_RIGHTPAREN = 1073742007, SDLK_KP_LEFTBRACE = 1073742008, SDLK_KP_RIGHTBRACE = 1073742009, SDLK_KP_TAB = 1073742010, SDLK_KP_BACKSPACE = 1073742011, SDLK_KP_A = 1073742012, SDLK_KP_B = 1073742013, SDLK_KP_C = 1073742014, SDLK_KP_D = 1073742015, SDLK_KP_E = 1073742016, SDLK_KP_F = 1073742017, SDLK_KP_XOR = 1073742018, SDLK_KP_POWER = 1073742019, SDLK_KP_PERCENT = 1073742020, SDLK_KP_LESS = 1073742021, SDLK_KP_GREATER = 1073742022, SDLK_KP_AMPERSAND = 1073742023, SDLK_KP_DBLAMPERSAND = 1073742024, SDLK_KP_VERTICALBAR = 1073742025, SDLK_KP_DBLVERTICALBAR = 1073742026, SDLK_KP_COLON = 1073742027, SDLK_KP_HASH = 1073742028, SDLK_KP_SPACE = 1073742029, SDLK_KP_AT = 1073742030, SDLK_KP_EXCLAM = 1073742031, SDLK_KP_MEMSTORE = 1073742032, SDLK_KP_MEMRECALL = 1073742033, SDLK_KP_MEMCLEAR = 1073742034, SDLK_KP_MEMADD = 1073742035, SDLK_KP_MEMSUBTRACT = 1073742036, SDLK_KP_MEMMULTIPLY = 1073742037, SDLK_KP_MEMDIVIDE = 1073742038, SDLK_KP_PLUSMINUS = 1073742039, SDLK_KP_CLEAR = 1073742040, SDLK_KP_CLEARENTRY = 1073742041, SDLK_KP_BINARY = 1073742042, SDLK_KP_OCTAL = 1073742043, SDLK_KP_DECIMAL = 1073742044, SDLK_KP_HEXADECIMAL = 1073742045, SDLK_LCTRL = 1073742048, SDLK_LSHIFT = 1073742049, SDLK_LALT = 1073742050, SDLK_LGUI = 1073742051, SDLK_RCTRL = 1073742052, SDLK_RSHIFT = 1073742053, SDLK_RALT = 1073742054, SDLK_RGUI = 1073742055, SDLK_MODE = 1073742081, SDLK_AUDIONEXT = 1073742082, SDLK_AUDIOPREV = 1073742083, SDLK_AUDIOSTOP = 1073742084, SDLK_AUDIOPLAY = 1073742085, SDLK_AUDIOMUTE = 1073742086, SDLK_MEDIASELECT = 1073742087, SDLK_WWW = 1073742088, SDLK_MAIL = 1073742089, SDLK_CALCULATOR = 1073742090, SDLK_COMPUTER = 1073742091, SDLK_AC_SEARCH = 1073742092, SDLK_AC_HOME = 1073742093, SDLK_AC_BACK = 1073742094, SDLK_AC_FORWARD = 1073742095, SDLK_AC_STOP = 1073742096, SDLK_AC_REFRESH = 1073742097, SDLK_AC_BOOKMARKS = 1073742098, SDLK_BRIGHTNESSDOWN = 1073742099, SDLK_BRIGHTNESSUP = 1073742100, SDLK_DISPLAYSWITCH = 1073742101, SDLK_KBDILLUMTOGGLE = 1073742102, SDLK_KBDILLUMDOWN = 1073742103, SDLK_KBDILLUMUP = 1073742104, SDLK_EJECT = 1073742105, SDLK_SLEEP = 1073742106, SDLK_APP1 = 1073742107, SDLK_APP2 = 1073742108, SDLK_AUDIOREWIND = 1073742109, SDLK_AUDIOFASTFORWARD = 1073742110, _, }; pub const SDL_KeyCode = enum_unnamed_51; pub const KMOD_NONE = @enumToInt(enum_unnamed_52.KMOD_NONE); pub const KMOD_LSHIFT = @enumToInt(enum_unnamed_52.KMOD_LSHIFT); pub const KMOD_RSHIFT = @enumToInt(enum_unnamed_52.KMOD_RSHIFT); pub const KMOD_LCTRL = @enumToInt(enum_unnamed_52.KMOD_LCTRL); pub const KMOD_RCTRL = @enumToInt(enum_unnamed_52.KMOD_RCTRL); pub const KMOD_LALT = @enumToInt(enum_unnamed_52.KMOD_LALT); pub const KMOD_RALT = @enumToInt(enum_unnamed_52.KMOD_RALT); pub const KMOD_LGUI = @enumToInt(enum_unnamed_52.KMOD_LGUI); pub const KMOD_RGUI = @enumToInt(enum_unnamed_52.KMOD_RGUI); pub const KMOD_NUM = @enumToInt(enum_unnamed_52.KMOD_NUM); pub const KMOD_CAPS = @enumToInt(enum_unnamed_52.KMOD_CAPS); pub const KMOD_MODE = @enumToInt(enum_unnamed_52.KMOD_MODE); pub const KMOD_RESERVED = @enumToInt(enum_unnamed_52.KMOD_RESERVED); pub const KMOD_CTRL = @enumToInt(enum_unnamed_52.KMOD_CTRL); pub const KMOD_SHIFT = @enumToInt(enum_unnamed_52.KMOD_SHIFT); pub const KMOD_ALT = @enumToInt(enum_unnamed_52.KMOD_ALT); pub const KMOD_GUI = @enumToInt(enum_unnamed_52.KMOD_GUI); const enum_unnamed_52 = enum(c_int) { KMOD_NONE = 0, KMOD_LSHIFT = 1, KMOD_RSHIFT = 2, KMOD_LCTRL = 64, KMOD_RCTRL = 128, KMOD_LALT = 256, KMOD_RALT = 512, KMOD_LGUI = 1024, KMOD_RGUI = 2048, KMOD_NUM = 4096, KMOD_CAPS = 8192, KMOD_MODE = 16384, KMOD_RESERVED = 32768, KMOD_CTRL = 192, KMOD_SHIFT = 3, KMOD_ALT = 768, KMOD_GUI = 3072, _, }; pub const SDL_Keymod = enum_unnamed_52; pub const struct_SDL_Keysym = extern struct { scancode: SDL_Scancode, sym: SDL_Keycode, mod: Uint16, unused: Uint32, }; pub const SDL_Keysym = struct_SDL_Keysym; pub extern fn SDL_GetKeyboardFocus() ?*SDL_Window; pub extern fn SDL_GetKeyboardState(numkeys: [*c]c_int) [*c]const Uint8; pub extern fn SDL_GetModState() SDL_Keymod; pub extern fn SDL_SetModState(modstate: SDL_Keymod) void; pub extern fn SDL_GetKeyFromScancode(scancode: SDL_Scancode) SDL_Keycode; pub extern fn SDL_GetScancodeFromKey(key: SDL_Keycode) SDL_Scancode; pub extern fn SDL_GetScancodeName(scancode: SDL_Scancode) [*c]const u8; pub extern fn SDL_GetScancodeFromName(name: [*c]const u8) SDL_Scancode; pub extern fn SDL_GetKeyName(key: SDL_Keycode) [*c]const u8; pub extern fn SDL_GetKeyFromName(name: [*c]const u8) SDL_Keycode; pub extern fn SDL_StartTextInput() void; pub extern fn SDL_IsTextInputActive() SDL_bool; pub extern fn SDL_StopTextInput() void; pub extern fn SDL_SetTextInputRect(rect: [*c]SDL_Rect) void; pub extern fn SDL_HasScreenKeyboardSupport() SDL_bool; pub extern fn SDL_IsScreenKeyboardShown(window: ?*SDL_Window) SDL_bool; pub const struct_SDL_Cursor = opaque {}; pub const SDL_Cursor = struct_SDL_Cursor; pub const SDL_SYSTEM_CURSOR_ARROW = @enumToInt(enum_unnamed_53.SDL_SYSTEM_CURSOR_ARROW); pub const SDL_SYSTEM_CURSOR_IBEAM = @enumToInt(enum_unnamed_53.SDL_SYSTEM_CURSOR_IBEAM); pub const SDL_SYSTEM_CURSOR_WAIT = @enumToInt(enum_unnamed_53.SDL_SYSTEM_CURSOR_WAIT); pub const SDL_SYSTEM_CURSOR_CROSSHAIR = @enumToInt(enum_unnamed_53.SDL_SYSTEM_CURSOR_CROSSHAIR); pub const SDL_SYSTEM_CURSOR_WAITARROW = @enumToInt(enum_unnamed_53.SDL_SYSTEM_CURSOR_WAITARROW); pub const SDL_SYSTEM_CURSOR_SIZENWSE = @enumToInt(enum_unnamed_53.SDL_SYSTEM_CURSOR_SIZENWSE); pub const SDL_SYSTEM_CURSOR_SIZENESW = @enumToInt(enum_unnamed_53.SDL_SYSTEM_CURSOR_SIZENESW); pub const SDL_SYSTEM_CURSOR_SIZEWE = @enumToInt(enum_unnamed_53.SDL_SYSTEM_CURSOR_SIZEWE); pub const SDL_SYSTEM_CURSOR_SIZENS = @enumToInt(enum_unnamed_53.SDL_SYSTEM_CURSOR_SIZENS); pub const SDL_SYSTEM_CURSOR_SIZEALL = @enumToInt(enum_unnamed_53.SDL_SYSTEM_CURSOR_SIZEALL); pub const SDL_SYSTEM_CURSOR_NO = @enumToInt(enum_unnamed_53.SDL_SYSTEM_CURSOR_NO); pub const SDL_SYSTEM_CURSOR_HAND = @enumToInt(enum_unnamed_53.SDL_SYSTEM_CURSOR_HAND); pub const SDL_NUM_SYSTEM_CURSORS = @enumToInt(enum_unnamed_53.SDL_NUM_SYSTEM_CURSORS); const enum_unnamed_53 = enum(c_int) { SDL_SYSTEM_CURSOR_ARROW, SDL_SYSTEM_CURSOR_IBEAM, SDL_SYSTEM_CURSOR_WAIT, SDL_SYSTEM_CURSOR_CROSSHAIR, SDL_SYSTEM_CURSOR_WAITARROW, SDL_SYSTEM_CURSOR_SIZENWSE, SDL_SYSTEM_CURSOR_SIZENESW, SDL_SYSTEM_CURSOR_SIZEWE, SDL_SYSTEM_CURSOR_SIZENS, SDL_SYSTEM_CURSOR_SIZEALL, SDL_SYSTEM_CURSOR_NO, SDL_SYSTEM_CURSOR_HAND, SDL_NUM_SYSTEM_CURSORS, _, }; pub const SDL_SystemCursor = enum_unnamed_53; pub const SDL_MOUSEWHEEL_NORMAL = @enumToInt(enum_unnamed_54.SDL_MOUSEWHEEL_NORMAL); pub const SDL_MOUSEWHEEL_FLIPPED = @enumToInt(enum_unnamed_54.SDL_MOUSEWHEEL_FLIPPED); const enum_unnamed_54 = enum(c_int) { SDL_MOUSEWHEEL_NORMAL, SDL_MOUSEWHEEL_FLIPPED, _, }; pub const SDL_MouseWheelDirection = enum_unnamed_54; pub extern fn SDL_GetMouseFocus() ?*SDL_Window; pub extern fn SDL_GetMouseState(x: [*c]c_int, y: [*c]c_int) Uint32; pub extern fn SDL_GetGlobalMouseState(x: [*c]c_int, y: [*c]c_int) Uint32; pub extern fn SDL_GetRelativeMouseState(x: [*c]c_int, y: [*c]c_int) Uint32; pub extern fn SDL_WarpMouseInWindow(window: ?*SDL_Window, x: c_int, y: c_int) void; pub extern fn SDL_WarpMouseGlobal(x: c_int, y: c_int) c_int; pub extern fn SDL_SetRelativeMouseMode(enabled: SDL_bool) c_int; pub extern fn SDL_CaptureMouse(enabled: SDL_bool) c_int; pub extern fn SDL_GetRelativeMouseMode() SDL_bool; pub extern fn SDL_CreateCursor(data: [*c]const Uint8, mask: [*c]const Uint8, w: c_int, h: c_int, hot_x: c_int, hot_y: c_int) ?*SDL_Cursor; pub extern fn SDL_CreateColorCursor(surface: [*c]SDL_Surface, hot_x: c_int, hot_y: c_int) ?*SDL_Cursor; pub extern fn SDL_CreateSystemCursor(id: SDL_SystemCursor) ?*SDL_Cursor; pub extern fn SDL_SetCursor(cursor: ?*SDL_Cursor) void; pub extern fn SDL_GetCursor() ?*SDL_Cursor; pub extern fn SDL_GetDefaultCursor() ?*SDL_Cursor; pub extern fn SDL_FreeCursor(cursor: ?*SDL_Cursor) void; pub extern fn SDL_ShowCursor(toggle: c_int) c_int; pub const struct__SDL_Joystick = opaque {}; pub const SDL_Joystick = struct__SDL_Joystick; pub const SDL_JoystickGUID = extern struct { data: [16]Uint8, }; pub const SDL_JoystickID = Sint32; pub const SDL_JOYSTICK_TYPE_UNKNOWN = @enumToInt(enum_unnamed_56.SDL_JOYSTICK_TYPE_UNKNOWN); pub const SDL_JOYSTICK_TYPE_GAMECONTROLLER = @enumToInt(enum_unnamed_56.SDL_JOYSTICK_TYPE_GAMECONTROLLER); pub const SDL_JOYSTICK_TYPE_WHEEL = @enumToInt(enum_unnamed_56.SDL_JOYSTICK_TYPE_WHEEL); pub const SDL_JOYSTICK_TYPE_ARCADE_STICK = @enumToInt(enum_unnamed_56.SDL_JOYSTICK_TYPE_ARCADE_STICK); pub const SDL_JOYSTICK_TYPE_FLIGHT_STICK = @enumToInt(enum_unnamed_56.SDL_JOYSTICK_TYPE_FLIGHT_STICK); pub const SDL_JOYSTICK_TYPE_DANCE_PAD = @enumToInt(enum_unnamed_56.SDL_JOYSTICK_TYPE_DANCE_PAD); pub const SDL_JOYSTICK_TYPE_GUITAR = @enumToInt(enum_unnamed_56.SDL_JOYSTICK_TYPE_GUITAR); pub const SDL_JOYSTICK_TYPE_DRUM_KIT = @enumToInt(enum_unnamed_56.SDL_JOYSTICK_TYPE_DRUM_KIT); pub const SDL_JOYSTICK_TYPE_ARCADE_PAD = @enumToInt(enum_unnamed_56.SDL_JOYSTICK_TYPE_ARCADE_PAD); pub const SDL_JOYSTICK_TYPE_THROTTLE = @enumToInt(enum_unnamed_56.SDL_JOYSTICK_TYPE_THROTTLE); const enum_unnamed_56 = enum(c_int) { SDL_JOYSTICK_TYPE_UNKNOWN, SDL_JOYSTICK_TYPE_GAMECONTROLLER, SDL_JOYSTICK_TYPE_WHEEL, SDL_JOYSTICK_TYPE_ARCADE_STICK, SDL_JOYSTICK_TYPE_FLIGHT_STICK, SDL_JOYSTICK_TYPE_DANCE_PAD, SDL_JOYSTICK_TYPE_GUITAR, SDL_JOYSTICK_TYPE_DRUM_KIT, SDL_JOYSTICK_TYPE_ARCADE_PAD, SDL_JOYSTICK_TYPE_THROTTLE, _, }; pub const SDL_JoystickType = enum_unnamed_56; pub const SDL_JOYSTICK_POWER_UNKNOWN = @enumToInt(enum_unnamed_57.SDL_JOYSTICK_POWER_UNKNOWN); pub const SDL_JOYSTICK_POWER_EMPTY = @enumToInt(enum_unnamed_57.SDL_JOYSTICK_POWER_EMPTY); pub const SDL_JOYSTICK_POWER_LOW = @enumToInt(enum_unnamed_57.SDL_JOYSTICK_POWER_LOW); pub const SDL_JOYSTICK_POWER_MEDIUM = @enumToInt(enum_unnamed_57.SDL_JOYSTICK_POWER_MEDIUM); pub const SDL_JOYSTICK_POWER_FULL = @enumToInt(enum_unnamed_57.SDL_JOYSTICK_POWER_FULL); pub const SDL_JOYSTICK_POWER_WIRED = @enumToInt(enum_unnamed_57.SDL_JOYSTICK_POWER_WIRED); pub const SDL_JOYSTICK_POWER_MAX = @enumToInt(enum_unnamed_57.SDL_JOYSTICK_POWER_MAX); const enum_unnamed_57 = enum(c_int) { SDL_JOYSTICK_POWER_UNKNOWN = -1, SDL_JOYSTICK_POWER_EMPTY = 0, SDL_JOYSTICK_POWER_LOW = 1, SDL_JOYSTICK_POWER_MEDIUM = 2, SDL_JOYSTICK_POWER_FULL = 3, SDL_JOYSTICK_POWER_WIRED = 4, SDL_JOYSTICK_POWER_MAX = 5, _, }; pub const SDL_JoystickPowerLevel = enum_unnamed_57; pub extern fn SDL_LockJoysticks() void; pub extern fn SDL_UnlockJoysticks() void; pub extern fn SDL_NumJoysticks() c_int; pub extern fn SDL_JoystickNameForIndex(device_index: c_int) [*c]const u8; pub extern fn SDL_JoystickGetDevicePlayerIndex(device_index: c_int) c_int; pub extern fn SDL_JoystickGetDeviceGUID(device_index: c_int) SDL_JoystickGUID; pub extern fn SDL_JoystickGetDeviceVendor(device_index: c_int) Uint16; pub extern fn SDL_JoystickGetDeviceProduct(device_index: c_int) Uint16; pub extern fn SDL_JoystickGetDeviceProductVersion(device_index: c_int) Uint16; pub extern fn SDL_JoystickGetDeviceType(device_index: c_int) SDL_JoystickType; pub extern fn SDL_JoystickGetDeviceInstanceID(device_index: c_int) SDL_JoystickID; pub extern fn SDL_JoystickOpen(device_index: c_int) ?*SDL_Joystick; pub extern fn SDL_JoystickFromInstanceID(instance_id: SDL_JoystickID) ?*SDL_Joystick; pub extern fn SDL_JoystickFromPlayerIndex(player_index: c_int) ?*SDL_Joystick; pub extern fn SDL_JoystickAttachVirtual(@"type": SDL_JoystickType, naxes: c_int, nbuttons: c_int, nhats: c_int) c_int; pub extern fn SDL_JoystickDetachVirtual(device_index: c_int) c_int; pub extern fn SDL_JoystickIsVirtual(device_index: c_int) SDL_bool; pub extern fn SDL_JoystickSetVirtualAxis(joystick: ?*SDL_Joystick, axis: c_int, value: Sint16) c_int; pub extern fn SDL_JoystickSetVirtualButton(joystick: ?*SDL_Joystick, button: c_int, value: Uint8) c_int; pub extern fn SDL_JoystickSetVirtualHat(joystick: ?*SDL_Joystick, hat: c_int, value: Uint8) c_int; pub extern fn SDL_JoystickName(joystick: ?*SDL_Joystick) [*c]const u8; pub extern fn SDL_JoystickGetPlayerIndex(joystick: ?*SDL_Joystick) c_int; pub extern fn SDL_JoystickSetPlayerIndex(joystick: ?*SDL_Joystick, player_index: c_int) void; pub extern fn SDL_JoystickGetGUID(joystick: ?*SDL_Joystick) SDL_JoystickGUID; pub extern fn SDL_JoystickGetVendor(joystick: ?*SDL_Joystick) Uint16; pub extern fn SDL_JoystickGetProduct(joystick: ?*SDL_Joystick) Uint16; pub extern fn SDL_JoystickGetProductVersion(joystick: ?*SDL_Joystick) Uint16; pub extern fn SDL_JoystickGetSerial(joystick: ?*SDL_Joystick) [*c]const u8; pub extern fn SDL_JoystickGetType(joystick: ?*SDL_Joystick) SDL_JoystickType; pub extern fn SDL_JoystickGetGUIDString(guid: SDL_JoystickGUID, pszGUID: [*c]u8, cbGUID: c_int) void; pub extern fn SDL_JoystickGetGUIDFromString(pchGUID: [*c]const u8) SDL_JoystickGUID; pub extern fn SDL_JoystickGetAttached(joystick: ?*SDL_Joystick) SDL_bool; pub extern fn SDL_JoystickInstanceID(joystick: ?*SDL_Joystick) SDL_JoystickID; pub extern fn SDL_JoystickNumAxes(joystick: ?*SDL_Joystick) c_int; pub extern fn SDL_JoystickNumBalls(joystick: ?*SDL_Joystick) c_int; pub extern fn SDL_JoystickNumHats(joystick: ?*SDL_Joystick) c_int; pub extern fn SDL_JoystickNumButtons(joystick: ?*SDL_Joystick) c_int; pub extern fn SDL_JoystickUpdate() void; pub extern fn SDL_JoystickEventState(state: c_int) c_int; pub extern fn SDL_JoystickGetAxis(joystick: ?*SDL_Joystick, axis: c_int) Sint16; pub extern fn SDL_JoystickGetAxisInitialState(joystick: ?*SDL_Joystick, axis: c_int, state: [*c]Sint16) SDL_bool; pub extern fn SDL_JoystickGetHat(joystick: ?*SDL_Joystick, hat: c_int) Uint8; pub extern fn SDL_JoystickGetBall(joystick: ?*SDL_Joystick, ball: c_int, dx: [*c]c_int, dy: [*c]c_int) c_int; pub extern fn SDL_JoystickGetButton(joystick: ?*SDL_Joystick, button: c_int) Uint8; pub extern fn SDL_JoystickRumble(joystick: ?*SDL_Joystick, low_frequency_rumble: Uint16, high_frequency_rumble: Uint16, duration_ms: Uint32) c_int; pub extern fn SDL_JoystickRumbleTriggers(joystick: ?*SDL_Joystick, left_rumble: Uint16, right_rumble: Uint16, duration_ms: Uint32) c_int; pub extern fn SDL_JoystickHasLED(joystick: ?*SDL_Joystick) SDL_bool; pub extern fn SDL_JoystickSetLED(joystick: ?*SDL_Joystick, red: Uint8, green: Uint8, blue: Uint8) c_int; pub extern fn SDL_JoystickSendEffect(joystick: ?*SDL_Joystick, data: ?*const anyopaque, size: c_int) c_int; pub extern fn SDL_JoystickClose(joystick: ?*SDL_Joystick) void; pub extern fn SDL_JoystickCurrentPowerLevel(joystick: ?*SDL_Joystick) SDL_JoystickPowerLevel; pub const struct__SDL_Sensor = opaque {}; pub const SDL_Sensor = struct__SDL_Sensor; pub const SDL_SensorID = Sint32; pub const SDL_SENSOR_INVALID = @enumToInt(enum_unnamed_83.SDL_SENSOR_INVALID); pub const SDL_SENSOR_UNKNOWN = @enumToInt(enum_unnamed_83.SDL_SENSOR_UNKNOWN); pub const SDL_SENSOR_ACCEL = @enumToInt(enum_unnamed_83.SDL_SENSOR_ACCEL); pub const SDL_SENSOR_GYRO = @enumToInt(enum_unnamed_83.SDL_SENSOR_GYRO); const enum_unnamed_83 = enum(c_int) { SDL_SENSOR_INVALID = -1, SDL_SENSOR_UNKNOWN = 0, SDL_SENSOR_ACCEL = 1, SDL_SENSOR_GYRO = 2, _, }; pub const SDL_SensorType = enum_unnamed_83; pub extern fn SDL_LockSensors() void; pub extern fn SDL_UnlockSensors() void; pub extern fn SDL_NumSensors() c_int; pub extern fn SDL_SensorGetDeviceName(device_index: c_int) [*c]const u8; pub extern fn SDL_SensorGetDeviceType(device_index: c_int) SDL_SensorType; pub extern fn SDL_SensorGetDeviceNonPortableType(device_index: c_int) c_int; pub extern fn SDL_SensorGetDeviceInstanceID(device_index: c_int) SDL_SensorID; pub extern fn SDL_SensorOpen(device_index: c_int) ?*SDL_Sensor; pub extern fn SDL_SensorFromInstanceID(instance_id: SDL_SensorID) ?*SDL_Sensor; pub extern fn SDL_SensorGetName(sensor: ?*SDL_Sensor) [*c]const u8; pub extern fn SDL_SensorGetType(sensor: ?*SDL_Sensor) SDL_SensorType; pub extern fn SDL_SensorGetNonPortableType(sensor: ?*SDL_Sensor) c_int; pub extern fn SDL_SensorGetInstanceID(sensor: ?*SDL_Sensor) SDL_SensorID; pub extern fn SDL_SensorGetData(sensor: ?*SDL_Sensor, data: [*c]f32, num_values: c_int) c_int; pub extern fn SDL_SensorClose(sensor: ?*SDL_Sensor) void; pub extern fn SDL_SensorUpdate() void; pub const struct__SDL_GameController = opaque {}; pub const SDL_GameController = struct__SDL_GameController; pub const SDL_CONTROLLER_TYPE_UNKNOWN = @enumToInt(enum_unnamed_58.SDL_CONTROLLER_TYPE_UNKNOWN); pub const SDL_CONTROLLER_TYPE_XBOX360 = @enumToInt(enum_unnamed_58.SDL_CONTROLLER_TYPE_XBOX360); pub const SDL_CONTROLLER_TYPE_XBOXONE = @enumToInt(enum_unnamed_58.SDL_CONTROLLER_TYPE_XBOXONE); pub const SDL_CONTROLLER_TYPE_PS3 = @enumToInt(enum_unnamed_58.SDL_CONTROLLER_TYPE_PS3); pub const SDL_CONTROLLER_TYPE_PS4 = @enumToInt(enum_unnamed_58.SDL_CONTROLLER_TYPE_PS4); pub const SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO = @enumToInt(enum_unnamed_58.SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO); pub const SDL_CONTROLLER_TYPE_VIRTUAL = @enumToInt(enum_unnamed_58.SDL_CONTROLLER_TYPE_VIRTUAL); pub const SDL_CONTROLLER_TYPE_PS5 = @enumToInt(enum_unnamed_58.SDL_CONTROLLER_TYPE_PS5); const enum_unnamed_58 = enum(c_int) { SDL_CONTROLLER_TYPE_UNKNOWN = 0, SDL_CONTROLLER_TYPE_XBOX360 = 1, SDL_CONTROLLER_TYPE_XBOXONE = 2, SDL_CONTROLLER_TYPE_PS3 = 3, SDL_CONTROLLER_TYPE_PS4 = 4, SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO = 5, SDL_CONTROLLER_TYPE_VIRTUAL = 6, SDL_CONTROLLER_TYPE_PS5 = 7, _, }; pub const SDL_GameControllerType = enum_unnamed_58; pub const SDL_CONTROLLER_BINDTYPE_NONE = @enumToInt(enum_unnamed_59.SDL_CONTROLLER_BINDTYPE_NONE); pub const SDL_CONTROLLER_BINDTYPE_BUTTON = @enumToInt(enum_unnamed_59.SDL_CONTROLLER_BINDTYPE_BUTTON); pub const SDL_CONTROLLER_BINDTYPE_AXIS = @enumToInt(enum_unnamed_59.SDL_CONTROLLER_BINDTYPE_AXIS); pub const SDL_CONTROLLER_BINDTYPE_HAT = @enumToInt(enum_unnamed_59.SDL_CONTROLLER_BINDTYPE_HAT); const enum_unnamed_59 = enum(c_int) { SDL_CONTROLLER_BINDTYPE_NONE = 0, SDL_CONTROLLER_BINDTYPE_BUTTON = 1, SDL_CONTROLLER_BINDTYPE_AXIS = 2, SDL_CONTROLLER_BINDTYPE_HAT = 3, _, }; pub const SDL_GameControllerBindType = enum_unnamed_59; const struct_unnamed_14 = extern struct { hat: c_int, hat_mask: c_int, }; const union_unnamed_13 = extern union { button: c_int, axis: c_int, hat: struct_unnamed_14, }; pub const struct_SDL_GameControllerButtonBind = extern struct { bindType: SDL_GameControllerBindType, value: union_unnamed_13, }; pub const SDL_GameControllerButtonBind = struct_SDL_GameControllerButtonBind; pub extern fn SDL_GameControllerAddMappingsFromRW(rw: [*c]SDL_RWops, freerw: c_int) c_int; pub extern fn SDL_GameControllerAddMapping(mappingString: [*c]const u8) c_int; pub extern fn SDL_GameControllerNumMappings() c_int; pub extern fn SDL_GameControllerMappingForIndex(mapping_index: c_int) [*c]u8; pub extern fn SDL_GameControllerMappingForGUID(guid: SDL_JoystickGUID) [*c]u8; pub extern fn SDL_GameControllerMapping(gamecontroller: ?*SDL_GameController) [*c]u8; pub extern fn SDL_IsGameController(joystick_index: c_int) SDL_bool; pub extern fn SDL_GameControllerNameForIndex(joystick_index: c_int) [*c]const u8; pub extern fn SDL_GameControllerTypeForIndex(joystick_index: c_int) SDL_GameControllerType; pub extern fn SDL_GameControllerMappingForDeviceIndex(joystick_index: c_int) [*c]u8; pub extern fn SDL_GameControllerOpen(joystick_index: c_int) ?*SDL_GameController; pub extern fn SDL_GameControllerFromInstanceID(joyid: SDL_JoystickID) ?*SDL_GameController; pub extern fn SDL_GameControllerFromPlayerIndex(player_index: c_int) ?*SDL_GameController; pub extern fn SDL_GameControllerName(gamecontroller: ?*SDL_GameController) [*c]const u8; pub extern fn SDL_GameControllerGetType(gamecontroller: ?*SDL_GameController) SDL_GameControllerType; pub extern fn SDL_GameControllerGetPlayerIndex(gamecontroller: ?*SDL_GameController) c_int; pub extern fn SDL_GameControllerSetPlayerIndex(gamecontroller: ?*SDL_GameController, player_index: c_int) void; pub extern fn SDL_GameControllerGetVendor(gamecontroller: ?*SDL_GameController) Uint16; pub extern fn SDL_GameControllerGetProduct(gamecontroller: ?*SDL_GameController) Uint16; pub extern fn SDL_GameControllerGetProductVersion(gamecontroller: ?*SDL_GameController) Uint16; pub extern fn SDL_GameControllerGetSerial(gamecontroller: ?*SDL_GameController) [*c]const u8; pub extern fn SDL_GameControllerGetAttached(gamecontroller: ?*SDL_GameController) SDL_bool; pub extern fn SDL_GameControllerGetJoystick(gamecontroller: ?*SDL_GameController) ?*SDL_Joystick; pub extern fn SDL_GameControllerEventState(state: c_int) c_int; pub extern fn SDL_GameControllerUpdate() void; pub const SDL_CONTROLLER_AXIS_INVALID = @enumToInt(enum_unnamed_62.SDL_CONTROLLER_AXIS_INVALID); pub const SDL_CONTROLLER_AXIS_LEFTX = @enumToInt(enum_unnamed_62.SDL_CONTROLLER_AXIS_LEFTX); pub const SDL_CONTROLLER_AXIS_LEFTY = @enumToInt(enum_unnamed_62.SDL_CONTROLLER_AXIS_LEFTY); pub const SDL_CONTROLLER_AXIS_RIGHTX = @enumToInt(enum_unnamed_62.SDL_CONTROLLER_AXIS_RIGHTX); pub const SDL_CONTROLLER_AXIS_RIGHTY = @enumToInt(enum_unnamed_62.SDL_CONTROLLER_AXIS_RIGHTY); pub const SDL_CONTROLLER_AXIS_TRIGGERLEFT = @enumToInt(enum_unnamed_62.SDL_CONTROLLER_AXIS_TRIGGERLEFT); pub const SDL_CONTROLLER_AXIS_TRIGGERRIGHT = @enumToInt(enum_unnamed_62.SDL_CONTROLLER_AXIS_TRIGGERRIGHT); pub const SDL_CONTROLLER_AXIS_MAX = @enumToInt(enum_unnamed_62.SDL_CONTROLLER_AXIS_MAX); const enum_unnamed_62 = enum(c_int) { SDL_CONTROLLER_AXIS_INVALID = -1, SDL_CONTROLLER_AXIS_LEFTX = 0, SDL_CONTROLLER_AXIS_LEFTY = 1, SDL_CONTROLLER_AXIS_RIGHTX = 2, SDL_CONTROLLER_AXIS_RIGHTY = 3, SDL_CONTROLLER_AXIS_TRIGGERLEFT = 4, SDL_CONTROLLER_AXIS_TRIGGERRIGHT = 5, SDL_CONTROLLER_AXIS_MAX = 6, _, }; pub const SDL_GameControllerAxis = enum_unnamed_62; pub extern fn SDL_GameControllerGetAxisFromString(str: [*c]const u8) SDL_GameControllerAxis; pub extern fn SDL_GameControllerGetStringForAxis(axis: SDL_GameControllerAxis) [*c]const u8; pub extern fn SDL_GameControllerGetBindForAxis(gamecontroller: ?*SDL_GameController, axis: SDL_GameControllerAxis) SDL_GameControllerButtonBind; pub extern fn SDL_GameControllerHasAxis(gamecontroller: ?*SDL_GameController, axis: SDL_GameControllerAxis) SDL_bool; pub extern fn SDL_GameControllerGetAxis(gamecontroller: ?*SDL_GameController, axis: SDL_GameControllerAxis) Sint16; pub const SDL_CONTROLLER_BUTTON_INVALID = @enumToInt(enum_unnamed_63.SDL_CONTROLLER_BUTTON_INVALID); pub const SDL_CONTROLLER_BUTTON_A = @enumToInt(enum_unnamed_63.SDL_CONTROLLER_BUTTON_A); pub const SDL_CONTROLLER_BUTTON_B = @enumToInt(enum_unnamed_63.SDL_CONTROLLER_BUTTON_B); pub const SDL_CONTROLLER_BUTTON_X = @enumToInt(enum_unnamed_63.SDL_CONTROLLER_BUTTON_X); pub const SDL_CONTROLLER_BUTTON_Y = @enumToInt(enum_unnamed_63.SDL_CONTROLLER_BUTTON_Y); pub const SDL_CONTROLLER_BUTTON_BACK = @enumToInt(enum_unnamed_63.SDL_CONTROLLER_BUTTON_BACK); pub const SDL_CONTROLLER_BUTTON_GUIDE = @enumToInt(enum_unnamed_63.SDL_CONTROLLER_BUTTON_GUIDE); pub const SDL_CONTROLLER_BUTTON_START = @enumToInt(enum_unnamed_63.SDL_CONTROLLER_BUTTON_START); pub const SDL_CONTROLLER_BUTTON_LEFTSTICK = @enumToInt(enum_unnamed_63.SDL_CONTROLLER_BUTTON_LEFTSTICK); pub const SDL_CONTROLLER_BUTTON_RIGHTSTICK = @enumToInt(enum_unnamed_63.SDL_CONTROLLER_BUTTON_RIGHTSTICK); pub const SDL_CONTROLLER_BUTTON_LEFTSHOULDER = @enumToInt(enum_unnamed_63.SDL_CONTROLLER_BUTTON_LEFTSHOULDER); pub const SDL_CONTROLLER_BUTTON_RIGHTSHOULDER = @enumToInt(enum_unnamed_63.SDL_CONTROLLER_BUTTON_RIGHTSHOULDER); pub const SDL_CONTROLLER_BUTTON_DPAD_UP = @enumToInt(enum_unnamed_63.SDL_CONTROLLER_BUTTON_DPAD_UP); pub const SDL_CONTROLLER_BUTTON_DPAD_DOWN = @enumToInt(enum_unnamed_63.SDL_CONTROLLER_BUTTON_DPAD_DOWN); pub const SDL_CONTROLLER_BUTTON_DPAD_LEFT = @enumToInt(enum_unnamed_63.SDL_CONTROLLER_BUTTON_DPAD_LEFT); pub const SDL_CONTROLLER_BUTTON_DPAD_RIGHT = @enumToInt(enum_unnamed_63.SDL_CONTROLLER_BUTTON_DPAD_RIGHT); pub const SDL_CONTROLLER_BUTTON_MISC1 = @enumToInt(enum_unnamed_63.SDL_CONTROLLER_BUTTON_MISC1); pub const SDL_CONTROLLER_BUTTON_PADDLE1 = @enumToInt(enum_unnamed_63.SDL_CONTROLLER_BUTTON_PADDLE1); pub const SDL_CONTROLLER_BUTTON_PADDLE2 = @enumToInt(enum_unnamed_63.SDL_CONTROLLER_BUTTON_PADDLE2); pub const SDL_CONTROLLER_BUTTON_PADDLE3 = @enumToInt(enum_unnamed_63.SDL_CONTROLLER_BUTTON_PADDLE3); pub const SDL_CONTROLLER_BUTTON_PADDLE4 = @enumToInt(enum_unnamed_63.SDL_CONTROLLER_BUTTON_PADDLE4); pub const SDL_CONTROLLER_BUTTON_MAX = @enumToInt(enum_unnamed_63.SDL_CONTROLLER_BUTTON_MAX); const enum_unnamed_63 = enum(c_int) { SDL_CONTROLLER_BUTTON_INVALID = -1, SDL_CONTROLLER_BUTTON_A = 0, SDL_CONTROLLER_BUTTON_B = 1, SDL_CONTROLLER_BUTTON_X = 2, SDL_CONTROLLER_BUTTON_Y = 3, SDL_CONTROLLER_BUTTON_BACK = 4, SDL_CONTROLLER_BUTTON_GUIDE = 5, SDL_CONTROLLER_BUTTON_START = 6, SDL_CONTROLLER_BUTTON_LEFTSTICK = 7, SDL_CONTROLLER_BUTTON_RIGHTSTICK = 8, SDL_CONTROLLER_BUTTON_LEFTSHOULDER = 9, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER = 10, SDL_CONTROLLER_BUTTON_DPAD_UP = 11, SDL_CONTROLLER_BUTTON_DPAD_DOWN = 12, SDL_CONTROLLER_BUTTON_DPAD_LEFT = 13, SDL_CONTROLLER_BUTTON_DPAD_RIGHT = 14, SDL_CONTROLLER_BUTTON_MISC1 = 15, SDL_CONTROLLER_BUTTON_PADDLE1 = 16, SDL_CONTROLLER_BUTTON_PADDLE2 = 17, SDL_CONTROLLER_BUTTON_PADDLE3 = 18, SDL_CONTROLLER_BUTTON_PADDLE4 = 19, SDL_CONTROLLER_BUTTON_MAX = 20, _, }; pub const SDL_GameControllerButton = enum_unnamed_63; pub extern fn SDL_GameControllerGetButtonFromString(str: [*c]const u8) SDL_GameControllerButton; pub extern fn SDL_GameControllerGetStringForButton(button: SDL_GameControllerButton) [*c]const u8; pub extern fn SDL_GameControllerGetBindForButton(gamecontroller: ?*SDL_GameController, button: SDL_GameControllerButton) SDL_GameControllerButtonBind; pub extern fn SDL_GameControllerHasButton(gamecontroller: ?*SDL_GameController, button: SDL_GameControllerButton) SDL_bool; pub extern fn SDL_GameControllerGetButton(gamecontroller: ?*SDL_GameController, button: SDL_GameControllerButton) Uint8; pub extern fn SDL_GameControllerGetNumTouchpads(gamecontroller: ?*SDL_GameController) c_int; pub extern fn SDL_GameControllerGetNumTouchpadFingers(gamecontroller: ?*SDL_GameController, touchpad: c_int) c_int; pub extern fn SDL_GameControllerGetTouchpadFinger(gamecontroller: ?*SDL_GameController, touchpad: c_int, finger: c_int, state: [*c]Uint8, x: [*c]f32, y: [*c]f32, pressure: [*c]f32) c_int; pub extern fn SDL_GameControllerHasSensor(gamecontroller: ?*SDL_GameController, @"type": SDL_SensorType) SDL_bool; pub extern fn SDL_GameControllerSetSensorEnabled(gamecontroller: ?*SDL_GameController, @"type": SDL_SensorType, enabled: SDL_bool) c_int; pub extern fn SDL_GameControllerIsSensorEnabled(gamecontroller: ?*SDL_GameController, @"type": SDL_SensorType) SDL_bool; pub extern fn SDL_GameControllerGetSensorDataRate(gamecontroller: ?*SDL_GameController, @"type": SDL_SensorType) f32; pub extern fn SDL_GameControllerGetSensorData(gamecontroller: ?*SDL_GameController, @"type": SDL_SensorType, data: [*c]f32, num_values: c_int) c_int; pub extern fn SDL_GameControllerRumble(gamecontroller: ?*SDL_GameController, low_frequency_rumble: Uint16, high_frequency_rumble: Uint16, duration_ms: Uint32) c_int; pub extern fn SDL_GameControllerRumbleTriggers(gamecontroller: ?*SDL_GameController, left_rumble: Uint16, right_rumble: Uint16, duration_ms: Uint32) c_int; pub extern fn SDL_GameControllerHasLED(gamecontroller: ?*SDL_GameController) SDL_bool; pub extern fn SDL_GameControllerSetLED(gamecontroller: ?*SDL_GameController, red: Uint8, green: Uint8, blue: Uint8) c_int; pub extern fn SDL_GameControllerSendEffect(gamecontroller: ?*SDL_GameController, data: ?*const anyopaque, size: c_int) c_int; pub extern fn SDL_GameControllerClose(gamecontroller: ?*SDL_GameController) void; pub const SDL_TouchID = Sint64; pub const SDL_FingerID = Sint64; pub const SDL_TOUCH_DEVICE_INVALID = @enumToInt(enum_unnamed_64.SDL_TOUCH_DEVICE_INVALID); pub const SDL_TOUCH_DEVICE_DIRECT = @enumToInt(enum_unnamed_64.SDL_TOUCH_DEVICE_DIRECT); pub const SDL_TOUCH_DEVICE_INDIRECT_ABSOLUTE = @enumToInt(enum_unnamed_64.SDL_TOUCH_DEVICE_INDIRECT_ABSOLUTE); pub const SDL_TOUCH_DEVICE_INDIRECT_RELATIVE = @enumToInt(enum_unnamed_64.SDL_TOUCH_DEVICE_INDIRECT_RELATIVE); const enum_unnamed_64 = enum(c_int) { SDL_TOUCH_DEVICE_INVALID = -1, SDL_TOUCH_DEVICE_DIRECT = 0, SDL_TOUCH_DEVICE_INDIRECT_ABSOLUTE = 1, SDL_TOUCH_DEVICE_INDIRECT_RELATIVE = 2, _, }; pub const SDL_TouchDeviceType = enum_unnamed_64; pub const struct_SDL_Finger = extern struct { id: SDL_FingerID, x: f32, y: f32, pressure: f32, }; pub const SDL_Finger = struct_SDL_Finger; pub extern fn SDL_GetNumTouchDevices() c_int; pub extern fn SDL_GetTouchDevice(index: c_int) SDL_TouchID; pub extern fn SDL_GetTouchDeviceType(touchID: SDL_TouchID) SDL_TouchDeviceType; pub extern fn SDL_GetNumTouchFingers(touchID: SDL_TouchID) c_int; pub extern fn SDL_GetTouchFinger(touchID: SDL_TouchID, index: c_int) [*c]SDL_Finger; pub const SDL_GestureID = Sint64; pub extern fn SDL_RecordGesture(touchId: SDL_TouchID) c_int; pub extern fn SDL_SaveAllDollarTemplates(dst: [*c]SDL_RWops) c_int; pub extern fn SDL_SaveDollarTemplate(gestureId: SDL_GestureID, dst: [*c]SDL_RWops) c_int; pub extern fn SDL_LoadDollarTemplates(touchId: SDL_TouchID, src: [*c]SDL_RWops) c_int; pub const SDL_FIRSTEVENT = @enumToInt(enum_unnamed_65.SDL_FIRSTEVENT); pub const SDL_QUIT = @enumToInt(enum_unnamed_65.SDL_QUIT); pub const SDL_APP_TERMINATING = @enumToInt(enum_unnamed_65.SDL_APP_TERMINATING); pub const SDL_APP_LOWMEMORY = @enumToInt(enum_unnamed_65.SDL_APP_LOWMEMORY); pub const SDL_APP_WILLENTERBACKGROUND = @enumToInt(enum_unnamed_65.SDL_APP_WILLENTERBACKGROUND); pub const SDL_APP_DIDENTERBACKGROUND = @enumToInt(enum_unnamed_65.SDL_APP_DIDENTERBACKGROUND); pub const SDL_APP_WILLENTERFOREGROUND = @enumToInt(enum_unnamed_65.SDL_APP_WILLENTERFOREGROUND); pub const SDL_APP_DIDENTERFOREGROUND = @enumToInt(enum_unnamed_65.SDL_APP_DIDENTERFOREGROUND); pub const SDL_LOCALECHANGED = @enumToInt(enum_unnamed_65.SDL_LOCALECHANGED); pub const SDL_DISPLAYEVENT = @enumToInt(enum_unnamed_65.SDL_DISPLAYEVENT); pub const SDL_WINDOWEVENT = @enumToInt(enum_unnamed_65.SDL_WINDOWEVENT); pub const SDL_SYSWMEVENT = @enumToInt(enum_unnamed_65.SDL_SYSWMEVENT); pub const SDL_KEYDOWN = @enumToInt(enum_unnamed_65.SDL_KEYDOWN); pub const SDL_KEYUP = @enumToInt(enum_unnamed_65.SDL_KEYUP); pub const SDL_TEXTEDITING = @enumToInt(enum_unnamed_65.SDL_TEXTEDITING); pub const SDL_TEXTINPUT = @enumToInt(enum_unnamed_65.SDL_TEXTINPUT); pub const SDL_KEYMAPCHANGED = @enumToInt(enum_unnamed_65.SDL_KEYMAPCHANGED); pub const SDL_MOUSEMOTION = @enumToInt(enum_unnamed_65.SDL_MOUSEMOTION); pub const SDL_MOUSEBUTTONDOWN = @enumToInt(enum_unnamed_65.SDL_MOUSEBUTTONDOWN); pub const SDL_MOUSEBUTTONUP = @enumToInt(enum_unnamed_65.SDL_MOUSEBUTTONUP); pub const SDL_MOUSEWHEEL = @enumToInt(enum_unnamed_65.SDL_MOUSEWHEEL); pub const SDL_JOYAXISMOTION = @enumToInt(enum_unnamed_65.SDL_JOYAXISMOTION); pub const SDL_JOYBALLMOTION = @enumToInt(enum_unnamed_65.SDL_JOYBALLMOTION); pub const SDL_JOYHATMOTION = @enumToInt(enum_unnamed_65.SDL_JOYHATMOTION); pub const SDL_JOYBUTTONDOWN = @enumToInt(enum_unnamed_65.SDL_JOYBUTTONDOWN); pub const SDL_JOYBUTTONUP = @enumToInt(enum_unnamed_65.SDL_JOYBUTTONUP); pub const SDL_JOYDEVICEADDED = @enumToInt(enum_unnamed_65.SDL_JOYDEVICEADDED); pub const SDL_JOYDEVICEREMOVED = @enumToInt(enum_unnamed_65.SDL_JOYDEVICEREMOVED); pub const SDL_CONTROLLERAXISMOTION = @enumToInt(enum_unnamed_65.SDL_CONTROLLERAXISMOTION); pub const SDL_CONTROLLERBUTTONDOWN = @enumToInt(enum_unnamed_65.SDL_CONTROLLERBUTTONDOWN); pub const SDL_CONTROLLERBUTTONUP = @enumToInt(enum_unnamed_65.SDL_CONTROLLERBUTTONUP); pub const SDL_CONTROLLERDEVICEADDED = @enumToInt(enum_unnamed_65.SDL_CONTROLLERDEVICEADDED); pub const SDL_CONTROLLERDEVICEREMOVED = @enumToInt(enum_unnamed_65.SDL_CONTROLLERDEVICEREMOVED); pub const SDL_CONTROLLERDEVICEREMAPPED = @enumToInt(enum_unnamed_65.SDL_CONTROLLERDEVICEREMAPPED); pub const SDL_FINGERDOWN = @enumToInt(enum_unnamed_65.SDL_FINGERDOWN); pub const SDL_FINGERUP = @enumToInt(enum_unnamed_65.SDL_FINGERUP); pub const SDL_FINGERMOTION = @enumToInt(enum_unnamed_65.SDL_FINGERMOTION); pub const SDL_DOLLARGESTURE = @enumToInt(enum_unnamed_65.SDL_DOLLARGESTURE); pub const SDL_DOLLARRECORD = @enumToInt(enum_unnamed_65.SDL_DOLLARRECORD); pub const SDL_MULTIGESTURE = @enumToInt(enum_unnamed_65.SDL_MULTIGESTURE); pub const SDL_CLIPBOARDUPDATE = @enumToInt(enum_unnamed_65.SDL_CLIPBOARDUPDATE); pub const SDL_DROPFILE = @enumToInt(enum_unnamed_65.SDL_DROPFILE); pub const SDL_DROPTEXT = @enumToInt(enum_unnamed_65.SDL_DROPTEXT); pub const SDL_DROPBEGIN = @enumToInt(enum_unnamed_65.SDL_DROPBEGIN); pub const SDL_DROPCOMPLETE = @enumToInt(enum_unnamed_65.SDL_DROPCOMPLETE); pub const SDL_AUDIODEVICEADDED = @enumToInt(enum_unnamed_65.SDL_AUDIODEVICEADDED); pub const SDL_AUDIODEVICEREMOVED = @enumToInt(enum_unnamed_65.SDL_AUDIODEVICEREMOVED); pub const SDL_SENSORUPDATE = @enumToInt(enum_unnamed_65.SDL_SENSORUPDATE); pub const SDL_RENDER_TARGETS_RESET = @enumToInt(enum_unnamed_65.SDL_RENDER_TARGETS_RESET); pub const SDL_RENDER_DEVICE_RESET = @enumToInt(enum_unnamed_65.SDL_RENDER_DEVICE_RESET); pub const SDL_USEREVENT = @enumToInt(enum_unnamed_65.SDL_USEREVENT); pub const SDL_LASTEVENT = @enumToInt(enum_unnamed_65.SDL_LASTEVENT); const enum_unnamed_65 = enum(c_int) { SDL_FIRSTEVENT = 0, SDL_QUIT = 256, SDL_APP_TERMINATING = 257, SDL_APP_LOWMEMORY = 258, SDL_APP_WILLENTERBACKGROUND = 259, SDL_APP_DIDENTERBACKGROUND = 260, SDL_APP_WILLENTERFOREGROUND = 261, SDL_APP_DIDENTERFOREGROUND = 262, SDL_LOCALECHANGED = 263, SDL_DISPLAYEVENT = 336, SDL_WINDOWEVENT = 512, SDL_SYSWMEVENT = 513, SDL_KEYDOWN = 768, SDL_KEYUP = 769, SDL_TEXTEDITING = 770, SDL_TEXTINPUT = 771, SDL_KEYMAPCHANGED = 772, SDL_MOUSEMOTION = 1024, SDL_MOUSEBUTTONDOWN = 1025, SDL_MOUSEBUTTONUP = 1026, SDL_MOUSEWHEEL = 1027, SDL_JOYAXISMOTION = 1536, SDL_JOYBALLMOTION = 1537, SDL_JOYHATMOTION = 1538, SDL_JOYBUTTONDOWN = 1539, SDL_JOYBUTTONUP = 1540, SDL_JOYDEVICEADDED = 1541, SDL_JOYDEVICEREMOVED = 1542, SDL_CONTROLLERAXISMOTION = 1616, SDL_CONTROLLERBUTTONDOWN = 1617, SDL_CONTROLLERBUTTONUP = 1618, SDL_CONTROLLERDEVICEADDED = 1619, SDL_CONTROLLERDEVICEREMOVED = 1620, SDL_CONTROLLERDEVICEREMAPPED = 1621, SDL_FINGERDOWN = 1792, SDL_FINGERUP = 1793, SDL_FINGERMOTION = 1794, SDL_DOLLARGESTURE = 2048, SDL_DOLLARRECORD = 2049, SDL_MULTIGESTURE = 2050, SDL_CLIPBOARDUPDATE = 2304, SDL_DROPFILE = 4096, SDL_DROPTEXT = 4097, SDL_DROPBEGIN = 4098, SDL_DROPCOMPLETE = 4099, SDL_AUDIODEVICEADDED = 4352, SDL_AUDIODEVICEREMOVED = 4353, SDL_SENSORUPDATE = 4608, SDL_RENDER_TARGETS_RESET = 8192, SDL_RENDER_DEVICE_RESET = 8193, SDL_USEREVENT = 32768, SDL_LASTEVENT = 65535, _, }; pub const SDL_EventType = enum_unnamed_65; pub const struct_SDL_CommonEvent = extern struct { type: Uint32, timestamp: Uint32, }; pub const SDL_CommonEvent = struct_SDL_CommonEvent; pub const struct_SDL_DisplayEvent = extern struct { type: Uint32, timestamp: Uint32, display: Uint32, event: Uint8, padding1: Uint8, padding2: Uint8, padding3: Uint8, data1: Sint32, }; pub const SDL_DisplayEvent = struct_SDL_DisplayEvent; pub const struct_SDL_WindowEvent = extern struct { type: Uint32, timestamp: Uint32, windowID: Uint32, event: Uint8, padding1: Uint8, padding2: Uint8, padding3: Uint8, data1: Sint32, data2: Sint32, }; pub const SDL_WindowEvent = struct_SDL_WindowEvent; pub const struct_SDL_KeyboardEvent = extern struct { type: Uint32, timestamp: Uint32, windowID: Uint32, state: Uint8, repeat: Uint8, padding2: Uint8, padding3: Uint8, keysym: SDL_Keysym, }; pub const SDL_KeyboardEvent = struct_SDL_KeyboardEvent; pub const struct_SDL_TextEditingEvent = extern struct { type: Uint32, timestamp: Uint32, windowID: Uint32, text: [32]u8, start: Sint32, length: Sint32, }; pub const SDL_TextEditingEvent = struct_SDL_TextEditingEvent; pub const struct_SDL_TextInputEvent = extern struct { type: Uint32, timestamp: Uint32, windowID: Uint32, text: [32]u8, }; pub const SDL_TextInputEvent = struct_SDL_TextInputEvent; pub const struct_SDL_MouseMotionEvent = extern struct { type: Uint32, timestamp: Uint32, windowID: Uint32, which: Uint32, state: Uint32, x: Sint32, y: Sint32, xrel: Sint32, yrel: Sint32, }; pub const SDL_MouseMotionEvent = struct_SDL_MouseMotionEvent; pub const struct_SDL_MouseButtonEvent = extern struct { type: Uint32, timestamp: Uint32, windowID: Uint32, which: Uint32, button: Uint8, state: Uint8, clicks: Uint8, padding1: Uint8, x: Sint32, y: Sint32, }; pub const SDL_MouseButtonEvent = struct_SDL_MouseButtonEvent; pub const struct_SDL_MouseWheelEvent = extern struct { type: Uint32, timestamp: Uint32, windowID: Uint32, which: Uint32, x: Sint32, y: Sint32, direction: Uint32, }; pub const SDL_MouseWheelEvent = struct_SDL_MouseWheelEvent; pub const struct_SDL_JoyAxisEvent = extern struct { type: Uint32, timestamp: Uint32, which: SDL_JoystickID, axis: Uint8, padding1: Uint8, padding2: Uint8, padding3: Uint8, value: Sint16, padding4: Uint16, }; pub const SDL_JoyAxisEvent = struct_SDL_JoyAxisEvent; pub const struct_SDL_JoyBallEvent = extern struct { type: Uint32, timestamp: Uint32, which: SDL_JoystickID, ball: Uint8, padding1: Uint8, padding2: Uint8, padding3: Uint8, xrel: Sint16, yrel: Sint16, }; pub const SDL_JoyBallEvent = struct_SDL_JoyBallEvent; pub const struct_SDL_JoyHatEvent = extern struct { type: Uint32, timestamp: Uint32, which: SDL_JoystickID, hat: Uint8, value: Uint8, padding1: Uint8, padding2: Uint8, }; pub const SDL_JoyHatEvent = struct_SDL_JoyHatEvent; pub const struct_SDL_JoyButtonEvent = extern struct { type: Uint32, timestamp: Uint32, which: SDL_JoystickID, button: Uint8, state: Uint8, padding1: Uint8, padding2: Uint8, }; pub const SDL_JoyButtonEvent = struct_SDL_JoyButtonEvent; pub const struct_SDL_JoyDeviceEvent = extern struct { type: Uint32, timestamp: Uint32, which: Sint32, }; pub const SDL_JoyDeviceEvent = struct_SDL_JoyDeviceEvent; pub const struct_SDL_ControllerAxisEvent = extern struct { type: Uint32, timestamp: Uint32, which: SDL_JoystickID, axis: Uint8, padding1: Uint8, padding2: Uint8, padding3: Uint8, value: Sint16, padding4: Uint16, }; pub const SDL_ControllerAxisEvent = struct_SDL_ControllerAxisEvent; pub const struct_SDL_ControllerButtonEvent = extern struct { type: Uint32, timestamp: Uint32, which: SDL_JoystickID, button: Uint8, state: Uint8, padding1: Uint8, padding2: Uint8, }; pub const SDL_ControllerButtonEvent = struct_SDL_ControllerButtonEvent; pub const struct_SDL_ControllerDeviceEvent = extern struct { type: Uint32, timestamp: Uint32, which: Sint32, }; pub const SDL_ControllerDeviceEvent = struct_SDL_ControllerDeviceEvent; pub const struct_SDL_ControllerTouchpadEvent = extern struct { type: Uint32, timestamp: Uint32, which: SDL_JoystickID, touchpad: Sint32, finger: Sint32, x: f32, y: f32, pressure: f32, }; pub const SDL_ControllerTouchpadEvent = struct_SDL_ControllerTouchpadEvent; pub const struct_SDL_ControllerSensorEvent = extern struct { type: Uint32, timestamp: Uint32, which: SDL_JoystickID, sensor: Sint32, data: [3]f32, }; pub const SDL_ControllerSensorEvent = struct_SDL_ControllerSensorEvent; pub const struct_SDL_AudioDeviceEvent = extern struct { type: Uint32, timestamp: Uint32, which: Uint32, iscapture: Uint8, padding1: Uint8, padding2: Uint8, padding3: Uint8, }; pub const SDL_AudioDeviceEvent = struct_SDL_AudioDeviceEvent; pub const struct_SDL_TouchFingerEvent = extern struct { type: Uint32, timestamp: Uint32, touchId: SDL_TouchID, fingerId: SDL_FingerID, x: f32, y: f32, dx: f32, dy: f32, pressure: f32, windowID: Uint32, }; pub const SDL_TouchFingerEvent = struct_SDL_TouchFingerEvent; pub const struct_SDL_MultiGestureEvent = extern struct { type: Uint32, timestamp: Uint32, touchId: SDL_TouchID, dTheta: f32, dDist: f32, x: f32, y: f32, numFingers: Uint16, padding: Uint16, }; pub const SDL_MultiGestureEvent = struct_SDL_MultiGestureEvent; pub const struct_SDL_DollarGestureEvent = extern struct { type: Uint32, timestamp: Uint32, touchId: SDL_TouchID, gestureId: SDL_GestureID, numFingers: Uint32, @"error": f32, x: f32, y: f32, }; pub const SDL_DollarGestureEvent = struct_SDL_DollarGestureEvent; pub const struct_SDL_DropEvent = extern struct { type: Uint32, timestamp: Uint32, file: [*c]u8, windowID: Uint32, }; pub const SDL_DropEvent = struct_SDL_DropEvent; pub const struct_SDL_SensorEvent = extern struct { type: Uint32, timestamp: Uint32, which: Sint32, data: [6]f32, }; pub const SDL_SensorEvent = struct_SDL_SensorEvent; pub const struct_SDL_QuitEvent = extern struct { type: Uint32, timestamp: Uint32, }; pub const SDL_QuitEvent = struct_SDL_QuitEvent; pub const struct_SDL_OSEvent = extern struct { type: Uint32, timestamp: Uint32, }; pub const SDL_OSEvent = struct_SDL_OSEvent; pub const struct_SDL_UserEvent = extern struct { type: Uint32, timestamp: Uint32, windowID: Uint32, code: Sint32, data1: ?*anyopaque, data2: ?*anyopaque, }; pub const SDL_UserEvent = struct_SDL_UserEvent; pub const struct_SDL_SysWMmsg = opaque {}; pub const SDL_SysWMmsg = struct_SDL_SysWMmsg; pub const struct_SDL_SysWMEvent = extern struct { type: Uint32, timestamp: Uint32, msg: ?*SDL_SysWMmsg, }; pub const SDL_SysWMEvent = struct_SDL_SysWMEvent; pub const union_SDL_Event = extern union { type: Uint32, common: SDL_CommonEvent, display: SDL_DisplayEvent, window: SDL_WindowEvent, key: SDL_KeyboardEvent, edit: SDL_TextEditingEvent, text: SDL_TextInputEvent, motion: SDL_MouseMotionEvent, button: SDL_MouseButtonEvent, wheel: SDL_MouseWheelEvent, jaxis: SDL_JoyAxisEvent, jball: SDL_JoyBallEvent, jhat: SDL_JoyHatEvent, jbutton: SDL_JoyButtonEvent, jdevice: SDL_JoyDeviceEvent, caxis: SDL_ControllerAxisEvent, cbutton: SDL_ControllerButtonEvent, cdevice: SDL_ControllerDeviceEvent, ctouchpad: SDL_ControllerTouchpadEvent, csensor: SDL_ControllerSensorEvent, adevice: SDL_AudioDeviceEvent, sensor: SDL_SensorEvent, quit: SDL_QuitEvent, user: SDL_UserEvent, syswm: SDL_SysWMEvent, tfinger: SDL_TouchFingerEvent, mgesture: SDL_MultiGestureEvent, dgesture: SDL_DollarGestureEvent, drop: SDL_DropEvent, padding: [56]Uint8, }; pub const SDL_Event = union_SDL_Event; pub const SDL_compile_time_assert_SDL_Event = [1]c_int; pub extern fn SDL_PumpEvents() void; pub const SDL_ADDEVENT = @enumToInt(enum_unnamed_66.SDL_ADDEVENT); pub const SDL_PEEKEVENT = @enumToInt(enum_unnamed_66.SDL_PEEKEVENT); pub const SDL_GETEVENT = @enumToInt(enum_unnamed_66.SDL_GETEVENT); const enum_unnamed_66 = enum(c_int) { SDL_ADDEVENT, SDL_PEEKEVENT, SDL_GETEVENT, _, }; pub const SDL_eventaction = enum_unnamed_66; pub extern fn SDL_PeepEvents(events: [*c]SDL_Event, numevents: c_int, action: SDL_eventaction, minType: Uint32, maxType: Uint32) c_int; pub extern fn SDL_HasEvent(@"type": Uint32) SDL_bool; pub extern fn SDL_HasEvents(minType: Uint32, maxType: Uint32) SDL_bool; pub extern fn SDL_FlushEvent(@"type": Uint32) void; pub extern fn SDL_FlushEvents(minType: Uint32, maxType: Uint32) void; pub extern fn SDL_PollEvent(event: [*c]SDL_Event) c_int; pub extern fn SDL_WaitEvent(event: [*c]SDL_Event) c_int; pub extern fn SDL_WaitEventTimeout(event: [*c]SDL_Event, timeout: c_int) c_int; pub extern fn SDL_PushEvent(event: [*c]SDL_Event) c_int; pub const SDL_EventFilter = ?fn (?*anyopaque, [*c]SDL_Event) callconv(.C) c_int; pub extern fn SDL_SetEventFilter(filter: SDL_EventFilter, userdata: ?*anyopaque) void; pub extern fn SDL_GetEventFilter(filter: [*c]SDL_EventFilter, userdata: [*c]?*anyopaque) SDL_bool; pub extern fn SDL_AddEventWatch(filter: SDL_EventFilter, userdata: ?*anyopaque) void; pub extern fn SDL_DelEventWatch(filter: SDL_EventFilter, userdata: ?*anyopaque) void; pub extern fn SDL_FilterEvents(filter: SDL_EventFilter, userdata: ?*anyopaque) void; pub extern fn SDL_EventState(@"type": Uint32, state: c_int) Uint8; pub extern fn SDL_RegisterEvents(numevents: c_int) Uint32; pub extern fn SDL_GetBasePath() [*c]u8; pub extern fn SDL_GetPrefPath(org: [*c]const u8, app: [*c]const u8) [*c]u8; pub const struct__SDL_Haptic = opaque {}; pub const SDL_Haptic = struct__SDL_Haptic; pub const struct_SDL_HapticDirection = extern struct { type: Uint8, dir: [3]Sint32, }; pub const SDL_HapticDirection = struct_SDL_HapticDirection; pub const struct_SDL_HapticConstant = extern struct { type: Uint16, direction: SDL_HapticDirection, length: Uint32, delay: Uint16, button: Uint16, interval: Uint16, level: Sint16, attack_length: Uint16, attack_level: Uint16, fade_length: Uint16, fade_level: Uint16, }; pub const SDL_HapticConstant = struct_SDL_HapticConstant; pub const struct_SDL_HapticPeriodic = extern struct { type: Uint16, direction: SDL_HapticDirection, length: Uint32, delay: Uint16, button: Uint16, interval: Uint16, period: Uint16, magnitude: Sint16, offset: Sint16, phase: Uint16, attack_length: Uint16, attack_level: Uint16, fade_length: Uint16, fade_level: Uint16, }; pub const SDL_HapticPeriodic = struct_SDL_HapticPeriodic; pub const struct_SDL_HapticCondition = extern struct { type: Uint16, direction: SDL_HapticDirection, length: Uint32, delay: Uint16, button: Uint16, interval: Uint16, right_sat: [3]Uint16, left_sat: [3]Uint16, right_coeff: [3]Sint16, left_coeff: [3]Sint16, deadband: [3]Uint16, center: [3]Sint16, }; pub const SDL_HapticCondition = struct_SDL_HapticCondition; pub const struct_SDL_HapticRamp = extern struct { type: Uint16, direction: SDL_HapticDirection, length: Uint32, delay: Uint16, button: Uint16, interval: Uint16, start: Sint16, end: Sint16, attack_length: Uint16, attack_level: Uint16, fade_length: Uint16, fade_level: Uint16, }; pub const SDL_HapticRamp = struct_SDL_HapticRamp; pub const struct_SDL_HapticLeftRight = extern struct { type: Uint16, length: Uint32, large_magnitude: Uint16, small_magnitude: Uint16, }; pub const SDL_HapticLeftRight = struct_SDL_HapticLeftRight; pub const struct_SDL_HapticCustom = extern struct { type: Uint16, direction: SDL_HapticDirection, length: Uint32, delay: Uint16, button: Uint16, interval: Uint16, channels: Uint8, period: Uint16, samples: Uint16, data: [*c]Uint16, attack_length: Uint16, attack_level: Uint16, fade_length: Uint16, fade_level: Uint16, }; pub const SDL_HapticCustom = struct_SDL_HapticCustom; pub const union_SDL_HapticEffect = extern union { type: Uint16, constant: SDL_HapticConstant, periodic: SDL_HapticPeriodic, condition: SDL_HapticCondition, ramp: SDL_HapticRamp, leftright: SDL_HapticLeftRight, custom: SDL_HapticCustom, }; pub const SDL_HapticEffect = union_SDL_HapticEffect; pub extern fn SDL_NumHaptics() c_int; pub extern fn SDL_HapticName(device_index: c_int) [*c]const u8; pub extern fn SDL_HapticOpen(device_index: c_int) ?*SDL_Haptic; pub extern fn SDL_HapticOpened(device_index: c_int) c_int; pub extern fn SDL_HapticIndex(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_MouseIsHaptic() c_int; pub extern fn SDL_HapticOpenFromMouse() ?*SDL_Haptic; pub extern fn SDL_JoystickIsHaptic(joystick: ?*SDL_Joystick) c_int; pub extern fn SDL_HapticOpenFromJoystick(joystick: ?*SDL_Joystick) ?*SDL_Haptic; pub extern fn SDL_HapticClose(haptic: ?*SDL_Haptic) void; pub extern fn SDL_HapticNumEffects(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_HapticNumEffectsPlaying(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_HapticQuery(haptic: ?*SDL_Haptic) c_uint; pub extern fn SDL_HapticNumAxes(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_HapticEffectSupported(haptic: ?*SDL_Haptic, effect: [*c]SDL_HapticEffect) c_int; pub extern fn SDL_HapticNewEffect(haptic: ?*SDL_Haptic, effect: [*c]SDL_HapticEffect) c_int; pub extern fn SDL_HapticUpdateEffect(haptic: ?*SDL_Haptic, effect: c_int, data: [*c]SDL_HapticEffect) c_int; pub extern fn SDL_HapticRunEffect(haptic: ?*SDL_Haptic, effect: c_int, iterations: Uint32) c_int; pub extern fn SDL_HapticStopEffect(haptic: ?*SDL_Haptic, effect: c_int) c_int; pub extern fn SDL_HapticDestroyEffect(haptic: ?*SDL_Haptic, effect: c_int) void; pub extern fn SDL_HapticGetEffectStatus(haptic: ?*SDL_Haptic, effect: c_int) c_int; pub extern fn SDL_HapticSetGain(haptic: ?*SDL_Haptic, gain: c_int) c_int; pub extern fn SDL_HapticSetAutocenter(haptic: ?*SDL_Haptic, autocenter: c_int) c_int; pub extern fn SDL_HapticPause(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_HapticUnpause(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_HapticStopAll(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_HapticRumbleSupported(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_HapticRumbleInit(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_HapticRumblePlay(haptic: ?*SDL_Haptic, strength: f32, length: Uint32) c_int; pub extern fn SDL_HapticRumbleStop(haptic: ?*SDL_Haptic) c_int; pub const SDL_HINT_DEFAULT = @enumToInt(enum_unnamed_67.SDL_HINT_DEFAULT); pub const SDL_HINT_NORMAL = @enumToInt(enum_unnamed_67.SDL_HINT_NORMAL); pub const SDL_HINT_OVERRIDE = @enumToInt(enum_unnamed_67.SDL_HINT_OVERRIDE); const enum_unnamed_67 = enum(c_int) { SDL_HINT_DEFAULT, SDL_HINT_NORMAL, SDL_HINT_OVERRIDE, _, }; pub const SDL_HintPriority = enum_unnamed_67; pub extern fn SDL_SetHintWithPriority(name: [*c]const u8, value: [*c]const u8, priority: SDL_HintPriority) SDL_bool; pub extern fn SDL_SetHint(name: [*c]const u8, value: [*c]const u8) SDL_bool; pub extern fn SDL_GetHint(name: [*c]const u8) [*c]const u8; pub extern fn SDL_GetHintBoolean(name: [*c]const u8, default_value: SDL_bool) SDL_bool; pub const SDL_HintCallback = ?fn (?*anyopaque, [*c]const u8, [*c]const u8, [*c]const u8) callconv(.C) void; pub extern fn SDL_AddHintCallback(name: [*c]const u8, callback: SDL_HintCallback, userdata: ?*anyopaque) void; pub extern fn SDL_DelHintCallback(name: [*c]const u8, callback: SDL_HintCallback, userdata: ?*anyopaque) void; pub extern fn SDL_ClearHints() void; pub extern fn SDL_LoadObject(sofile: [*c]const u8) ?*anyopaque; pub extern fn SDL_LoadFunction(handle: ?*anyopaque, name: [*c]const u8) ?*anyopaque; pub extern fn SDL_UnloadObject(handle: ?*anyopaque) void; pub const SDL_LOG_CATEGORY_APPLICATION = @enumToInt(enum_unnamed_68.SDL_LOG_CATEGORY_APPLICATION); pub const SDL_LOG_CATEGORY_ERROR = @enumToInt(enum_unnamed_68.SDL_LOG_CATEGORY_ERROR); pub const SDL_LOG_CATEGORY_ASSERT = @enumToInt(enum_unnamed_68.SDL_LOG_CATEGORY_ASSERT); pub const SDL_LOG_CATEGORY_SYSTEM = @enumToInt(enum_unnamed_68.SDL_LOG_CATEGORY_SYSTEM); pub const SDL_LOG_CATEGORY_AUDIO = @enumToInt(enum_unnamed_68.SDL_LOG_CATEGORY_AUDIO); pub const SDL_LOG_CATEGORY_VIDEO = @enumToInt(enum_unnamed_68.SDL_LOG_CATEGORY_VIDEO); pub const SDL_LOG_CATEGORY_RENDER = @enumToInt(enum_unnamed_68.SDL_LOG_CATEGORY_RENDER); pub const SDL_LOG_CATEGORY_INPUT = @enumToInt(enum_unnamed_68.SDL_LOG_CATEGORY_INPUT); pub const SDL_LOG_CATEGORY_TEST = @enumToInt(enum_unnamed_68.SDL_LOG_CATEGORY_TEST); pub const SDL_LOG_CATEGORY_RESERVED1 = @enumToInt(enum_unnamed_68.SDL_LOG_CATEGORY_RESERVED1); pub const SDL_LOG_CATEGORY_RESERVED2 = @enumToInt(enum_unnamed_68.SDL_LOG_CATEGORY_RESERVED2); pub const SDL_LOG_CATEGORY_RESERVED3 = @enumToInt(enum_unnamed_68.SDL_LOG_CATEGORY_RESERVED3); pub const SDL_LOG_CATEGORY_RESERVED4 = @enumToInt(enum_unnamed_68.SDL_LOG_CATEGORY_RESERVED4); pub const SDL_LOG_CATEGORY_RESERVED5 = @enumToInt(enum_unnamed_68.SDL_LOG_CATEGORY_RESERVED5); pub const SDL_LOG_CATEGORY_RESERVED6 = @enumToInt(enum_unnamed_68.SDL_LOG_CATEGORY_RESERVED6); pub const SDL_LOG_CATEGORY_RESERVED7 = @enumToInt(enum_unnamed_68.SDL_LOG_CATEGORY_RESERVED7); pub const SDL_LOG_CATEGORY_RESERVED8 = @enumToInt(enum_unnamed_68.SDL_LOG_CATEGORY_RESERVED8); pub const SDL_LOG_CATEGORY_RESERVED9 = @enumToInt(enum_unnamed_68.SDL_LOG_CATEGORY_RESERVED9); pub const SDL_LOG_CATEGORY_RESERVED10 = @enumToInt(enum_unnamed_68.SDL_LOG_CATEGORY_RESERVED10); pub const SDL_LOG_CATEGORY_CUSTOM = @enumToInt(enum_unnamed_68.SDL_LOG_CATEGORY_CUSTOM); const enum_unnamed_68 = enum(c_int) { SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_CATEGORY_ERROR, SDL_LOG_CATEGORY_ASSERT, SDL_LOG_CATEGORY_SYSTEM, SDL_LOG_CATEGORY_AUDIO, SDL_LOG_CATEGORY_VIDEO, SDL_LOG_CATEGORY_RENDER, SDL_LOG_CATEGORY_INPUT, SDL_LOG_CATEGORY_TEST, SDL_LOG_CATEGORY_RESERVED1, SDL_LOG_CATEGORY_RESERVED2, SDL_LOG_CATEGORY_RESERVED3, SDL_LOG_CATEGORY_RESERVED4, SDL_LOG_CATEGORY_RESERVED5, SDL_LOG_CATEGORY_RESERVED6, SDL_LOG_CATEGORY_RESERVED7, SDL_LOG_CATEGORY_RESERVED8, SDL_LOG_CATEGORY_RESERVED9, SDL_LOG_CATEGORY_RESERVED10, SDL_LOG_CATEGORY_CUSTOM, _, }; pub const SDL_LogCategory = enum_unnamed_68; pub const SDL_LOG_PRIORITY_VERBOSE = @enumToInt(enum_unnamed_69.SDL_LOG_PRIORITY_VERBOSE); pub const SDL_LOG_PRIORITY_DEBUG = @enumToInt(enum_unnamed_69.SDL_LOG_PRIORITY_DEBUG); pub const SDL_LOG_PRIORITY_INFO = @enumToInt(enum_unnamed_69.SDL_LOG_PRIORITY_INFO); pub const SDL_LOG_PRIORITY_WARN = @enumToInt(enum_unnamed_69.SDL_LOG_PRIORITY_WARN); pub const SDL_LOG_PRIORITY_ERROR = @enumToInt(enum_unnamed_69.SDL_LOG_PRIORITY_ERROR); pub const SDL_LOG_PRIORITY_CRITICAL = @enumToInt(enum_unnamed_69.SDL_LOG_PRIORITY_CRITICAL); pub const SDL_NUM_LOG_PRIORITIES = @enumToInt(enum_unnamed_69.SDL_NUM_LOG_PRIORITIES); const enum_unnamed_69 = enum(c_int) { SDL_LOG_PRIORITY_VERBOSE = 1, SDL_LOG_PRIORITY_DEBUG = 2, SDL_LOG_PRIORITY_INFO = 3, SDL_LOG_PRIORITY_WARN = 4, SDL_LOG_PRIORITY_ERROR = 5, SDL_LOG_PRIORITY_CRITICAL = 6, SDL_NUM_LOG_PRIORITIES = 7, _, }; pub const SDL_LogPriority = enum_unnamed_69; pub extern fn SDL_LogSetAllPriority(priority: SDL_LogPriority) void; pub extern fn SDL_LogSetPriority(category: c_int, priority: SDL_LogPriority) void; pub extern fn SDL_LogGetPriority(category: c_int) SDL_LogPriority; pub extern fn SDL_LogResetPriorities() void; pub extern fn SDL_Log(fmt: [*c]const u8, ...) void; pub extern fn SDL_LogVerbose(category: c_int, fmt: [*c]const u8, ...) void; pub extern fn SDL_LogDebug(category: c_int, fmt: [*c]const u8, ...) void; pub extern fn SDL_LogInfo(category: c_int, fmt: [*c]const u8, ...) void; pub extern fn SDL_LogWarn(category: c_int, fmt: [*c]const u8, ...) void; pub extern fn SDL_LogError(category: c_int, fmt: [*c]const u8, ...) void; pub extern fn SDL_LogCritical(category: c_int, fmt: [*c]const u8, ...) void; pub extern fn SDL_LogMessage(category: c_int, priority: SDL_LogPriority, fmt: [*c]const u8, ...) void; pub extern fn SDL_LogMessageV(category: c_int, priority: SDL_LogPriority, fmt: [*c]const u8, ap: [*c]struct___va_list_tag) void; pub const SDL_LogOutputFunction = ?fn (?*anyopaque, c_int, SDL_LogPriority, [*c]const u8) callconv(.C) void; pub extern fn SDL_LogGetOutputFunction(callback: [*c]SDL_LogOutputFunction, userdata: [*c]?*anyopaque) void; pub extern fn SDL_LogSetOutputFunction(callback: SDL_LogOutputFunction, userdata: ?*anyopaque) void; pub const SDL_MESSAGEBOX_ERROR = @enumToInt(enum_unnamed_70.SDL_MESSAGEBOX_ERROR); pub const SDL_MESSAGEBOX_WARNING = @enumToInt(enum_unnamed_70.SDL_MESSAGEBOX_WARNING); pub const SDL_MESSAGEBOX_INFORMATION = @enumToInt(enum_unnamed_70.SDL_MESSAGEBOX_INFORMATION); pub const SDL_MESSAGEBOX_BUTTONS_LEFT_TO_RIGHT = @enumToInt(enum_unnamed_70.SDL_MESSAGEBOX_BUTTONS_LEFT_TO_RIGHT); pub const SDL_MESSAGEBOX_BUTTONS_RIGHT_TO_LEFT = @enumToInt(enum_unnamed_70.SDL_MESSAGEBOX_BUTTONS_RIGHT_TO_LEFT); const enum_unnamed_70 = enum(c_int) { SDL_MESSAGEBOX_ERROR = 16, SDL_MESSAGEBOX_WARNING = 32, SDL_MESSAGEBOX_INFORMATION = 64, SDL_MESSAGEBOX_BUTTONS_LEFT_TO_RIGHT = 128, SDL_MESSAGEBOX_BUTTONS_RIGHT_TO_LEFT = 256, _, }; pub const SDL_MessageBoxFlags = enum_unnamed_70; pub const SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT = @enumToInt(enum_unnamed_71.SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT); pub const SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT = @enumToInt(enum_unnamed_71.SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT); const enum_unnamed_71 = enum(c_int) { SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT = 1, SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT = 2, _, }; pub const SDL_MessageBoxButtonFlags = enum_unnamed_71; pub const SDL_MessageBoxButtonData = extern struct { flags: Uint32, buttonid: c_int, text: [*c]const u8, }; pub const SDL_MessageBoxColor = extern struct { r: Uint8, g: Uint8, b: Uint8, }; pub const SDL_MESSAGEBOX_COLOR_BACKGROUND = @enumToInt(enum_unnamed_74.SDL_MESSAGEBOX_COLOR_BACKGROUND); pub const SDL_MESSAGEBOX_COLOR_TEXT = @enumToInt(enum_unnamed_74.SDL_MESSAGEBOX_COLOR_TEXT); pub const SDL_MESSAGEBOX_COLOR_BUTTON_BORDER = @enumToInt(enum_unnamed_74.SDL_MESSAGEBOX_COLOR_BUTTON_BORDER); pub const SDL_MESSAGEBOX_COLOR_BUTTON_BACKGROUND = @enumToInt(enum_unnamed_74.SDL_MESSAGEBOX_COLOR_BUTTON_BACKGROUND); pub const SDL_MESSAGEBOX_COLOR_BUTTON_SELECTED = @enumToInt(enum_unnamed_74.SDL_MESSAGEBOX_COLOR_BUTTON_SELECTED); pub const SDL_MESSAGEBOX_COLOR_MAX = @enumToInt(enum_unnamed_74.SDL_MESSAGEBOX_COLOR_MAX); const enum_unnamed_74 = enum(c_int) { SDL_MESSAGEBOX_COLOR_BACKGROUND, SDL_MESSAGEBOX_COLOR_TEXT, SDL_MESSAGEBOX_COLOR_BUTTON_BORDER, SDL_MESSAGEBOX_COLOR_BUTTON_BACKGROUND, SDL_MESSAGEBOX_COLOR_BUTTON_SELECTED, SDL_MESSAGEBOX_COLOR_MAX, _, }; pub const SDL_MessageBoxColorType = enum_unnamed_74; pub const SDL_MessageBoxColorScheme = extern struct { colors: [5]SDL_MessageBoxColor, }; pub const SDL_MessageBoxData = extern struct { flags: Uint32, window: ?*SDL_Window, title: [*c]const u8, message: [*c]const u8, numbuttons: c_int, buttons: [*c]const SDL_MessageBoxButtonData, colorScheme: [*c]const SDL_MessageBoxColorScheme, }; pub extern fn SDL_ShowMessageBox(messageboxdata: [*c]const SDL_MessageBoxData, buttonid: [*c]c_int) c_int; pub extern fn SDL_ShowSimpleMessageBox(flags: Uint32, title: [*c]const u8, message: [*c]const u8, window: ?*SDL_Window) c_int; pub const SDL_MetalView = ?*anyopaque; pub extern fn SDL_Metal_CreateView(window: ?*SDL_Window) SDL_MetalView; pub extern fn SDL_Metal_DestroyView(view: SDL_MetalView) void; pub extern fn SDL_Metal_GetLayer(view: SDL_MetalView) ?*anyopaque; pub extern fn SDL_Metal_GetDrawableSize(window: ?*SDL_Window, w: [*c]c_int, h: [*c]c_int) void; pub const SDL_POWERSTATE_UNKNOWN = @enumToInt(enum_unnamed_77.SDL_POWERSTATE_UNKNOWN); pub const SDL_POWERSTATE_ON_BATTERY = @enumToInt(enum_unnamed_77.SDL_POWERSTATE_ON_BATTERY); pub const SDL_POWERSTATE_NO_BATTERY = @enumToInt(enum_unnamed_77.SDL_POWERSTATE_NO_BATTERY); pub const SDL_POWERSTATE_CHARGING = @enumToInt(enum_unnamed_77.SDL_POWERSTATE_CHARGING); pub const SDL_POWERSTATE_CHARGED = @enumToInt(enum_unnamed_77.SDL_POWERSTATE_CHARGED); const enum_unnamed_77 = enum(c_int) { SDL_POWERSTATE_UNKNOWN, SDL_POWERSTATE_ON_BATTERY, SDL_POWERSTATE_NO_BATTERY, SDL_POWERSTATE_CHARGING, SDL_POWERSTATE_CHARGED, _, }; pub const SDL_PowerState = enum_unnamed_77; pub extern fn SDL_GetPowerInfo(secs: [*c]c_int, pct: [*c]c_int) SDL_PowerState; pub const SDL_RENDERER_SOFTWARE = @enumToInt(enum_unnamed_78.SDL_RENDERER_SOFTWARE); pub const SDL_RENDERER_ACCELERATED = @enumToInt(enum_unnamed_78.SDL_RENDERER_ACCELERATED); pub const SDL_RENDERER_PRESENTVSYNC = @enumToInt(enum_unnamed_78.SDL_RENDERER_PRESENTVSYNC); pub const SDL_RENDERER_TARGETTEXTURE = @enumToInt(enum_unnamed_78.SDL_RENDERER_TARGETTEXTURE); const enum_unnamed_78 = enum(c_int) { SDL_RENDERER_SOFTWARE = 1, SDL_RENDERER_ACCELERATED = 2, SDL_RENDERER_PRESENTVSYNC = 4, SDL_RENDERER_TARGETTEXTURE = 8, _, }; pub const SDL_RendererFlags = enum_unnamed_78; pub const struct_SDL_RendererInfo = extern struct { name: [*c]const u8, flags: Uint32, num_texture_formats: Uint32, texture_formats: [16]Uint32, max_texture_width: c_int, max_texture_height: c_int, }; pub const SDL_RendererInfo = struct_SDL_RendererInfo; pub const SDL_ScaleModeNearest = @enumToInt(enum_unnamed_79.SDL_ScaleModeNearest); pub const SDL_ScaleModeLinear = @enumToInt(enum_unnamed_79.SDL_ScaleModeLinear); pub const SDL_ScaleModeBest = @enumToInt(enum_unnamed_79.SDL_ScaleModeBest); const enum_unnamed_79 = enum(c_int) { SDL_ScaleModeNearest, SDL_ScaleModeLinear, SDL_ScaleModeBest, _, }; pub const SDL_ScaleMode = enum_unnamed_79; pub const SDL_TEXTUREACCESS_STATIC = @enumToInt(enum_unnamed_80.SDL_TEXTUREACCESS_STATIC); pub const SDL_TEXTUREACCESS_STREAMING = @enumToInt(enum_unnamed_80.SDL_TEXTUREACCESS_STREAMING); pub const SDL_TEXTUREACCESS_TARGET = @enumToInt(enum_unnamed_80.SDL_TEXTUREACCESS_TARGET); const enum_unnamed_80 = enum(c_int) { SDL_TEXTUREACCESS_STATIC, SDL_TEXTUREACCESS_STREAMING, SDL_TEXTUREACCESS_TARGET, _, }; pub const SDL_TextureAccess = enum_unnamed_80; pub const SDL_TEXTUREMODULATE_NONE = @enumToInt(enum_unnamed_81.SDL_TEXTUREMODULATE_NONE); pub const SDL_TEXTUREMODULATE_COLOR = @enumToInt(enum_unnamed_81.SDL_TEXTUREMODULATE_COLOR); pub const SDL_TEXTUREMODULATE_ALPHA = @enumToInt(enum_unnamed_81.SDL_TEXTUREMODULATE_ALPHA); const enum_unnamed_81 = enum(c_int) { SDL_TEXTUREMODULATE_NONE = 0, SDL_TEXTUREMODULATE_COLOR = 1, SDL_TEXTUREMODULATE_ALPHA = 2, _, }; pub const SDL_TextureModulate = enum_unnamed_81; pub const SDL_FLIP_NONE = @enumToInt(enum_unnamed_82.SDL_FLIP_NONE); pub const SDL_FLIP_HORIZONTAL = @enumToInt(enum_unnamed_82.SDL_FLIP_HORIZONTAL); pub const SDL_FLIP_VERTICAL = @enumToInt(enum_unnamed_82.SDL_FLIP_VERTICAL); const enum_unnamed_82 = enum(c_int) { SDL_FLIP_NONE = 0, SDL_FLIP_HORIZONTAL = 1, SDL_FLIP_VERTICAL = 2, _, }; pub const SDL_RendererFlip = enum_unnamed_82; pub const struct_SDL_Renderer = opaque {}; pub const SDL_Renderer = struct_SDL_Renderer; pub const struct_SDL_Texture = opaque {}; pub const SDL_Texture = struct_SDL_Texture; pub extern fn SDL_GetNumRenderDrivers() c_int; pub extern fn SDL_GetRenderDriverInfo(index: c_int, info: [*c]SDL_RendererInfo) c_int; pub extern fn SDL_CreateWindowAndRenderer(width: c_int, height: c_int, window_flags: Uint32, window: [*c]?*SDL_Window, renderer: [*c]?*SDL_Renderer) c_int; pub extern fn SDL_CreateRenderer(window: ?*SDL_Window, index: c_int, flags: Uint32) ?*SDL_Renderer; pub extern fn SDL_CreateSoftwareRenderer(surface: [*c]SDL_Surface) ?*SDL_Renderer; pub extern fn SDL_GetRenderer(window: ?*SDL_Window) ?*SDL_Renderer; pub extern fn SDL_GetRendererInfo(renderer: ?*SDL_Renderer, info: [*c]SDL_RendererInfo) c_int; pub extern fn SDL_GetRendererOutputSize(renderer: ?*SDL_Renderer, w: [*c]c_int, h: [*c]c_int) c_int; pub extern fn SDL_CreateTexture(renderer: ?*SDL_Renderer, format: Uint32, access: c_int, w: c_int, h: c_int) ?*SDL_Texture; pub extern fn SDL_CreateTextureFromSurface(renderer: ?*SDL_Renderer, surface: [*c]SDL_Surface) ?*SDL_Texture; pub extern fn SDL_QueryTexture(texture: ?*SDL_Texture, format: [*c]Uint32, access: [*c]c_int, w: [*c]c_int, h: [*c]c_int) c_int; pub extern fn SDL_SetTextureColorMod(texture: ?*SDL_Texture, r: Uint8, g: Uint8, b: Uint8) c_int; pub extern fn SDL_GetTextureColorMod(texture: ?*SDL_Texture, r: [*c]Uint8, g: [*c]Uint8, b: [*c]Uint8) c_int; pub extern fn SDL_SetTextureAlphaMod(texture: ?*SDL_Texture, alpha: Uint8) c_int; pub extern fn SDL_GetTextureAlphaMod(texture: ?*SDL_Texture, alpha: [*c]Uint8) c_int; pub extern fn SDL_SetTextureBlendMode(texture: ?*SDL_Texture, blendMode: SDL_BlendMode) c_int; pub extern fn SDL_GetTextureBlendMode(texture: ?*SDL_Texture, blendMode: [*c]SDL_BlendMode) c_int; pub extern fn SDL_SetTextureScaleMode(texture: ?*SDL_Texture, scaleMode: SDL_ScaleMode) c_int; pub extern fn SDL_GetTextureScaleMode(texture: ?*SDL_Texture, scaleMode: [*c]SDL_ScaleMode) c_int; pub extern fn SDL_UpdateTexture(texture: ?*SDL_Texture, rect: [*c]const SDL_Rect, pixels: ?*const anyopaque, pitch: c_int) c_int; pub extern fn SDL_UpdateYUVTexture(texture: ?*SDL_Texture, rect: [*c]const SDL_Rect, Yplane: [*c]const Uint8, Ypitch: c_int, Uplane: [*c]const Uint8, Upitch: c_int, Vplane: [*c]const Uint8, Vpitch: c_int) c_int; pub extern fn SDL_UpdateNVTexture(texture: ?*SDL_Texture, rect: [*c]const SDL_Rect, Yplane: [*c]const Uint8, Ypitch: c_int, UVplane: [*c]const Uint8, UVpitch: c_int) c_int; pub extern fn SDL_LockTexture(texture: ?*SDL_Texture, rect: [*c]const SDL_Rect, pixels: [*c]?*anyopaque, pitch: [*c]c_int) c_int; pub extern fn SDL_LockTextureToSurface(texture: ?*SDL_Texture, rect: [*c]const SDL_Rect, surface: [*c][*c]SDL_Surface) c_int; pub extern fn SDL_UnlockTexture(texture: ?*SDL_Texture) void; pub extern fn SDL_RenderTargetSupported(renderer: ?*SDL_Renderer) SDL_bool; pub extern fn SDL_SetRenderTarget(renderer: ?*SDL_Renderer, texture: ?*SDL_Texture) c_int; pub extern fn SDL_GetRenderTarget(renderer: ?*SDL_Renderer) ?*SDL_Texture; pub extern fn SDL_RenderSetLogicalSize(renderer: ?*SDL_Renderer, w: c_int, h: c_int) c_int; pub extern fn SDL_RenderGetLogicalSize(renderer: ?*SDL_Renderer, w: [*c]c_int, h: [*c]c_int) void; pub extern fn SDL_RenderSetIntegerScale(renderer: ?*SDL_Renderer, enable: SDL_bool) c_int; pub extern fn SDL_RenderGetIntegerScale(renderer: ?*SDL_Renderer) SDL_bool; pub extern fn SDL_RenderSetViewport(renderer: ?*SDL_Renderer, rect: [*c]const SDL_Rect) c_int; pub extern fn SDL_RenderGetViewport(renderer: ?*SDL_Renderer, rect: [*c]SDL_Rect) void; pub extern fn SDL_RenderSetClipRect(renderer: ?*SDL_Renderer, rect: [*c]const SDL_Rect) c_int; pub extern fn SDL_RenderGetClipRect(renderer: ?*SDL_Renderer, rect: [*c]SDL_Rect) void; pub extern fn SDL_RenderIsClipEnabled(renderer: ?*SDL_Renderer) SDL_bool; pub extern fn SDL_RenderSetScale(renderer: ?*SDL_Renderer, scaleX: f32, scaleY: f32) c_int; pub extern fn SDL_RenderGetScale(renderer: ?*SDL_Renderer, scaleX: [*c]f32, scaleY: [*c]f32) void; pub extern fn SDL_SetRenderDrawColor(renderer: ?*SDL_Renderer, r: Uint8, g: Uint8, b: Uint8, a: Uint8) c_int; pub extern fn SDL_GetRenderDrawColor(renderer: ?*SDL_Renderer, r: [*c]Uint8, g: [*c]Uint8, b: [*c]Uint8, a: [*c]Uint8) c_int; pub extern fn SDL_SetRenderDrawBlendMode(renderer: ?*SDL_Renderer, blendMode: SDL_BlendMode) c_int; pub extern fn SDL_GetRenderDrawBlendMode(renderer: ?*SDL_Renderer, blendMode: [*c]SDL_BlendMode) c_int; pub extern fn SDL_RenderClear(renderer: ?*SDL_Renderer) c_int; pub extern fn SDL_RenderDrawPoint(renderer: ?*SDL_Renderer, x: c_int, y: c_int) c_int; pub extern fn SDL_RenderDrawPoints(renderer: ?*SDL_Renderer, points: [*c]const SDL_Point, count: c_int) c_int; pub extern fn SDL_RenderDrawLine(renderer: ?*SDL_Renderer, x1: c_int, y1: c_int, x2: c_int, y2: c_int) c_int; pub extern fn SDL_RenderDrawLines(renderer: ?*SDL_Renderer, points: [*c]const SDL_Point, count: c_int) c_int; pub extern fn SDL_RenderDrawRect(renderer: ?*SDL_Renderer, rect: [*c]const SDL_Rect) c_int; pub extern fn SDL_RenderDrawRects(renderer: ?*SDL_Renderer, rects: [*c]const SDL_Rect, count: c_int) c_int; pub extern fn SDL_RenderFillRect(renderer: ?*SDL_Renderer, rect: [*c]const SDL_Rect) c_int; pub extern fn SDL_RenderFillRects(renderer: ?*SDL_Renderer, rects: [*c]const SDL_Rect, count: c_int) c_int; pub extern fn SDL_RenderCopy(renderer: ?*SDL_Renderer, texture: ?*SDL_Texture, srcrect: [*c]const SDL_Rect, dstrect: [*c]const SDL_Rect) c_int; pub extern fn SDL_RenderCopyEx(renderer: ?*SDL_Renderer, texture: ?*SDL_Texture, srcrect: [*c]const SDL_Rect, dstrect: [*c]const SDL_Rect, angle: f64, center: [*c]const SDL_Point, flip: SDL_RendererFlip) c_int; pub extern fn SDL_RenderDrawPointF(renderer: ?*SDL_Renderer, x: f32, y: f32) c_int; pub extern fn SDL_RenderDrawPointsF(renderer: ?*SDL_Renderer, points: [*c]const SDL_FPoint, count: c_int) c_int; pub extern fn SDL_RenderDrawLineF(renderer: ?*SDL_Renderer, x1: f32, y1: f32, x2: f32, y2: f32) c_int; pub extern fn SDL_RenderDrawLinesF(renderer: ?*SDL_Renderer, points: [*c]const SDL_FPoint, count: c_int) c_int; pub extern fn SDL_RenderDrawRectF(renderer: ?*SDL_Renderer, rect: [*c]const SDL_FRect) c_int; pub extern fn SDL_RenderDrawRectsF(renderer: ?*SDL_Renderer, rects: [*c]const SDL_FRect, count: c_int) c_int; pub extern fn SDL_RenderFillRectF(renderer: ?*SDL_Renderer, rect: [*c]const SDL_FRect) c_int; pub extern fn SDL_RenderFillRectsF(renderer: ?*SDL_Renderer, rects: [*c]const SDL_FRect, count: c_int) c_int; pub extern fn SDL_RenderCopyF(renderer: ?*SDL_Renderer, texture: ?*SDL_Texture, srcrect: [*c]const SDL_Rect, dstrect: [*c]const SDL_FRect) c_int; pub extern fn SDL_RenderCopyExF(renderer: ?*SDL_Renderer, texture: ?*SDL_Texture, srcrect: [*c]const SDL_Rect, dstrect: [*c]const SDL_FRect, angle: f64, center: [*c]const SDL_FPoint, flip: SDL_RendererFlip) c_int; pub extern fn SDL_RenderReadPixels(renderer: ?*SDL_Renderer, rect: [*c]const SDL_Rect, format: Uint32, pixels: ?*anyopaque, pitch: c_int) c_int; pub extern fn SDL_RenderPresent(renderer: ?*SDL_Renderer) void; pub extern fn SDL_DestroyTexture(texture: ?*SDL_Texture) void; pub extern fn SDL_DestroyRenderer(renderer: ?*SDL_Renderer) void; pub extern fn SDL_RenderFlush(renderer: ?*SDL_Renderer) c_int; pub extern fn SDL_GL_BindTexture(texture: ?*SDL_Texture, texw: [*c]f32, texh: [*c]f32) c_int; pub extern fn SDL_GL_UnbindTexture(texture: ?*SDL_Texture) c_int; pub extern fn SDL_RenderGetMetalLayer(renderer: ?*SDL_Renderer) ?*anyopaque; pub extern fn SDL_RenderGetMetalCommandEncoder(renderer: ?*SDL_Renderer) ?*anyopaque; pub extern fn SDL_CreateShapedWindow(title: [*c]const u8, x: c_uint, y: c_uint, w: c_uint, h: c_uint, flags: Uint32) ?*SDL_Window; pub extern fn SDL_IsShapedWindow(window: ?*const SDL_Window) SDL_bool; pub const ShapeModeDefault = @enumToInt(enum_unnamed_84.ShapeModeDefault); pub const ShapeModeBinarizeAlpha = @enumToInt(enum_unnamed_84.ShapeModeBinarizeAlpha); pub const ShapeModeReverseBinarizeAlpha = @enumToInt(enum_unnamed_84.ShapeModeReverseBinarizeAlpha); pub const ShapeModeColorKey = @enumToInt(enum_unnamed_84.ShapeModeColorKey); const enum_unnamed_84 = enum(c_int) { ShapeModeDefault, ShapeModeBinarizeAlpha, ShapeModeReverseBinarizeAlpha, ShapeModeColorKey, _, }; pub const WindowShapeMode = enum_unnamed_84; pub const SDL_WindowShapeParams = extern union { binarizationCutoff: Uint8, colorKey: SDL_Color, }; pub const struct_SDL_WindowShapeMode = extern struct { mode: WindowShapeMode, parameters: SDL_WindowShapeParams, }; pub const SDL_WindowShapeMode = struct_SDL_WindowShapeMode; pub extern fn SDL_SetWindowShape(window: ?*SDL_Window, shape: [*c]SDL_Surface, shape_mode: [*c]SDL_WindowShapeMode) c_int; pub extern fn SDL_GetShapedWindowMode(window: ?*SDL_Window, shape_mode: [*c]SDL_WindowShapeMode) c_int; pub extern fn SDL_LinuxSetThreadPriority(threadID: Sint64, priority: c_int) c_int; pub extern fn SDL_IsTablet() SDL_bool; pub extern fn SDL_OnApplicationWillTerminate() void; pub extern fn SDL_OnApplicationDidReceiveMemoryWarning() void; pub extern fn SDL_OnApplicationWillResignActive() void; pub extern fn SDL_OnApplicationDidEnterBackground() void; pub extern fn SDL_OnApplicationWillEnterForeground() void; pub extern fn SDL_OnApplicationDidBecomeActive() void; pub extern fn SDL_GetTicks() Uint32; pub extern fn SDL_GetPerformanceCounter() Uint64; pub extern fn SDL_GetPerformanceFrequency() Uint64; pub extern fn SDL_Delay(ms: Uint32) void; pub const SDL_TimerCallback = ?fn (Uint32, ?*anyopaque) callconv(.C) Uint32; pub const SDL_TimerID = c_int; pub extern fn SDL_AddTimer(interval: Uint32, callback: SDL_TimerCallback, param: ?*anyopaque) SDL_TimerID; pub extern fn SDL_RemoveTimer(id: SDL_TimerID) SDL_bool; pub const struct_SDL_version = extern struct { major: Uint8, minor: Uint8, patch: Uint8, }; pub const SDL_version = struct_SDL_version; pub extern fn SDL_GetVersion(ver: [*c]SDL_version) void; pub extern fn SDL_GetRevision() [*c]const u8; pub extern fn SDL_GetRevisionNumber() c_int; pub const struct_SDL_Locale = extern struct { language: [*c]const u8, country: [*c]const u8, }; pub const SDL_Locale = struct_SDL_Locale; pub extern fn SDL_GetPreferredLocales() [*c]SDL_Locale; pub extern fn SDL_OpenURL(url: [*c]const u8) c_int; pub extern fn SDL_Init(flags: Uint32) c_int; pub extern fn SDL_InitSubSystem(flags: Uint32) c_int; pub extern fn SDL_QuitSubSystem(flags: Uint32) void; pub extern fn SDL_WasInit(flags: Uint32) Uint32; pub extern fn SDL_Quit() void; pub const SDL_arraysize = @compileError("unable to translate C expr: expected ')'"); // /usr/include/SDL2/SDL_stdinc.h:121:9 pub const SDL_STRINGIFY_ARG = @compileError("unable to translate C expr: unexpected token .Hash"); // /usr/include/SDL2/SDL_stdinc.h:129:9 pub const SDL_IN_BYTECAP = @compileError("unable to translate C expr: unexpected token .Eof"); // /usr/include/SDL2/SDL_stdinc.h:328:9 pub const SDL_INOUT_Z_CAP = @compileError("unable to translate C expr: unexpected token .Eof"); // /usr/include/SDL2/SDL_stdinc.h:329:9 pub const SDL_OUT_Z_CAP = @compileError("unable to translate C expr: unexpected token .Eof"); // /usr/include/SDL2/SDL_stdinc.h:330:9 pub const SDL_OUT_CAP = @compileError("unable to translate C expr: unexpected token .Eof"); // /usr/include/SDL2/SDL_stdinc.h:331:9 pub const SDL_OUT_BYTECAP = @compileError("unable to translate C expr: unexpected token .Eof"); // /usr/include/SDL2/SDL_stdinc.h:332:9 pub const SDL_OUT_Z_BYTECAP = @compileError("unable to translate C expr: unexpected token .Eof"); // /usr/include/SDL2/SDL_stdinc.h:333:9 pub const SDL_PRINTF_VARARG_FUNC = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // /usr/include/SDL2/SDL_stdinc.h:338:9 pub const SDL_SCANF_VARARG_FUNC = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // /usr/include/SDL2/SDL_stdinc.h:339:9 pub const SDL_COMPILE_TIME_ASSERT = @compileError("unable to translate macro: undefined identifier `SDL_compile_time_assert_`"); // /usr/include/SDL2/SDL_stdinc.h:346:9 pub const SDL_stack_alloc = @compileError("unable to translate C expr: unexpected token .RParen"); // /usr/include/SDL2/SDL_stdinc.h:388:9 pub const SDL_stack_free = @compileError("unable to translate C expr: unexpected token .Eof"); // /usr/include/SDL2/SDL_stdinc.h:389:9 pub const SDL_zero = @compileError("unable to translate C expr: unexpected token .LParen"); // /usr/include/SDL2/SDL_stdinc.h:457:9 pub const SDL_zerop = @compileError("unable to translate C expr: unexpected token .Asterisk"); // /usr/include/SDL2/SDL_stdinc.h:458:9 pub const SDL_zeroa = @compileError("unable to translate C expr: unexpected token .LParen"); // /usr/include/SDL2/SDL_stdinc.h:459:9 pub const SDL_TriggerBreakpoint = @compileError("unable to translate macro: undefined identifier `__asm__`"); // /usr/include/SDL2/SDL_assert.h:55:13 pub const SDL_FUNCTION = @compileError("unable to translate macro: undefined identifier `__func__`"); // /usr/include/SDL2/SDL_assert.h:71:12 pub const SDL_FILE = @compileError("unable to translate macro: undefined identifier `__FILE__`"); // /usr/include/SDL2/SDL_assert.h:77:9 pub const SDL_LINE = @compileError("unable to translate macro: undefined identifier `__LINE__`"); // /usr/include/SDL2/SDL_assert.h:78:9 pub const SDL_disabled_assert = @compileError("unable to translate C expr: unexpected token .Keyword_do"); // /usr/include/SDL2/SDL_assert.h:103:9 pub const SDL_enabled_assert = @compileError("unable to translate macro: undefined identifier `sdl_assert_data`"); // /usr/include/SDL2/SDL_assert.h:149:9 pub const SDL_CompilerBarrier = @compileError("unable to translate macro: undefined identifier `__asm__`"); // /usr/include/SDL2/SDL_atomic.h:149:9 pub const SDL_AUDIOCVT_PACKED = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // /usr/include/SDL2/SDL_audio.h:226:9 pub const SDL_AUDIO_DRIVER_ALSA = @as(c_int, 1); pub const SDL_AUDIO_DRIVER_ALSA_DYNAMIC = "libasound.so.2"; pub const SDL_AUDIO_DRIVER_DISK = @as(c_int, 1); pub const SDL_AUDIO_DRIVER_DUMMY = @as(c_int, 1); pub const SDL_AUDIO_DRIVER_JACK = @as(c_int, 1); pub const SDL_AUDIO_DRIVER_JACK_DYNAMIC = "libjack.so.0"; pub const SDL_AUDIO_DRIVER_OSS = @as(c_int, 1); pub const SDL_AUDIO_DRIVER_PIPEWIRE = @as(c_int, 1); pub const SDL_AUDIO_DRIVER_PIPEWIRE_DYNAMIC = "libpipewire-0.3.so.0"; pub const SDL_AUDIO_DRIVER_PULSEAUDIO = @as(c_int, 1); pub const SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC = "libpulse-simple.so.0"; pub const SDL_INPUT_LINUXEV = @as(c_int, 1); pub const SDL_INPUT_LINUXKD = @as(c_int, 1); pub const SDL_JOYSTICK_LINUX = @as(c_int, 1); pub const SDL_JOYSTICK_HIDAPI = @as(c_int, 1); pub const SDL_JOYSTICK_VIRTUAL = @as(c_int, 1); pub const SDL_HAPTIC_LINUX = @as(c_int, 1); pub const SDL_LIBUSB_DYNAMIC = ""; pub const SDL_SENSOR_DUMMY = @as(c_int, 1); pub const SDL_LOADSO_DLOPEN = @as(c_int, 1); pub const SDL_THREAD_PTHREAD = @as(c_int, 1); pub const SDL_THREAD_PTHREAD_RECURSIVE_MUTEX = @as(c_int, 1); pub const SDL_TIMER_UNIX = @as(c_int, 1); pub const SDL_VIDEO_DRIVER_DUMMY = @as(c_int, 1); pub const SDL_VIDEO_DRIVER_WAYLAND = @as(c_int, 1); pub const SDL_VIDEO_DRIVER_KMSDRM = @as(c_int, 1); pub const SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC = "libdrm.so.2"; pub const SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC_GBM = "libgbm.so.1"; pub const SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH = @as(c_int, 1); pub const SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC = "libwayland-client.so.0"; pub const SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_EGL = "libwayland-egl.so.1"; pub const SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_CURSOR = "libwayland-cursor.so.0"; pub const SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_XKBCOMMON = "libxkbcommon.so.0"; pub const SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_LIBDECOR = "libdecor-0.so.0"; pub const SDL_VIDEO_DRIVER_X11 = @as(c_int, 1); pub const SDL_VIDEO_DRIVER_X11_DYNAMIC = "libX11.so.6"; pub const SDL_VIDEO_DRIVER_X11_DYNAMIC_XEXT = "libXext.so.6"; pub const SDL_VIDEO_DRIVER_X11_DYNAMIC_XCURSOR = "libXcursor.so.1"; pub const SDL_VIDEO_DRIVER_X11_DYNAMIC_XINERAMA = "libXinerama.so.1"; pub const SDL_VIDEO_DRIVER_X11_DYNAMIC_XINPUT2 = "libXi.so.6"; pub const SDL_VIDEO_DRIVER_X11_DYNAMIC_XRANDR = "libXrandr.so.2"; pub const SDL_VIDEO_DRIVER_X11_DYNAMIC_XSS = "libXss.so.1"; pub const SDL_VIDEO_DRIVER_X11_DYNAMIC_XVIDMODE = "libXxf86vm.so.1"; pub const SDL_VIDEO_DRIVER_X11_XCURSOR = @as(c_int, 1); pub const SDL_VIDEO_DRIVER_X11_XINERAMA = @as(c_int, 1); pub const SDL_VIDEO_DRIVER_X11_XINPUT2 = @as(c_int, 1); pub const SDL_VIDEO_DRIVER_X11_XINPUT2_SUPPORTS_MULTITOUCH = @as(c_int, 1); pub const SDL_VIDEO_DRIVER_X11_XRANDR = @as(c_int, 1); pub const SDL_VIDEO_DRIVER_X11_XSCRNSAVER = @as(c_int, 1); pub const SDL_VIDEO_DRIVER_X11_XSHAPE = @as(c_int, 1); pub const SDL_VIDEO_DRIVER_X11_XVIDMODE = @as(c_int, 1); pub const SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS = @as(c_int, 1); pub const SDL_VIDEO_DRIVER_X11_CONST_PARAM_XEXTADDDISPLAY = @as(c_int, 1); pub const SDL_VIDEO_DRIVER_X11_HAS_XKBKEYCODETOKEYSYM = @as(c_int, 1); pub const SDL_VIDEO_RENDER_OGL = @as(c_int, 1); pub const SDL_VIDEO_RENDER_OGL_ES2 = @as(c_int, 1); pub const SDL_VIDEO_OPENGL = @as(c_int, 1); pub const SDL_VIDEO_OPENGL_ES2 = @as(c_int, 1); pub const SDL_VIDEO_OPENGL_GLX = @as(c_int, 1); pub const SDL_VIDEO_OPENGL_EGL = @as(c_int, 1); pub const SDL_VIDEO_VULKAN = @as(c_int, 1); pub const SDL_POWER_LINUX = @as(c_int, 1); pub const SDL_FILESYSTEM_UNIX = @as(c_int, 1); pub const SDL_ASSEMBLY_ROUTINES = @as(c_int, 1); pub const SDL_LIBSAMPLERATE_DYNAMIC = "libsamplerate.so.0"; pub inline fn SDL_TABLESIZE(table: anytype) @TypeOf(SDL_arraysize(table)) { return SDL_arraysize(table); } pub inline fn SDL_reinterpret_cast(@"type": anytype, expression: anytype) @TypeOf(@"type"(expression)) { return @"type"(expression); } pub inline fn SDL_static_cast(@"type": anytype, expression: anytype) @TypeOf(@"type"(expression)) { return @"type"(expression); } pub inline fn SDL_const_cast(@"type": anytype, expression: anytype) @TypeOf(@"type"(expression)) { return @"type"(expression); } pub inline fn SDL_FOURCC(A: anytype, B: anytype, C: anytype, D: anytype) @TypeOf((((SDL_static_cast(Uint32, SDL_static_cast(Uint8, A)) << @as(c_int, 0)) | (SDL_static_cast(Uint32, SDL_static_cast(Uint8, B)) << @as(c_int, 8))) | (SDL_static_cast(Uint32, SDL_static_cast(Uint8, C)) << @as(c_int, 16))) | (SDL_static_cast(Uint32, SDL_static_cast(Uint8, D)) << @as(c_int, 24))) { return (((SDL_static_cast(Uint32, SDL_static_cast(Uint8, A)) << @as(c_int, 0)) | (SDL_static_cast(Uint32, SDL_static_cast(Uint8, B)) << @as(c_int, 8))) | (SDL_static_cast(Uint32, SDL_static_cast(Uint8, C)) << @as(c_int, 16))) | (SDL_static_cast(Uint32, SDL_static_cast(Uint8, D)) << @as(c_int, 24)); } pub const SDL_MAX_SINT8 = @import("std").zig.c_translation.cast(Sint8, @as(c_int, 0x7F)); pub const SDL_MIN_SINT8 = @import("std").zig.c_translation.cast(Sint8, ~@as(c_int, 0x7F)); pub const SDL_MAX_UINT8 = @import("std").zig.c_translation.cast(Uint8, @as(c_int, 0xFF)); pub const SDL_MIN_UINT8 = @import("std").zig.c_translation.cast(Uint8, @as(c_int, 0x00)); pub const SDL_MAX_SINT16 = @import("std").zig.c_translation.cast(Sint16, @as(c_int, 0x7FFF)); pub const SDL_MIN_SINT16 = @import("std").zig.c_translation.cast(Sint16, ~@as(c_int, 0x7FFF)); pub const SDL_MAX_UINT16 = @import("std").zig.c_translation.cast(Uint16, @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFF, .hexadecimal)); pub const SDL_MIN_UINT16 = @import("std").zig.c_translation.cast(Uint16, @as(c_int, 0x0000)); pub const SDL_MAX_SINT32 = @import("std").zig.c_translation.cast(Sint32, @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x7FFFFFFF, .hexadecimal)); pub const SDL_MIN_SINT32 = @import("std").zig.c_translation.cast(Sint32, ~@import("std").zig.c_translation.promoteIntLiteral(c_int, 0x7FFFFFFF, .hexadecimal)); pub const SDL_MAX_UINT32 = @import("std").zig.c_translation.cast(Uint32, @import("std").zig.c_translation.promoteIntLiteral(c_uint, 0xFFFFFFFF, .hexadecimal)); pub const SDL_MIN_UINT32 = @import("std").zig.c_translation.cast(Uint32, @as(c_int, 0x00000000)); pub const SDL_MAX_SINT64 = @import("std").zig.c_translation.cast(Sint64, @as(c_longlong, 0x7FFFFFFFFFFFFFFF)); pub const SDL_MIN_SINT64 = @import("std").zig.c_translation.cast(Sint64, ~@as(c_longlong, 0x7FFFFFFFFFFFFFFF)); pub const SDL_MAX_UINT64 = @import("std").zig.c_translation.cast(Uint64, @as(c_ulonglong, 0xFFFFFFFFFFFFFFFF)); pub const SDL_MIN_UINT64 = @import("std").zig.c_translation.cast(Uint64, @as(c_ulonglong, 0x0000000000000000)); pub const SDL_PRIs64 = "ld"; pub const SDL_PRIu64 = PRIu64; pub const SDL_PRIx64 = PRIx64; pub const SDL_PRIX64 = PRIX64; pub const SDL_PRIs32 = PRId32; pub const SDL_PRIu32 = PRIu32; pub const SDL_PRIx32 = PRIx32; pub const SDL_PRIX32 = PRIX32; pub const SDL_PRINTF_FORMAT_STRING = ""; pub const SDL_SCANF_FORMAT_STRING = ""; pub inline fn SDL_min(x: anytype, y: anytype) @TypeOf(if (x < y) x else y) { return if (x < y) x else y; } pub inline fn SDL_max(x: anytype, y: anytype) @TypeOf(if (x > y) x else y) { return if (x > y) x else y; } pub const SDL_ICONV_ERROR = @import("std").zig.c_translation.cast(usize, -@as(c_int, 1)); pub const SDL_ICONV_E2BIG = @import("std").zig.c_translation.cast(usize, -@as(c_int, 2)); pub const SDL_ICONV_EILSEQ = @import("std").zig.c_translation.cast(usize, -@as(c_int, 3)); pub const SDL_ICONV_EINVAL = @import("std").zig.c_translation.cast(usize, -@as(c_int, 4)); pub inline fn SDL_iconv_utf8_locale(S: anytype) @TypeOf(SDL_iconv_string("", "UTF-8", S, SDL_strlen(S) + @as(c_int, 1))) { return SDL_iconv_string("", "UTF-8", S, SDL_strlen(S) + @as(c_int, 1)); } pub inline fn SDL_iconv_utf8_ucs2(S: anytype) [*c]Uint16 { return @import("std").zig.c_translation.cast([*c]Uint16, SDL_iconv_string("UCS-2-INTERNAL", "UTF-8", S, SDL_strlen(S) + @as(c_int, 1))); } pub inline fn SDL_iconv_utf8_ucs4(S: anytype) [*c]Uint32 { return @import("std").zig.c_translation.cast([*c]Uint32, SDL_iconv_string("UCS-4-INTERNAL", "UTF-8", S, SDL_strlen(S) + @as(c_int, 1))); } pub const SDLMAIN_DECLSPEC = ""; pub const SDL_assert_h_ = ""; pub const SDL_ASSERT_LEVEL = @as(c_int, 2); pub const SDL_NULL_WHILE_LOOP_CONDITION = @as(c_int, 0); pub inline fn SDL_assert(condition: anytype) @TypeOf(SDL_enabled_assert(condition)) { return SDL_enabled_assert(condition); } pub inline fn SDL_assert_release(condition: anytype) @TypeOf(SDL_enabled_assert(condition)) { return SDL_enabled_assert(condition); } pub inline fn SDL_assert_paranoid(condition: anytype) @TypeOf(SDL_disabled_assert(condition)) { return SDL_disabled_assert(condition); } pub inline fn SDL_assert_always(condition: anytype) @TypeOf(SDL_enabled_assert(condition)) { return SDL_enabled_assert(condition); } pub const SDL_assert_state = SDL_AssertState; pub const SDL_assert_data = SDL_AssertData; pub const SDL_atomic_h_ = ""; pub inline fn SDL_MemoryBarrierRelease() @TypeOf(SDL_CompilerBarrier()) { return SDL_CompilerBarrier(); } pub inline fn SDL_MemoryBarrierAcquire() @TypeOf(SDL_CompilerBarrier()) { return SDL_CompilerBarrier(); } pub inline fn SDL_AtomicIncRef(a: anytype) @TypeOf(SDL_AtomicAdd(a, @as(c_int, 1))) { return SDL_AtomicAdd(a, @as(c_int, 1)); } pub inline fn SDL_AtomicDecRef(a: anytype) @TypeOf(SDL_AtomicAdd(a, -@as(c_int, 1)) == @as(c_int, 1)) { return SDL_AtomicAdd(a, -@as(c_int, 1)) == @as(c_int, 1); } pub const SDL_audio_h_ = ""; pub const SDL_error_h_ = ""; pub inline fn SDL_OutOfMemory() @TypeOf(SDL_Error(SDL_ENOMEM)) { return SDL_Error(SDL_ENOMEM); } pub inline fn SDL_Unsupported() @TypeOf(SDL_Error(SDL_UNSUPPORTED)) { return SDL_Error(SDL_UNSUPPORTED); } pub inline fn SDL_InvalidParamError(param: anytype) @TypeOf(SDL_SetError("Parameter '%s' is invalid", param)) { return SDL_SetError("Parameter '%s' is invalid", param); } pub const SDL_endian_h_ = ""; pub const SDL_LIL_ENDIAN = @as(c_int, 1234); pub const SDL_BIG_ENDIAN = @as(c_int, 4321); pub const SDL_BYTEORDER = __BYTE_ORDER; pub inline fn SDL_Swap16(x: anytype) @TypeOf(__builtin_bswap16(x)) { return __builtin_bswap16(x); } pub inline fn SDL_Swap32(x: anytype) @TypeOf(__builtin_bswap32(x)) { return __builtin_bswap32(x); } pub inline fn SDL_Swap64(x: anytype) @TypeOf(__builtin_bswap64(x)) { return __builtin_bswap64(x); } pub inline fn SDL_SwapLE16(X: anytype) @TypeOf(X) { return X; } pub inline fn SDL_SwapLE32(X: anytype) @TypeOf(X) { return X; } pub inline fn SDL_SwapLE64(X: anytype) @TypeOf(X) { return X; } pub inline fn SDL_SwapFloatLE(X: anytype) @TypeOf(X) { return X; } pub inline fn SDL_SwapBE16(X: anytype) @TypeOf(SDL_Swap16(X)) { return SDL_Swap16(X); } pub inline fn SDL_SwapBE32(X: anytype) @TypeOf(SDL_Swap32(X)) { return SDL_Swap32(X); } pub inline fn SDL_SwapBE64(X: anytype) @TypeOf(SDL_Swap64(X)) { return SDL_Swap64(X); } pub inline fn SDL_SwapFloatBE(X: anytype) @TypeOf(SDL_SwapFloat(X)) { return SDL_SwapFloat(X); } pub const SDL_mutex_h_ = ""; pub const SDL_MUTEX_TIMEDOUT = @as(c_int, 1); pub const SDL_MUTEX_MAXWAIT = ~@import("std").zig.c_translation.cast(Uint32, @as(c_int, 0)); pub inline fn SDL_mutexP(m: anytype) @TypeOf(SDL_LockMutex(m)) { return SDL_LockMutex(m); } pub inline fn SDL_mutexV(m: anytype) @TypeOf(SDL_UnlockMutex(m)) { return SDL_UnlockMutex(m); } pub const SDL_thread_h_ = ""; pub const SDL_rwops_h_ = ""; pub const SDL_RWOPS_UNKNOWN = @as(c_uint, 0); pub const SDL_RWOPS_WINFILE = @as(c_uint, 1); pub const SDL_RWOPS_STDFILE = @as(c_uint, 2); pub const SDL_RWOPS_JNIFILE = @as(c_uint, 3); pub const SDL_RWOPS_MEMORY = @as(c_uint, 4); pub const SDL_RWOPS_MEMORY_RO = @as(c_uint, 5); pub const RW_SEEK_SET = @as(c_int, 0); pub const RW_SEEK_CUR = @as(c_int, 1); pub const RW_SEEK_END = @as(c_int, 2); pub const SDL_AUDIO_MASK_BITSIZE = @as(c_int, 0xFF); pub const SDL_AUDIO_MASK_DATATYPE = @as(c_int, 1) << @as(c_int, 8); pub const SDL_AUDIO_MASK_ENDIAN = @as(c_int, 1) << @as(c_int, 12); pub const SDL_AUDIO_MASK_SIGNED = @as(c_int, 1) << @as(c_int, 15); pub inline fn SDL_AUDIO_BITSIZE(x: anytype) @TypeOf(x & SDL_AUDIO_MASK_BITSIZE) { return x & SDL_AUDIO_MASK_BITSIZE; } pub inline fn SDL_AUDIO_ISFLOAT(x: anytype) @TypeOf(x & SDL_AUDIO_MASK_DATATYPE) { return x & SDL_AUDIO_MASK_DATATYPE; } pub inline fn SDL_AUDIO_ISBIGENDIAN(x: anytype) @TypeOf(x & SDL_AUDIO_MASK_ENDIAN) { return x & SDL_AUDIO_MASK_ENDIAN; } pub inline fn SDL_AUDIO_ISSIGNED(x: anytype) @TypeOf(x & SDL_AUDIO_MASK_SIGNED) { return x & SDL_AUDIO_MASK_SIGNED; } pub inline fn SDL_AUDIO_ISINT(x: anytype) @TypeOf(!(SDL_AUDIO_ISFLOAT(x) != 0)) { return !(SDL_AUDIO_ISFLOAT(x) != 0); } pub inline fn SDL_AUDIO_ISLITTLEENDIAN(x: anytype) @TypeOf(!(SDL_AUDIO_ISBIGENDIAN(x) != 0)) { return !(SDL_AUDIO_ISBIGENDIAN(x) != 0); } pub inline fn SDL_AUDIO_ISUNSIGNED(x: anytype) @TypeOf(!(SDL_AUDIO_ISSIGNED(x) != 0)) { return !(SDL_AUDIO_ISSIGNED(x) != 0); } pub const SDL_AUDIO_ALLOW_FREQUENCY_CHANGE = @as(c_int, 0x00000001); pub const SDL_AUDIO_ALLOW_FORMAT_CHANGE = @as(c_int, 0x00000002); pub const SDL_AUDIO_ALLOW_CHANNELS_CHANGE = @as(c_int, 0x00000004); pub const SDL_AUDIO_ALLOW_SAMPLES_CHANGE = @as(c_int, 0x00000008); pub const SDL_AUDIO_ALLOW_ANY_CHANGE = ((SDL_AUDIO_ALLOW_FREQUENCY_CHANGE | SDL_AUDIO_ALLOW_FORMAT_CHANGE) | SDL_AUDIO_ALLOW_CHANNELS_CHANGE) | SDL_AUDIO_ALLOW_SAMPLES_CHANGE; pub const SDL_AUDIOCVT_MAX_FILTERS = @as(c_int, 9); pub inline fn SDL_LoadWAV(file: anytype, spec: anytype, audio_buf: anytype, audio_len: anytype) @TypeOf(SDL_LoadWAV_RW(SDL_RWFromFile(file, "rb"), @as(c_int, 1), spec, audio_buf, audio_len)) { return SDL_LoadWAV_RW(SDL_RWFromFile(file, "rb"), @as(c_int, 1), spec, audio_buf, audio_len); } pub const SDL_MIX_MAXVOLUME = @as(c_int, 128); pub const SDL_clipboard_h_ = ""; pub const SDL_cpuinfo_h_ = ""; pub const SDL_CACHELINE_SIZE = @as(c_int, 128); pub const SDL_events_h_ = ""; pub const SDL_video_h_ = ""; pub const SDL_pixels_h_ = ""; pub const SDL_ALPHA_OPAQUE = @as(c_int, 255); pub const SDL_ALPHA_TRANSPARENT = @as(c_int, 0); pub inline fn SDL_DEFINE_PIXELFOURCC(A: anytype, B: anytype, C: anytype, D: anytype) @TypeOf(SDL_FOURCC(A, B, C, D)) { return SDL_FOURCC(A, B, C, D); } pub inline fn SDL_DEFINE_PIXELFORMAT(@"type": anytype, order: anytype, layout: anytype, bits: anytype, bytes: anytype) @TypeOf((((((@as(c_int, 1) << @as(c_int, 28)) | (@"type" << @as(c_int, 24))) | (order << @as(c_int, 20))) | (layout << @as(c_int, 16))) | (bits << @as(c_int, 8))) | (bytes << @as(c_int, 0))) { return (((((@as(c_int, 1) << @as(c_int, 28)) | (@"type" << @as(c_int, 24))) | (order << @as(c_int, 20))) | (layout << @as(c_int, 16))) | (bits << @as(c_int, 8))) | (bytes << @as(c_int, 0)); } pub inline fn SDL_PIXELFLAG(X: anytype) @TypeOf((X >> @as(c_int, 28)) & @as(c_int, 0x0F)) { return (X >> @as(c_int, 28)) & @as(c_int, 0x0F); } pub inline fn SDL_PIXELTYPE(X: anytype) @TypeOf((X >> @as(c_int, 24)) & @as(c_int, 0x0F)) { return (X >> @as(c_int, 24)) & @as(c_int, 0x0F); } pub inline fn SDL_PIXELORDER(X: anytype) @TypeOf((X >> @as(c_int, 20)) & @as(c_int, 0x0F)) { return (X >> @as(c_int, 20)) & @as(c_int, 0x0F); } pub inline fn SDL_PIXELLAYOUT(X: anytype) @TypeOf((X >> @as(c_int, 16)) & @as(c_int, 0x0F)) { return (X >> @as(c_int, 16)) & @as(c_int, 0x0F); } pub inline fn SDL_BITSPERPIXEL(X: anytype) @TypeOf((X >> @as(c_int, 8)) & @as(c_int, 0xFF)) { return (X >> @as(c_int, 8)) & @as(c_int, 0xFF); } pub inline fn SDL_BYTESPERPIXEL(X: anytype) @TypeOf(if (SDL_ISPIXELFORMAT_FOURCC(X)) if (((X == SDL_PIXELFORMAT_YUY2) or (X == SDL_PIXELFORMAT_UYVY)) or (X == SDL_PIXELFORMAT_YVYU)) @as(c_int, 2) else @as(c_int, 1) else (X >> @as(c_int, 0)) & @as(c_int, 0xFF)) { return if (SDL_ISPIXELFORMAT_FOURCC(X)) if (((X == SDL_PIXELFORMAT_YUY2) or (X == SDL_PIXELFORMAT_UYVY)) or (X == SDL_PIXELFORMAT_YVYU)) @as(c_int, 2) else @as(c_int, 1) else (X >> @as(c_int, 0)) & @as(c_int, 0xFF); } pub inline fn SDL_ISPIXELFORMAT_INDEXED(format: anytype) @TypeOf(!(SDL_ISPIXELFORMAT_FOURCC(format) != 0) and (((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX1) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX4)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX8))) { return !(SDL_ISPIXELFORMAT_FOURCC(format) != 0) and (((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX1) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX4)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX8)); } pub inline fn SDL_ISPIXELFORMAT_PACKED(format: anytype) @TypeOf(!(SDL_ISPIXELFORMAT_FOURCC(format) != 0) and (((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_PACKED8) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_PACKED16)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_PACKED32))) { return !(SDL_ISPIXELFORMAT_FOURCC(format) != 0) and (((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_PACKED8) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_PACKED16)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_PACKED32)); } pub inline fn SDL_ISPIXELFORMAT_ARRAY(format: anytype) @TypeOf(!(SDL_ISPIXELFORMAT_FOURCC(format) != 0) and (((((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYU8) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYU16)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYU32)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYF16)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYF32))) { return !(SDL_ISPIXELFORMAT_FOURCC(format) != 0) and (((((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYU8) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYU16)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYU32)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYF16)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYF32)); } pub inline fn SDL_ISPIXELFORMAT_ALPHA(format: anytype) @TypeOf(((SDL_ISPIXELFORMAT_PACKED(format) != 0) and ((((SDL_PIXELORDER(format) == SDL_PACKEDORDER_ARGB) or (SDL_PIXELORDER(format) == SDL_PACKEDORDER_RGBA)) or (SDL_PIXELORDER(format) == SDL_PACKEDORDER_ABGR)) or (SDL_PIXELORDER(format) == SDL_PACKEDORDER_BGRA))) or ((SDL_ISPIXELFORMAT_ARRAY(format) != 0) and ((((SDL_PIXELORDER(format) == SDL_ARRAYORDER_ARGB) or (SDL_PIXELORDER(format) == SDL_ARRAYORDER_RGBA)) or (SDL_PIXELORDER(format) == SDL_ARRAYORDER_ABGR)) or (SDL_PIXELORDER(format) == SDL_ARRAYORDER_BGRA)))) { return ((SDL_ISPIXELFORMAT_PACKED(format) != 0) and ((((SDL_PIXELORDER(format) == SDL_PACKEDORDER_ARGB) or (SDL_PIXELORDER(format) == SDL_PACKEDORDER_RGBA)) or (SDL_PIXELORDER(format) == SDL_PACKEDORDER_ABGR)) or (SDL_PIXELORDER(format) == SDL_PACKEDORDER_BGRA))) or ((SDL_ISPIXELFORMAT_ARRAY(format) != 0) and ((((SDL_PIXELORDER(format) == SDL_ARRAYORDER_ARGB) or (SDL_PIXELORDER(format) == SDL_ARRAYORDER_RGBA)) or (SDL_PIXELORDER(format) == SDL_ARRAYORDER_ABGR)) or (SDL_PIXELORDER(format) == SDL_ARRAYORDER_BGRA))); } pub inline fn SDL_ISPIXELFORMAT_FOURCC(format: anytype) @TypeOf((format != 0) and (SDL_PIXELFLAG(format) != @as(c_int, 1))) { return (format != 0) and (SDL_PIXELFLAG(format) != @as(c_int, 1)); } pub const SDL_Colour = SDL_Color; pub const SDL_rect_h_ = ""; pub const SDL_surface_h_ = ""; pub const SDL_blendmode_h_ = ""; pub const SDL_SWSURFACE = @as(c_int, 0); pub const SDL_PREALLOC = @as(c_int, 0x00000001); pub const SDL_RLEACCEL = @as(c_int, 0x00000002); pub const SDL_DONTFREE = @as(c_int, 0x00000004); pub const SDL_SIMD_ALIGNED = @as(c_int, 0x00000008); pub inline fn SDL_MUSTLOCK(S: anytype) @TypeOf((S.*.flags & SDL_RLEACCEL) != @as(c_int, 0)) { return (S.*.flags & SDL_RLEACCEL) != @as(c_int, 0); } pub inline fn SDL_LoadBMP(file: anytype) @TypeOf(SDL_LoadBMP_RW(SDL_RWFromFile(file, "rb"), @as(c_int, 1))) { return SDL_LoadBMP_RW(SDL_RWFromFile(file, "rb"), @as(c_int, 1)); } pub inline fn SDL_SaveBMP(surface: anytype, file: anytype) @TypeOf(SDL_SaveBMP_RW(surface, SDL_RWFromFile(file, "wb"), @as(c_int, 1))) { return SDL_SaveBMP_RW(surface, SDL_RWFromFile(file, "wb"), @as(c_int, 1)); } pub const SDL_BlitSurface = SDL_UpperBlit; pub const SDL_BlitScaled = SDL_UpperBlitScaled; pub const SDL_WINDOWPOS_UNDEFINED_MASK = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 0x1FFF0000, .hexadecimal); pub inline fn SDL_WINDOWPOS_UNDEFINED_DISPLAY(X: anytype) @TypeOf(SDL_WINDOWPOS_UNDEFINED_MASK | X) { return SDL_WINDOWPOS_UNDEFINED_MASK | X; } pub const SDL_WINDOWPOS_UNDEFINED = SDL_WINDOWPOS_UNDEFINED_DISPLAY(@as(c_int, 0)); pub inline fn SDL_WINDOWPOS_ISUNDEFINED(X: anytype) @TypeOf((X & @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFF0000, .hexadecimal)) == SDL_WINDOWPOS_UNDEFINED_MASK) { return (X & @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFF0000, .hexadecimal)) == SDL_WINDOWPOS_UNDEFINED_MASK; } pub const SDL_WINDOWPOS_CENTERED_MASK = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 0x2FFF0000, .hexadecimal); pub inline fn SDL_WINDOWPOS_CENTERED_DISPLAY(X: anytype) @TypeOf(SDL_WINDOWPOS_CENTERED_MASK | X) { return SDL_WINDOWPOS_CENTERED_MASK | X; } pub const SDL_WINDOWPOS_CENTERED = SDL_WINDOWPOS_CENTERED_DISPLAY(@as(c_int, 0)); pub inline fn SDL_WINDOWPOS_ISCENTERED(X: anytype) @TypeOf((X & @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFF0000, .hexadecimal)) == SDL_WINDOWPOS_CENTERED_MASK) { return (X & @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFF0000, .hexadecimal)) == SDL_WINDOWPOS_CENTERED_MASK; } pub const SDL_keyboard_h_ = ""; pub const SDL_keycode_h_ = ""; pub const SDL_scancode_h_ = ""; pub const SDLK_SCANCODE_MASK = @as(c_int, 1) << @as(c_int, 30); pub inline fn SDL_SCANCODE_TO_KEYCODE(X: anytype) @TypeOf(X | SDLK_SCANCODE_MASK) { return X | SDLK_SCANCODE_MASK; } pub const SDL_mouse_h_ = ""; pub inline fn SDL_BUTTON(X: anytype) @TypeOf(@as(c_int, 1) << (X - @as(c_int, 1))) { return @as(c_int, 1) << (X - @as(c_int, 1)); } pub const SDL_BUTTON_LEFT = @as(c_int, 1); pub const SDL_BUTTON_MIDDLE = @as(c_int, 2); pub const SDL_BUTTON_RIGHT = @as(c_int, 3); pub const SDL_BUTTON_X1 = @as(c_int, 4); pub const SDL_BUTTON_X2 = @as(c_int, 5); pub const SDL_BUTTON_LMASK = SDL_BUTTON(SDL_BUTTON_LEFT); pub const SDL_BUTTON_MMASK = SDL_BUTTON(SDL_BUTTON_MIDDLE); pub const SDL_BUTTON_RMASK = SDL_BUTTON(SDL_BUTTON_RIGHT); pub const SDL_BUTTON_X1MASK = SDL_BUTTON(SDL_BUTTON_X1); pub const SDL_BUTTON_X2MASK = SDL_BUTTON(SDL_BUTTON_X2); pub const SDL_joystick_h_ = ""; pub const SDL_IPHONE_MAX_GFORCE = 5.0; pub const SDL_JOYSTICK_AXIS_MAX = @as(c_int, 32767); pub const SDL_JOYSTICK_AXIS_MIN = -@import("std").zig.c_translation.promoteIntLiteral(c_int, 32768, .decimal); pub const SDL_HAT_CENTERED = @as(c_int, 0x00); pub const SDL_HAT_UP = @as(c_int, 0x01); pub const SDL_HAT_RIGHT = @as(c_int, 0x02); pub const SDL_HAT_DOWN = @as(c_int, 0x04); pub const SDL_HAT_LEFT = @as(c_int, 0x08); pub const SDL_HAT_RIGHTUP = SDL_HAT_RIGHT | SDL_HAT_UP; pub const SDL_HAT_RIGHTDOWN = SDL_HAT_RIGHT | SDL_HAT_DOWN; pub const SDL_HAT_LEFTUP = SDL_HAT_LEFT | SDL_HAT_UP; pub const SDL_HAT_LEFTDOWN = SDL_HAT_LEFT | SDL_HAT_DOWN; pub const SDL_gamecontroller_h_ = ""; pub const SDL_sensor_h_ = ""; pub const SDL_STANDARD_GRAVITY = @as(f32, 9.80665); pub inline fn SDL_GameControllerAddMappingsFromFile(file: anytype) @TypeOf(SDL_GameControllerAddMappingsFromRW(SDL_RWFromFile(file, "rb"), @as(c_int, 1))) { return SDL_GameControllerAddMappingsFromRW(SDL_RWFromFile(file, "rb"), @as(c_int, 1)); } pub const SDL_quit_h_ = ""; pub inline fn SDL_QuitRequested() @TypeOf(SDL_PeepEvents(NULL, @as(c_int, 0), SDL_PEEKEVENT, SDL_QUIT, SDL_QUIT) > @as(c_int, 0)) { return blk: { _ = SDL_PumpEvents(); break :blk SDL_PeepEvents(NULL, @as(c_int, 0), SDL_PEEKEVENT, SDL_QUIT, SDL_QUIT) > @as(c_int, 0); }; } pub const SDL_gesture_h_ = ""; pub const SDL_touch_h_ = ""; pub const SDL_TOUCH_MOUSEID = @import("std").zig.c_translation.cast(Uint32, -@as(c_int, 1)); pub const SDL_MOUSE_TOUCHID = @import("std").zig.c_translation.cast(Sint64, -@as(c_int, 1)); pub const SDL_RELEASED = @as(c_int, 0); pub const SDL_PRESSED = @as(c_int, 1); pub const SDL_TEXTEDITINGEVENT_TEXT_SIZE = @as(c_int, 32); pub const SDL_TEXTINPUTEVENT_TEXT_SIZE = @as(c_int, 32); pub const SDL_QUERY = -@as(c_int, 1); pub const SDL_IGNORE = @as(c_int, 0); pub const SDL_DISABLE = @as(c_int, 0); pub const SDL_ENABLE = @as(c_int, 1); pub inline fn SDL_GetEventState(@"type": anytype) @TypeOf(SDL_EventState(@"type", SDL_QUERY)) { return SDL_EventState(@"type", SDL_QUERY); } pub const SDL_filesystem_h_ = ""; pub const SDL_haptic_h_ = ""; pub const SDL_HAPTIC_CONSTANT = @as(c_uint, 1) << @as(c_int, 0); pub const SDL_HAPTIC_SINE = @as(c_uint, 1) << @as(c_int, 1); pub const SDL_HAPTIC_LEFTRIGHT = @as(c_uint, 1) << @as(c_int, 2); pub const SDL_HAPTIC_TRIANGLE = @as(c_uint, 1) << @as(c_int, 3); pub const SDL_HAPTIC_SAWTOOTHUP = @as(c_uint, 1) << @as(c_int, 4); pub const SDL_HAPTIC_SAWTOOTHDOWN = @as(c_uint, 1) << @as(c_int, 5); pub const SDL_HAPTIC_RAMP = @as(c_uint, 1) << @as(c_int, 6); pub const SDL_HAPTIC_SPRING = @as(c_uint, 1) << @as(c_int, 7); pub const SDL_HAPTIC_DAMPER = @as(c_uint, 1) << @as(c_int, 8); pub const SDL_HAPTIC_INERTIA = @as(c_uint, 1) << @as(c_int, 9); pub const SDL_HAPTIC_FRICTION = @as(c_uint, 1) << @as(c_int, 10); pub const SDL_HAPTIC_CUSTOM = @as(c_uint, 1) << @as(c_int, 11); pub const SDL_HAPTIC_GAIN = @as(c_uint, 1) << @as(c_int, 12); pub const SDL_HAPTIC_AUTOCENTER = @as(c_uint, 1) << @as(c_int, 13); pub const SDL_HAPTIC_STATUS = @as(c_uint, 1) << @as(c_int, 14); pub const SDL_HAPTIC_PAUSE = @as(c_uint, 1) << @as(c_int, 15); pub const SDL_HAPTIC_POLAR = @as(c_int, 0); pub const SDL_HAPTIC_CARTESIAN = @as(c_int, 1); pub const SDL_HAPTIC_SPHERICAL = @as(c_int, 2); pub const SDL_HAPTIC_STEERING_AXIS = @as(c_int, 3); pub const SDL_HAPTIC_INFINITY = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 4294967295, .decimal); pub const SDL_hints_h_ = ""; pub const SDL_HINT_ACCELEROMETER_AS_JOYSTICK = "SDL_ACCELEROMETER_AS_JOYSTICK"; pub const SDL_HINT_ALLOW_ALT_TAB_WHILE_GRABBED = "SDL_ALLOW_ALT_TAB_WHILE_GRABBED"; pub const SDL_HINT_ALLOW_TOPMOST = "SDL_ALLOW_TOPMOST"; pub const SDL_HINT_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION = "SDL_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION"; pub const SDL_HINT_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION = "SDL_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION"; pub const SDL_HINT_ANDROID_BLOCK_ON_PAUSE = "SDL_ANDROID_BLOCK_ON_PAUSE"; pub const SDL_HINT_ANDROID_BLOCK_ON_PAUSE_PAUSEAUDIO = "SDL_ANDROID_BLOCK_ON_PAUSE_PAUSEAUDIO"; pub const SDL_HINT_ANDROID_TRAP_BACK_BUTTON = "SDL_ANDROID_TRAP_BACK_BUTTON"; pub const SDL_HINT_APPLE_TV_CONTROLLER_UI_EVENTS = "SDL_APPLE_TV_CONTROLLER_UI_EVENTS"; pub const SDL_HINT_APPLE_TV_REMOTE_ALLOW_ROTATION = "SDL_APPLE_TV_REMOTE_ALLOW_ROTATION"; pub const SDL_HINT_AUDIO_CATEGORY = "SDL_AUDIO_CATEGORY"; pub const SDL_HINT_AUDIO_DEVICE_APP_NAME = "SDL_AUDIO_DEVICE_APP_NAME"; pub const SDL_HINT_AUDIO_DEVICE_STREAM_NAME = "SDL_AUDIO_DEVICE_STREAM_NAME"; pub const SDL_HINT_AUDIO_DEVICE_STREAM_ROLE = "SDL_AUDIO_DEVICE_STREAM_ROLE"; pub const SDL_HINT_AUDIO_RESAMPLING_MODE = "SDL_AUDIO_RESAMPLING_MODE"; pub const SDL_HINT_AUTO_UPDATE_JOYSTICKS = "SDL_AUTO_UPDATE_JOYSTICKS"; pub const SDL_HINT_AUTO_UPDATE_SENSORS = "SDL_AUTO_UPDATE_SENSORS"; pub const SDL_HINT_BMP_SAVE_LEGACY_FORMAT = "SDL_BMP_SAVE_LEGACY_FORMAT"; pub const SDL_HINT_DISPLAY_USABLE_BOUNDS = "SDL_DISPLAY_USABLE_BOUNDS"; pub const SDL_HINT_EMSCRIPTEN_ASYNCIFY = "SDL_EMSCRIPTEN_ASYNCIFY"; pub const SDL_HINT_EMSCRIPTEN_KEYBOARD_ELEMENT = "SDL_EMSCRIPTEN_KEYBOARD_ELEMENT"; pub const SDL_HINT_ENABLE_STEAM_CONTROLLERS = "SDL_ENABLE_STEAM_CONTROLLERS"; pub const SDL_HINT_EVENT_LOGGING = "SDL_EVENT_LOGGING"; pub const SDL_HINT_FRAMEBUFFER_ACCELERATION = "SDL_FRAMEBUFFER_ACCELERATION"; pub const SDL_HINT_GAMECONTROLLERCONFIG = "SDL_GAMECONTROLLERCONFIG"; pub const SDL_HINT_GAMECONTROLLERCONFIG_FILE = "SDL_GAMECONTROLLERCONFIG_FILE"; pub const SDL_HINT_GAMECONTROLLERTYPE = "SDL_GAMECONTROLLERTYPE"; pub const SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES = "SDL_GAMECONTROLLER_IGNORE_DEVICES"; pub const SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT = "SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT"; pub const SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS = "SDL_GAMECONTROLLER_USE_BUTTON_LABELS"; pub const SDL_HINT_GRAB_KEYBOARD = "SDL_GRAB_KEYBOARD"; pub const SDL_HINT_IDLE_TIMER_DISABLED = "SDL_IOS_IDLE_TIMER_DISABLED"; pub const SDL_HINT_IME_INTERNAL_EDITING = "SDL_IME_INTERNAL_EDITING"; pub const SDL_HINT_IOS_HIDE_HOME_INDICATOR = "SDL_IOS_HIDE_HOME_INDICATOR"; pub const SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS = "SDL_JOYSTICK_ALLOW_BACKGROUND_EVENTS"; pub const SDL_HINT_JOYSTICK_HIDAPI = "SDL_JOYSTICK_HIDAPI"; pub const SDL_HINT_JOYSTICK_HIDAPI_GAMECUBE = "SDL_JOYSTICK_HIDAPI_GAMECUBE"; pub const SDL_HINT_JOYSTICK_HIDAPI_JOY_CONS = "SDL_JOYSTICK_HIDAPI_JOY_CONS"; pub const SDL_HINT_JOYSTICK_HIDAPI_LUNA = "SDL_JOYSTICK_HIDAPI_LUNA"; pub const SDL_HINT_JOYSTICK_HIDAPI_PS4 = "SDL_JOYSTICK_HIDAPI_PS4"; pub const SDL_HINT_JOYSTICK_HIDAPI_PS4_RUMBLE = "SDL_JOYSTICK_HIDAPI_PS4_RUMBLE"; pub const SDL_HINT_JOYSTICK_HIDAPI_PS5 = "SDL_JOYSTICK_HIDAPI_PS5"; pub const SDL_HINT_JOYSTICK_HIDAPI_PS5_PLAYER_LED = "SDL_JOYSTICK_HIDAPI_PS5_PLAYER_LED"; pub const SDL_HINT_JOYSTICK_HIDAPI_PS5_RUMBLE = "SDL_JOYSTICK_HIDAPI_PS5_RUMBLE"; pub const SDL_HINT_JOYSTICK_HIDAPI_STADIA = "SDL_JOYSTICK_HIDAPI_STADIA"; pub const SDL_HINT_JOYSTICK_HIDAPI_STEAM = "SDL_JOYSTICK_HIDAPI_STEAM"; pub const SDL_HINT_JOYSTICK_HIDAPI_SWITCH = "SDL_JOYSTICK_HIDAPI_SWITCH"; pub const SDL_HINT_JOYSTICK_HIDAPI_SWITCH_HOME_LED = "SDL_JOYSTICK_HIDAPI_SWITCH_HOME_LED"; pub const SDL_HINT_JOYSTICK_HIDAPI_XBOX = "SDL_JOYSTICK_HIDAPI_XBOX"; pub const SDL_HINT_JOYSTICK_RAWINPUT = "SDL_JOYSTICK_RAWINPUT"; pub const SDL_HINT_JOYSTICK_RAWINPUT_CORRELATE_XINPUT = "SDL_JOYSTICK_RAWINPUT_CORRELATE_XINPUT"; pub const SDL_HINT_JOYSTICK_THREAD = "SDL_JOYSTICK_THREAD"; pub const SDL_HINT_KMSDRM_REQUIRE_DRM_MASTER = "SDL_KMSDRM_REQUIRE_DRM_MASTER"; pub const SDL_HINT_LINUX_JOYSTICK_DEADZONES = "SDL_LINUX_JOYSTICK_DEADZONES"; pub const SDL_HINT_MAC_BACKGROUND_APP = "SDL_MAC_BACKGROUND_APP"; pub const SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK = "SDL_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK"; pub const SDL_HINT_MOUSE_DOUBLE_CLICK_RADIUS = "SDL_MOUSE_DOUBLE_CLICK_RADIUS"; pub const SDL_HINT_MOUSE_DOUBLE_CLICK_TIME = "SDL_MOUSE_DOUBLE_CLICK_TIME"; pub const SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH = "SDL_MOUSE_FOCUS_CLICKTHROUGH"; pub const SDL_HINT_MOUSE_NORMAL_SPEED_SCALE = "SDL_MOUSE_NORMAL_SPEED_SCALE"; pub const SDL_HINT_MOUSE_RELATIVE_MODE_WARP = "SDL_MOUSE_RELATIVE_MODE_WARP"; pub const SDL_HINT_MOUSE_RELATIVE_SCALING = "SDL_MOUSE_RELATIVE_SCALING"; pub const SDL_HINT_MOUSE_RELATIVE_SPEED_SCALE = "SDL_MOUSE_RELATIVE_SPEED_SCALE"; pub const SDL_HINT_MOUSE_TOUCH_EVENTS = "SDL_MOUSE_TOUCH_EVENTS"; pub const SDL_HINT_NO_SIGNAL_HANDLERS = "SDL_NO_SIGNAL_HANDLERS"; pub const SDL_HINT_OPENGL_ES_DRIVER = "SDL_OPENGL_ES_DRIVER"; pub const SDL_HINT_ORIENTATIONS = "SDL_IOS_ORIENTATIONS"; pub const SDL_HINT_PREFERRED_LOCALES = "SDL_PREFERRED_LOCALES"; pub const SDL_HINT_QTWAYLAND_CONTENT_ORIENTATION = "SDL_QTWAYLAND_CONTENT_ORIENTATION"; pub const SDL_HINT_QTWAYLAND_WINDOW_FLAGS = "SDL_QTWAYLAND_WINDOW_FLAGS"; pub const SDL_HINT_RENDER_BATCHING = "SDL_RENDER_BATCHING"; pub const SDL_HINT_RENDER_DIRECT3D11_DEBUG = "SDL_RENDER_DIRECT3D11_DEBUG"; pub const SDL_HINT_RENDER_DIRECT3D_THREADSAFE = "SDL_RENDER_DIRECT3D_THREADSAFE"; pub const SDL_HINT_RENDER_DRIVER = "SDL_RENDER_DRIVER"; pub const SDL_HINT_RENDER_LOGICAL_SIZE_MODE = "SDL_RENDER_LOGICAL_SIZE_MODE"; pub const SDL_HINT_RENDER_OPENGL_SHADERS = "SDL_RENDER_OPENGL_SHADERS"; pub const SDL_HINT_RENDER_SCALE_QUALITY = "SDL_RENDER_SCALE_QUALITY"; pub const SDL_HINT_RENDER_VSYNC = "SDL_RENDER_VSYNC"; pub const SDL_HINT_RETURN_KEY_HIDES_IME = "SDL_RETURN_KEY_HIDES_IME"; pub const SDL_HINT_RPI_VIDEO_LAYER = "SDL_RPI_VIDEO_LAYER"; pub const SDL_HINT_THREAD_FORCE_REALTIME_TIME_CRITICAL = "SDL_THREAD_FORCE_REALTIME_TIME_CRITICAL"; pub const SDL_HINT_THREAD_PRIORITY_POLICY = "SDL_THREAD_PRIORITY_POLICY"; pub const SDL_HINT_THREAD_STACK_SIZE = "SDL_THREAD_STACK_SIZE"; pub const SDL_HINT_TIMER_RESOLUTION = "SDL_TIMER_RESOLUTION"; pub const SDL_HINT_TOUCH_MOUSE_EVENTS = "SDL_TOUCH_MOUSE_EVENTS"; pub const SDL_HINT_TV_REMOTE_AS_JOYSTICK = "SDL_TV_REMOTE_AS_JOYSTICK"; pub const SDL_HINT_VIDEO_ALLOW_SCREENSAVER = "SDL_VIDEO_ALLOW_SCREENSAVER"; pub const SDL_HINT_VIDEO_DOUBLE_BUFFER = "SDL_VIDEO_DOUBLE_BUFFER"; pub const SDL_HINT_VIDEO_EXTERNAL_CONTEXT = "SDL_VIDEO_EXTERNAL_CONTEXT"; pub const SDL_HINT_VIDEO_HIGHDPI_DISABLED = "SDL_VIDEO_HIGHDPI_DISABLED"; pub const SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES = "SDL_VIDEO_MAC_FULLSCREEN_SPACES"; pub const SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS = "SDL_VIDEO_MINIMIZE_ON_FOCUS_LOSS"; pub const SDL_HINT_VIDEO_WAYLAND_ALLOW_LIBDECOR = "SDL_VIDEO_WAYLAND_ALLOW_LIBDECOR"; pub const SDL_HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT = "SDL_VIDEO_WINDOW_SHARE_PIXEL_FORMAT"; pub const SDL_HINT_VIDEO_WIN_D3DCOMPILER = "SDL_VIDEO_WIN_D3DCOMPILER"; pub const SDL_HINT_VIDEO_X11_FORCE_EGL = "SDL_VIDEO_X11_FORCE_EGL"; pub const SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR = "SDL_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR"; pub const SDL_HINT_VIDEO_X11_NET_WM_PING = "SDL_VIDEO_X11_NET_WM_PING"; pub const SDL_HINT_VIDEO_X11_WINDOW_VISUALID = "SDL_VIDEO_X11_WINDOW_VISUALID"; pub const SDL_HINT_VIDEO_X11_XINERAMA = "SDL_VIDEO_X11_XINERAMA"; pub const SDL_HINT_VIDEO_X11_XRANDR = "SDL_VIDEO_X11_XRANDR"; pub const SDL_HINT_VIDEO_X11_XVIDMODE = "SDL_VIDEO_X11_XVIDMODE"; pub const SDL_HINT_WAVE_FACT_CHUNK = "SDL_WAVE_FACT_CHUNK"; pub const SDL_HINT_WAVE_RIFF_CHUNK_SIZE = "SDL_WAVE_RIFF_CHUNK_SIZE"; pub const SDL_HINT_WAVE_TRUNCATION = "SDL_WAVE_TRUNCATION"; pub const SDL_HINT_WINDOWS_DISABLE_THREAD_NAMING = "SDL_WINDOWS_DISABLE_THREAD_NAMING"; pub const SDL_HINT_WINDOWS_ENABLE_MESSAGELOOP = "SDL_WINDOWS_ENABLE_MESSAGELOOP"; pub const SDL_HINT_WINDOWS_FORCE_MUTEX_CRITICAL_SECTIONS = "SDL_WINDOWS_FORCE_MUTEX_CRITICAL_SECTIONS"; pub const SDL_HINT_WINDOWS_FORCE_SEMAPHORE_KERNEL = "SDL_WINDOWS_FORCE_SEMAPHORE_KERNEL"; pub const SDL_HINT_WINDOWS_INTRESOURCE_ICON = "SDL_WINDOWS_INTRESOURCE_ICON"; pub const SDL_HINT_WINDOWS_INTRESOURCE_ICON_SMALL = "SDL_WINDOWS_INTRESOURCE_ICON_SMALL"; pub const SDL_HINT_WINDOWS_NO_CLOSE_ON_ALT_F4 = "SDL_WINDOWS_NO_CLOSE_ON_ALT_F4"; pub const SDL_HINT_WINDOWS_USE_D3D9EX = "SDL_WINDOWS_USE_D3D9EX"; pub const SDL_HINT_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN = "SDL_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN"; pub const SDL_HINT_WINRT_HANDLE_BACK_BUTTON = "SDL_WINRT_HANDLE_BACK_BUTTON"; pub const SDL_HINT_WINRT_PRIVACY_POLICY_LABEL = "SDL_WINRT_PRIVACY_POLICY_LABEL"; pub const SDL_HINT_WINRT_PRIVACY_POLICY_URL = "SDL_WINRT_PRIVACY_POLICY_URL"; pub const SDL_HINT_X11_FORCE_OVERRIDE_REDIRECT = "SDL_X11_FORCE_OVERRIDE_REDIRECT"; pub const SDL_HINT_XINPUT_ENABLED = "SDL_XINPUT_ENABLED"; pub const SDL_HINT_XINPUT_USE_OLD_JOYSTICK_MAPPING = "SDL_XINPUT_USE_OLD_JOYSTICK_MAPPING"; pub const SDL_HINT_AUDIO_INCLUDE_MONITORS = "SDL_AUDIO_INCLUDE_MONITORS"; pub const SDL_loadso_h_ = ""; pub const SDL_log_h_ = ""; pub const SDL_MAX_LOG_MESSAGE = @as(c_int, 4096); pub const SDL_messagebox_h_ = ""; pub const SDL_metal_h_ = ""; pub const SDL_power_h_ = ""; pub const SDL_render_h_ = ""; pub const SDL_shape_h_ = ""; pub const SDL_NONSHAPEABLE_WINDOW = -@as(c_int, 1); pub const SDL_INVALID_SHAPE_ARGUMENT = -@as(c_int, 2); pub const SDL_WINDOW_LACKS_SHAPE = -@as(c_int, 3); pub inline fn SDL_SHAPEMODEALPHA(mode: anytype) @TypeOf(((mode == ShapeModeDefault) or (mode == ShapeModeBinarizeAlpha)) or (mode == ShapeModeReverseBinarizeAlpha)) { return ((mode == ShapeModeDefault) or (mode == ShapeModeBinarizeAlpha)) or (mode == ShapeModeReverseBinarizeAlpha); } pub const SDL_system_h_ = ""; pub const SDL_timer_h_ = ""; pub inline fn SDL_TICKS_PASSED(A: anytype, B: anytype) @TypeOf(@import("std").zig.c_translation.cast(Sint32, B - A) <= @as(c_int, 0)) { return @import("std").zig.c_translation.cast(Sint32, B - A) <= @as(c_int, 0); } pub const SDL_version_h_ = ""; pub const SDL_MAJOR_VERSION = @as(c_int, 2); pub const SDL_MINOR_VERSION = @as(c_int, 0); pub const SDL_PATCHLEVEL = @as(c_int, 16); pub inline fn SDL_VERSIONNUM(X: anytype, Y: anytype, Z: anytype) @TypeOf(((X * @as(c_int, 1000)) + (Y * @as(c_int, 100))) + Z) { return ((X * @as(c_int, 1000)) + (Y * @as(c_int, 100))) + Z; } pub const SDL_COMPILEDVERSION = SDL_VERSIONNUM(SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_PATCHLEVEL); pub inline fn SDL_VERSION_ATLEAST(X: anytype, Y: anytype, Z: anytype) @TypeOf(SDL_COMPILEDVERSION >= SDL_VERSIONNUM(X, Y, Z)) { return SDL_COMPILEDVERSION >= SDL_VERSIONNUM(X, Y, Z); } pub const _SDL_locale_h = ""; pub const SDL_misc_h_ = ""; pub const SDL_INIT_TIMER = @as(c_uint, 0x00000001); pub const SDL_INIT_AUDIO = @as(c_uint, 0x00000010); pub const SDL_INIT_VIDEO = @as(c_uint, 0x00000020); pub const SDL_INIT_JOYSTICK = @as(c_uint, 0x00000200); pub const SDL_INIT_HAPTIC = @as(c_uint, 0x00001000); pub const SDL_INIT_GAMECONTROLLER = @as(c_uint, 0x00002000); pub const SDL_INIT_EVENTS = @as(c_uint, 0x00004000); pub const SDL_INIT_SENSOR = @as(c_uint, 0x00008000); pub const SDL_INIT_NOPARACHUTE = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 0x00100000, .hexadecimal); pub const SDL_INIT_EVERYTHING = ((((((SDL_INIT_TIMER | SDL_INIT_AUDIO) | SDL_INIT_VIDEO) | SDL_INIT_EVENTS) | SDL_INIT_JOYSTICK) | SDL_INIT_HAPTIC) | SDL_INIT_GAMECONTROLLER) | SDL_INIT_SENSOR;
gamekit/deps/sdl/sdl.zig
// SPDX-License-Identifier: MIT // This file is part of the `termcon` project under the MIT license. pub const Style = struct { fg_color: Color, bg_color: Color, text_decorations: TextDecorations, const Self = @This(); pub fn equal(self: *const Self, other: Style) bool { return self.fg_color.equal(other.fg_color) and self.bg_color.equal(other.bg_color) and self.text_decorations.equal(other.text_decorations); } }; pub const TextDecorations = struct { italic: bool, bold: bool, underline: bool, const Self = @This(); pub fn equal(self: *const Self, other: TextDecorations) bool { return (self.italic == other.italic and self.bold == other.bold and self.underline == other.underline); } }; pub const Color = union(ColorType) { Default: u0, Named8: ColorNamed8, Named16: ColorNamed16, Bit8: ColorBit8, Bit24: ColorBit24, const Self = @This(); pub fn equal(self: Self, other: Color) bool { if (@as(ColorType, self) != @as(ColorType, other)) return false; return switch (self) { ColorType.Default => true, ColorType.Named8 => |v| v == other.Named8, ColorType.Named16 => |v| v == other.Named16, ColorType.Bit8 => |v| v.code == other.Bit8.code, ColorType.Bit24 => |v| v.code == other.Bit24.code, }; } }; pub const ColorType = enum { Default, Named8, Named16, Bit8, Bit24, }; /// Color names and values based on: /// [ANSI Escape Codes](https://en.wikipedia.org/wiki/ANSI_escape_code) pub const ColorNamed8 = enum(u3) { Black, Red, Green, Yellow, Blue, Magenta, Cyan, White, }; /// Color names and values based on: /// [ANSI Escape Codes](https://en.wikipedia.org/wiki/ANSI_escape_code) pub const ColorNamed16 = enum(u4) { Black, Red, Green, Yellow, Blue, Magenta, Cyan, White, BrightBlack, BrightRed, BrightGreen, BrightYellow, BrightBlue, BrightMagenta, BrightCyan, BrightWhite, pub fn fromNamed8(name: ColorNamed8) ColorNamed16 { return switch (name) { ColorNamed8.Black => Black, ColorNamed8.Red => Red, ColorNamed8.Green => Green, ColorNamed8.Yellow => Yellow, ColorNamed8.Blue => Blue, ColorNamed8.Magenta => Magenta, ColorNamed8.Cyan => Cyan, ColorNamed8.White => White, }; } }; /// Color values based on: /// [ANSI Escape Codes](https://en.wikipedia.org/wiki/ANSI_escape_code) pub const ColorBit8 = struct { code: u8, pub fn init(code: u8) ColorBit8 { return ColorBit8{ .code = code }; } pub fn fromNamed8(name: ColorNamed8) ColorBit8 { return ColorBit8{ .code = @enumToInt(name) }; } pub fn fromNamed16(name: ColorNamed16) ColorBit8 { return ColorBit8{ .code = @enumToInt(name) }; } }; pub const ColorBit24 = struct { code: u24, pub fn init(code: u24) ColorBit24 { return ColorBit24{ .code = code }; } pub fn initRGB(red: u8, green: u8, blue: u8) ColorBit24 { var code: u24 = 0; code |= blue; code |= @as(u16, green) << 8; code |= @as(u24, red) << 16; return ColorBit24{ .code = code }; } /// Color values based on: /// [ANSI Escape Codes](https://en.wikipedia.org/wiki/ANSI_escape_code) /// VGA values pub fn fromNamed8(name: ColorNamed8) ColorBit24 { return switch (name) { ColorNamed8.Black => self.initRGB(0, 0, 0), ColorNamed8.Red => self.initRGB(170, 0, 0), ColorNamed8.Green => self.initRGB(0, 170, 0), ColorNamed8.Yellow => self.initRGB(170, 85, 0), ColorNamed8.Blue => self.initRGB(0, 0, 170), ColorNamed8.Magenta => self.initRGB(170, 0, 170), ColorNamed8.Cyan => self.initRGB(0, 170, 170), ColorNamed8.White => self.initRGB(170, 170, 170), }; } /// Color values based on: /// [ANSI Escape Codes](https://en.wikipedia.org/wiki/ANSI_escape_code) /// VGA values pub fn fromNamed16(name: ColorNamed16) ColorBit24 { return switch (name) { ColorNamed16.Black => self.initRGB(0, 0, 0), ColorNamed16.Red => self.initRGB(170, 0, 0), ColorNamed16.Green => self.initRGB(0, 170, 0), ColorNamed16.Yellow => self.initRGB(170, 85, 0), ColorNamed16.Blue => self.initRGB(0, 0, 170), ColorNamed16.Magenta => self.initRGB(170, 0, 170), ColorNamed16.Cyan => self.initRGB(0, 170, 170), ColorNamed16.White => self.initRGB(170, 170, 170), ColorNamed16.BrightBlack => self.initRGB(85, 85, 85), ColorNamed16.BrightRed => self.initRGB(255, 85, 85), ColorNamed16.BrightGreen => self.initRGB(85, 255, 85), ColorNamed16.BrightYellow => self.initRGB(255, 255, 85), ColorNamed16.BrightBlue => self.initRGB(85, 85, 255), ColorNamed16.BrightMagenta => self.initRGB(255, 85, 255), ColorNamed16.BrightCyan => self.initRGB(85, 255, 255), ColorNamed16.BrightWhite => self.initRGB(255, 255, 255), }; } };
src/view/style.zig
const std = @import("std"); const mem = std.mem; const Allocator = mem.Allocator; const assert = std.debug.assert; const print = std.debug.print; const data = @embedFile("data/day12.txt"); const EntriesList = std.ArrayList(Record); const Record = struct { x: usize = 0, }; const north: u32 = 0; const east: u32 = 1; const south: u32 = 2; const west: u32 = 3; const left = [_]u32 { west, north, east, south }; const back = [_]u32 { south, west, north, east }; const right = [_]u32 { east, south, west, north }; const x = [_]i32 { 0, 1, 0, -1 }; const y = [_]i32 { 1, 0, -1, 0 }; pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const ally = &arena.allocator; var sx: i32 = 0; var sy: i32 = 0; var wx: i32 = 10; var wy: i32 = 1; var lines = std.mem.tokenize(data, "\r\n"); var entries = EntriesList.init(ally); try entries.ensureCapacity(400); var result: usize = 0; var forward = east; while (lines.next()) |line| { if (line.len == 0) continue; var code = line[0]; const amt = try std.fmt.parseUnsigned(u32, line[1..], 10); if (code == 'L') { if (amt == 270) code = 'R' else if (amt == 180) code = 'B' else assert(amt == 90); } else if (code == 'R') { if (amt == 270) code = 'L' else if (amt == 180) code = 'B' else assert(amt == 90); } var direction: ?u32 = null; switch (code) { 'F' => { sx += @intCast(i32, amt) * wx; sy += @intCast(i32, amt) * wy; }, 'N' => direction = north, 'E' => direction = east, 'W' => direction = west, 'S' => direction = south, 'R' => { var tmp = wy; wy = -wx; wx = tmp; }, 'L' => { var tmp = wx; wx = -wy; wy = tmp; }, 'B' => { wx = -wx; wy = -wy; }, else => unreachable, } if (direction) |d| { wx += @intCast(i32, amt) * x[d]; wy += @intCast(i32, amt) * y[d]; } //print("{c} {} ({}, {}) face {}\n", .{code, }) } print("x: {}, y: {}\n", .{sx, sy}); }
src/day12.zig
pub const PspCtrlButtons = extern enum(c_uint) { Select = 1, Start = 8, Up = 16, Right = 32, Down = 64, Left = 128, LTrigger = 256, RTrigger = 512, Triangle = 4096, Circle = 8192, Cross = 16384, Square = 32768, Home = 65536, Hold = 131072, Note = 8388608, Screen = 4194304, VolUp = 1048576, VolDown = 2097152, WlanUp = 262144, Remote = 524288, Disc = 16777216, Ms = 33554432, }; pub const PspCtrlMode = extern enum(c_int) { Digital = 0, Analog = 1, }; pub const SceCtrlData = extern struct { timeStamp: c_uint, buttons: c_uint, Lx: u8, Ly: u8, Rsrv: [6]u8, }; pub const SceCtrlLatch = extern struct { uiMake: c_uint, uiBreak: c_uint, uiPress: c_uint, uiRelease: c_uint, }; // Set the controller cycle setting. // // @param cycle - Cycle. Normally set to 0. // // @return The previous cycle setting. pub extern fn sceCtrlSetSamplingCycle(cycle: c_int) c_int; // Get the controller current cycle setting. // // @param pcycle - Return value. // // @return 0. pub extern fn sceCtrlGetSamplingCycle(pcycle: *c_int) c_int; // Set the controller mode. // // @param mode - One of ::PspCtrlMode. // // @return The previous mode. pub extern fn sceCtrlSetSamplingMode(mode: c_int) c_int; pub fn ctrlSetSamplingMode(mode: PspCtrlMode) PspCtrlMode { @setRuntimeSafety(false); var res = sceCtrlSetSamplingMode(@enumToInt(mode)); return @intToEnum(PspCtrlMode, res); } // Get the current controller mode. // // @param pmode - Return value. // // @return 0. pub extern fn sceCtrlGetSamplingMode(pmode: *c_int) c_int; pub extern fn sceCtrlPeekBufferPositive(pad_data: *SceCtrlData, count: c_int) c_int; pub extern fn sceCtrlPeekBufferNegative(pad_data: *SceCtrlData, count: c_int) c_int; // Read buffer positive // C Example: // SceCtrlData pad; // sceCtrlSetSamplingCycle(0); // sceCtrlSetSamplingMode(1); // sceCtrlReadBufferPositive(&pad, 1); // @param pad_data - Pointer to a ::SceCtrlData structure used hold the returned pad data. // @param count - Number of ::SceCtrlData buffers to read. pub extern fn sceCtrlReadBufferPositive(pad_data: *SceCtrlData, count: c_int) c_int; pub extern fn sceCtrlReadBufferNegative(pad_data: *SceCtrlData, count: c_int) c_int; pub extern fn sceCtrlPeekLatch(latch_data: *SceCtrlLatch) c_int; pub extern fn sceCtrlReadLatch(latch_data: *SceCtrlLatch) c_int; // Set analog threshold relating to the idle timer. // // @param idlereset - Movement needed by the analog to reset the idle timer. // @param idleback - Movement needed by the analog to bring the PSP back from an idle state. // // Set to -1 for analog to not cancel idle timer. // Set to 0 for idle timer to be cancelled even if the analog is not moved. // Set between 1 - 128 to specify the movement on either axis needed by the analog to fire the event. // // @return < 0 on error. pub extern fn sceCtrlSetIdleCancelThreshold(idlereset: c_int, idleback: c_int) c_int; pub fn ctrlSetIdleCancelThreshold(idlereset: c_int, idleback: c_int) !i32 { var res = sceCtrlSetIdleCancelThreshold(idlereset, idleback); if (res < 0) { return error.Unexpected; } return res; } // Get the idle threshold values. // // @param idlerest - Movement needed by the analog to reset the idle timer. // @param idleback - Movement needed by the analog to bring the PSP back from an idle state. // // @return < 0 on error. pub extern fn sceCtrlGetIdleCancelThreshold(idlerest: *c_int, idleback: *c_int) c_int; pub fn ctrlGetIdleCancelThreshold(idlerest: *c_int, idleback: *c_int) !i32 { var res = sceCtrlGetIdleCancelThreshold(idlereset, idleback); if (res < 0) { return error.Unexpected; } return res; }
src/psp/sdk/pspctrl.zig
const std = @import("std"); const testing = std.testing; const os = std.os; const io = std.io; const mem = std.mem; const net = std.net; const assert = std.debug.assert; const kisa = @import("kisa"); const rpc = @import("rpc.zig"); const state = @import("state.zig"); const Config = @import("config.zig").Config; const transport = @import("transport.zig"); pub const MoveDirection = enum { up, down, left, right, }; /// A high-level abstraction which accepts a frontend and provides a set of functions to operate on /// the frontent. Frontend itself contains all low-level functions which might not be all useful /// in a high-level interaction context. pub const UI = struct { frontend: UIVT100, pub const Error = UIVT100.Error; const Self = @This(); pub fn init(frontend: UIVT100) Self { return .{ .frontend = frontend }; } pub fn draw(self: *Self, string: []const u8, first_line_number: u32, max_line_number: u32) !void { _ = self; _ = string; _ = first_line_number; _ = max_line_number; } pub inline fn textAreaRows(self: Self) u32 { return self.frontend.textAreaRows(); } pub inline fn textAreaCols(self: Self) u32 { return self.frontend.textAreaCols(); } pub inline fn nextKey(self: *Self) ?kisa.Key { return self.frontend.nextKey(); } pub fn moveCursor(self: *Self, direction: MoveDirection, number: u32) !void { try self.frontend.moveCursor(direction, number); try self.frontend.refresh(); } pub inline fn setup(self: *Self) !void { try self.frontend.setup(); } pub inline fn teardown(self: *Self) void { self.frontend.teardown(); } }; /// Commands and occasionally queries is a general interface for interacting with the State /// of a text editor. pub const Commands = struct { workspace: *state.Workspace, const Self = @This(); pub fn openFile( self: Self, client: *Server.ClientRepresentation, path: []const u8, ) !void { // TODO: open existing text buffer. client.state.active_display_state = self.workspace.newTextBuffer( client.state.active_display_state, state.TextBuffer.InitParams{ .path = path, .name = path, .contents = null, }, ) catch |err| switch (err) { error.InitParamsMustHaveEitherPathOrContent => return error.InvalidParams, error.SharingViolation, error.OutOfMemory, error.OperationAborted, error.NotOpenForReading, error.InputOutput, 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, }; try client.send(rpc.ackResponse(client.last_request_id)); } // TODO: draw real data. pub fn redraw(self: Self, client: *Server.ClientRepresentation) !void { const draw_data = self.workspace.draw(client.state.active_display_state); const message = rpc.response(kisa.DrawData, client.last_request_id, draw_data); try client.send(message); } // TODO: use multiplier. // TODO: draw real data. pub fn cursorMoveDown(self: Self, client: *Server.ClientRepresentation, multiplier: u32) !void { _ = multiplier; try self.redraw(client); } }; pub const Server = struct { ally: *mem.Allocator, config: Config, watcher: transport.Watcher, workspace: state.Workspace, clients: std.ArrayList(state.Client), commands: Commands, last_client_id: state.Workspace.Id = 0, const Self = @This(); pub const ClientRepresentation = struct { comms: transport.CommunicationResources, state: *state.Client, last_request_id: u32 = 0, pub usingnamespace transport.CommunicationMixin(@This()); }; /// `initDynamic` must be called right after `init`. pub fn init(ally: *mem.Allocator, address: *net.Address) !Self { defer ally.destroy(address); const listen_socket = try transport.bindUnixSocket(address); var watcher = transport.Watcher.init(ally); try watcher.addListenSocket(listen_socket, 0); var workspace = state.Workspace.init(ally); try workspace.initDefaultBuffers(); return Self{ .ally = ally, .config = try readConfig(ally), .watcher = watcher, .workspace = workspace, .clients = std.ArrayList(state.Client).init(ally), .commands = undefined, }; } /// Initializes all the elements with dynamic memory which would require to reference /// objects from the stack if it were in `init`, resulting in error. /// Must be called right after `init`. pub fn initDynamic(self: *Self) void { self.commands = Commands{ .workspace = &self.workspace }; } pub fn deinit(self: *Self) void { self.config.deinit(); self.watcher.deinit(); self.workspace.deinit(); for (self.clients.items) |*client| client.deinit(); self.clients.deinit(); } fn findClient(self: Self, id: state.Workspace.Id) ?ClientRepresentation { const watcher_result = self.watcher.findFileDescriptor(id) orelse return null; const client = blk: { for (self.clients.items) |*client| { if (client.id == id) { break :blk client; } } return null; }; return ClientRepresentation{ .comms = transport.CommunicationResources.initWithUnixSocket(watcher_result.fd), .state = client, }; } fn addClient( self: *Self, id: state.Workspace.Id, socket: os.socket_t, active_display_state: state.ActiveDisplayState, ) !ClientRepresentation { try self.watcher.addConnectionSocket(socket, id); errdefer self.watcher.removeFileDescriptor(id); const client = try self.clients.addOne(); client.* = state.Client{ .id = id, .active_display_state = active_display_state }; return ClientRepresentation{ .comms = transport.CommunicationResources.initWithUnixSocket(socket), .state = client, }; } fn removeClient(self: *Self, id: state.Workspace.Id) void { self.watcher.removeFileDescriptor(id); for (self.clients.items) |client, idx| { if (client.id == id) { _ = self.clients.swapRemove(idx); break; } } } /// Main loop of the server, listens for requests and sends responses. pub fn loop(self: *Self) !void { var packet_buf: [transport.max_packet_size]u8 = undefined; var method_buf: [transport.max_method_size]u8 = undefined; var message_buf: [transport.max_message_size]u8 = undefined; while (true) { switch ((try self.watcher.pollReadable(-1)).?) { .success => |polled_data| { switch (polled_data.ty) { .listen_socket => { try self.processNewConnection(polled_data.fd); }, .connection_socket => { var client = self.findClient(polled_data.id).?; self.processClientRequest( &client, &packet_buf, &method_buf, &message_buf, ) catch |err| switch (err) { error.ShouldQuit => break, // Some errors are programming errors. // We don't send non-blocking responses to clients, always block. error.WouldBlock, error.MessageTooBig, // XXX: This error is caught inside Commands, probably a bug that // compiler complains about it not being caught here. error.InitParamsMustHaveEitherPathOrContent, => unreachable, // For these errors the client is probably wrong and we can send // an error message explaining why. error.EmptyPacket, error.NullIdInRequest, error.ParseError, error.InvalidRequest, error.MethodNotFound, error.InvalidParams, error.InvalidUtf8, error.BadPathName, error.NoSpaceLeft, error.DeviceBusy, error.NoDevice, error.NameTooLong, error.FileNotFound, error.SystemFdQuotaExceeded, error.ProcessFdQuotaExceeded, error.SymLinkLoop, error.SharingViolation, error.InputOutput, error.NotOpenForReading, error.OperationAborted, error.IsDir, error.FileTooBig, error.UninitializedClient, => |e| { client.send(rpc.errorResponse(client.state.id, e)) catch { std.debug.print( "Failed to send error response to client ID {d}: {s}", .{ client.state.id, @errorName(err) }, ); }; }, // These errors indicate that we can't use this socket connection. error.BrokenPipe, error.ConnectionResetByPeer, error.AccessDenied, error.NetworkSubsystemFailed, error.SocketNotConnected, error.SocketNotBound, error.ConnectionRefused, => { self.removeClient(polled_data.id); if (self.watcher.fds.len == 1) { self.deinit(); break; } }, // Some errors are unrecoverable or seem impossible. error.FastOpenAlreadyInProgress, error.SystemResources, error.FileDescriptorNotASocket, error.NetworkUnreachable, error.Unexpected, error.OutOfMemory, => return err, }; }, } }, .err => |polled_data| { self.removeClient(polled_data.id); if (self.watcher.fds.len == 1) { self.deinit(); break; } }, } } } fn processNewConnection(self: *Self, polled_fd: os.socket_t) !void { const accepted_socket = try os.accept(polled_fd, null, null, 0); const client_id = self.nextClientId(); const client = try self.addClient( client_id, accepted_socket, // This `empty` is similar to `undefined`, we can't use it and have // to initialize first. With `empty` errors should be better. We can // also make it nullable but it's a pain to always account for a // nullable field. state.ActiveDisplayState.empty, ); errdefer self.removeClient(client_id); try client.send(rpc.ackResponse(client.last_request_id)); } fn processClientRequest( self: *Self, client: *ClientRepresentation, packet_buf: []u8, method_buf: []u8, message_buf: []u8, ) !void { const packet = (try client.readPacket(packet_buf)) orelse return error.EmptyPacket; if (rpc.parseId(packet)) |request_id| { client.last_request_id = request_id orelse return error.NullIdInRequest; } else |err| switch (err) { // Could be a notification with absent ID. error.MissingField => client.last_request_id = 0, error.ParseError => return error.ParseError, } const method_str = try rpc.parseMethod(method_buf, packet); const method = std.meta.stringToEnum( kisa.CommandKind, method_str, ) orelse { std.debug.print("Unknown rpc method from client: {s}\n", .{method_str}); return error.MethodNotFound; }; if (method != .initialize and std.meta.eql(client.state.active_display_state, state.ActiveDisplayState.empty)) { return error.UninitializedClient; } switch (method) { .open_file => { const command = try rpc.parseCommandFromRequest(.open_file, message_buf, packet); try self.commands.openFile(client, command.open_file.path); }, .redraw => { try self.commands.redraw(client); }, .keypress => { const key_command = try rpc.parseCommandFromRequest(.keypress, message_buf, packet); const command = self.config.resolveKey(key_command.keypress.key); switch (command) { .cursor_move_down => { try self.commands.cursorMoveDown(client, key_command.keypress.multiplier); }, else => @panic("Not implemented"), } }, .initialize => { const command = try rpc.parseCommandFromRequest(.initialize, message_buf, packet); const client_init_params = command.initialize; for (self.clients.items) |*c| { if (client.state.id == c.id) { c.active_display_state = try self.workspace.new( state.TextBuffer.InitParams{ .contents = null, .path = client_init_params.path, .name = client_init_params.path, .readonly = client_init_params.readonly, }, state.WindowPane.InitParams{ .text_area_rows = client_init_params.text_area_rows, .text_area_cols = client_init_params.text_area_cols, }, ); break; } } try client.send(rpc.ackResponse(client.last_request_id)); }, .quitted => { self.removeClient(client.state.id); if (self.watcher.fds.len == 1) { self.deinit(); return error.ShouldQuit; } }, else => @panic("Not implemented"), } } fn readConfig(ally: *mem.Allocator) !Config { // var path_buf: [256]u8 = undefined; // const path = try std.fs.cwd().realpath("kisarc.zzz", &path_buf); var config = Config.init(ally); try config.setup(); try config.addConfig(@embedFile("../kisarc.zzz"), true); // try config.addConfigFile(path); return config; } // Ids start at 1 so that for `Watcher` 0 is reserved for a listen socket. fn nextClientId(self: *Self) state.Workspace.Id { self.last_client_id += 1; return self.last_client_id; } }; pub const Application = struct { client: Client, /// In threaded mode we call `join` on `deinit`. In not threaded mode this field is `null`. server_thread: ?*std.Thread = null, // This is post 0.8 version. // server_thread: ?std.Thread = null, const Self = @This(); pub const ConcurrencyModel = enum { threaded, forked, }; /// Start `Server` instance on background and `Client` instance on foreground. This function /// returns `null` when it launches a server instance and no actions should be performed, /// currently it is only relevant for `forked` concurrency model. When this function returns /// `Application` instance, this is client code. pub fn start( ally: *mem.Allocator, concurrency_model: ConcurrencyModel, ) !?Self { const unix_socket_path = try transport.pathForUnixSocket(ally); defer ally.free(unix_socket_path); const address = try transport.addressForUnixSocket(ally, unix_socket_path); switch (concurrency_model) { .forked => { const child_pid = try os.fork(); if (child_pid == 0) { // Server // Close stdout and stdin on the server since we don't use them. os.close(io.getStdIn().handle); os.close(io.getStdOut().handle); // This is post 0.8 version. // try startServer(ally, address); try startServer(.{ .ally = ally, .address = address }); return null; } else { // Client var uivt100 = try UIVT100.init(); var ui = UI.init(uivt100); var client = Client.init(ally, ui); try client.register(address); return Self{ .client = client }; } }, .threaded => { // This is post 0.8 version. // const server_thread = try std.Thread.spawn(.{}, startServer, .{ ally, address }); const server_thread = try std.Thread.spawn(startServer, .{ .ally = ally, .address = address }); var uivt100 = try UIVT100.init(); var ui = UI.init(uivt100); var client = Client.init(ally, ui); const address_for_client = try ally.create(net.Address); address_for_client.* = address.*; try client.register(address_for_client); return Self{ .client = client, .server_thread = server_thread }; }, } unreachable; } fn startServer(arg: struct { ally: *mem.Allocator, address: *net.Address }) !void { var server = try Server.init(arg.ally, arg.address); server.initDynamic(); errdefer server.deinit(); try server.loop(); } pub fn deinit(self: *Self) void { self.client.deinit(); if (self.server_thread) |server_thread| { // This is post 0.8 version. // server_thread.join(); server_thread.wait(); self.server_thread = null; } } }; pub const Client = struct { ally: *mem.Allocator, ui: UI, server: ServerForClient, watcher: transport.Watcher, last_message_id: u32 = 0, const Self = @This(); /// How Client sees the Server. pub const ServerForClient = struct { comms: transport.CommunicationResources, pub usingnamespace transport.CommunicationMixin(@This()); }; pub fn init(ally: *mem.Allocator, ui: UI) Self { return Self{ .ally = ally, .ui = ui, .watcher = transport.Watcher.init(ally), .server = undefined, }; } pub fn deinit(self: *Self) void { const message = rpc.emptyNotification("quitted"); self.server.send(message) catch {}; // TEST: Check for race conditions. // std.time.sleep(std.time.ns_per_s * 1); self.watcher.deinit(); } pub fn register(self: *Self, address: *net.Address) !void { defer self.ally.destroy(address); self.server = ServerForClient.initWithUnixSocket( try transport.connectToUnixSocket(address), ); var request_buf: [transport.max_message_size]u8 = undefined; // Here we custom checking instead of waitForResponse because we expect `null` id which // is the single place where `null` in id is allowed for successful response. const response = (try self.server.recv(rpc.EmptyResponse, &request_buf)).?; assert(response == .Success); const message_id = self.nextMessageId(); const message = rpc.commandRequest( .initialize, message_id, .{ .path = "/home/grfork/reps/kisa/kisarc.zzz", .readonly = false, .text_area_rows = 80, .text_area_cols = 24, }, ); try self.server.send(message); try self.waitForResponse(message_id); try self.watcher.addConnectionSocket(self.server.comms.un_socket.socket, 0); } /// Main loop of the client, listens for keypresses and sends requests. pub fn loop(self: *Self) !void { var packet_buf: [transport.max_packet_size]u8 = undefined; var method_buf: [transport.max_method_size]u8 = undefined; var message_buf: [transport.max_message_size]u8 = undefined; while (true) { if (try self.watcher.pollReadable(5)) |poll_result| { switch (poll_result) { .success => |polled_data| { switch (polled_data.ty) { .listen_socket => unreachable, .connection_socket => { // TODO: process incoming notifications from the server. }, } }, .err => { return error.ServerClosedConnection; }, } } if (self.ui.nextKey()) |key| { switch (key.code) { .unicode_codepoint => { if (key.isCtrl('c')) { break; } // TODO: work with multiplier. _ = try client.keypress(key, 1); }, else => { std.debug.print("Unrecognized key: {}\r\n", .{key}); return error.UnrecognizedKey; }, } } } } pub fn keypress(self: *Self, key: kisa.Key, multiplier: u32) !kisa.DrawData { const id = self.nextMessageId(); const message = rpc.commandRequest(.keypress, id, .{ .key = key, .multiplier = multiplier }); try self.server.send(message); return try self.receiveDrawData(id); } // It only returns `DrawData` for testing purposes, probably should be `void` instead. pub fn edit(self: *Client, path: []const u8) !kisa.DrawData { try self.openFile(path); return try self.redraw(); } fn openFile(self: *Client, path: []const u8) !void { const id = self.nextMessageId(); const message = rpc.commandRequest(.open_file, id, .{ .path = path }); try self.server.send(message); try self.waitForResponse(id); } pub fn redraw(self: *Client) !kisa.DrawData { const id = self.nextMessageId(); const message = rpc.emptyCommandRequest(.redraw, id); try self.server.send(message); return try self.receiveDrawData(@intCast(u32, id)); } fn receiveDrawData(self: *Client, id: u32) !kisa.DrawData { var message_buf: [transport.max_message_size]u8 = undefined; // TODO: better API for response construction const response = try self.receiveResponse(id, rpc.Response(kisa.DrawData), &message_buf); return response.Success.result; } fn waitForResponse(self: *Self, id: u32) !void { var message_buf: [transport.max_message_size]u8 = undefined; const response = (try self.server.recv( rpc.EmptyResponse, &message_buf, )) orelse return error.ServerClosedConnection; switch (response) { .Success => |s| { if (s.id) |response_id| { if (!std.meta.eql(id, response_id)) return error.InvalidResponseId; } else { return error.ReceivedNullId; } }, .Error => return error.ErrorResponse, } } fn receiveResponse( self: *Self, id: u32, comptime Message: type, message_buf: []u8, ) !Message { const response = (try self.server.recv( Message, message_buf, )) orelse return error.ServerClosedConnection; switch (response) { .Success => |s| { if (!std.meta.eql(id, s.id.?)) return error.InvalidResponseId; return response; }, .Error => return error.ErrorResponse, } } pub fn nextMessageId(self: *Self) u32 { self.last_message_id += 1; return self.last_message_id; } }; test "main: start application threaded via socket" { if (try Application.start(testing.allocator, .threaded)) |*app| { defer app.deinit(); var client = app.client; { const draw_data = try client.edit("/home/grfork/reps/kisa/kisarc.zzz"); try testing.expectEqual(@as(usize, 1), draw_data.lines.len); try testing.expectEqual(@as(u32, 1), draw_data.lines[0].number); try testing.expectEqualStrings("hello", draw_data.lines[0].contents); } { const draw_data = try client.keypress(kisa.Key.ascii('j'), 1); try testing.expectEqual(@as(usize, 1), draw_data.lines.len); try testing.expectEqual(@as(u32, 1), draw_data.lines[0].number); try testing.expectEqualStrings("hello", draw_data.lines[0].contents); } } } test "fork/socket: start application forked via socket" { if (try Application.start(testing.allocator, .forked)) |*app| { defer app.deinit(); var client = app.client; { const draw_data = try client.edit("/home/grfork/reps/kisa/kisarc.zzz"); try testing.expectEqual(@as(usize, 1), draw_data.lines.len); try testing.expectEqual(@as(u32, 1), draw_data.lines[0].number); try testing.expectEqualStrings("hello", draw_data.lines[0].contents); } { const draw_data = try client.keypress(kisa.Key.ascii('j'), 1); try testing.expectEqual(@as(usize, 1), draw_data.lines.len); try testing.expectEqual(@as(u32, 1), draw_data.lines[0].number); try testing.expectEqualStrings("hello", draw_data.lines[0].contents); } } } pub fn main() anyerror!void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var ally = &gpa.allocator; var arg_it = std.process.args(); _ = try arg_it.next(ally) orelse unreachable; const filename = blk: { if (arg_it.next(ally)) |file_name_delimited| { break :blk try std.fs.cwd().realpathAlloc(ally, try file_name_delimited); } else { break :blk null; } }; if (filename) |fname| { std.debug.print("Supplied filename: {s}\n", .{fname}); } else { std.debug.print("No filename Supplied\n", .{}); } std.debug.print("So far nothing in `main`, try `zig build test`\n", .{}); } /// UI frontent. VT100 is an old hardware terminal from 1978. Although it lacks a lot of capabilities /// which are exposed in this implementation, such as colored output, it established a standard /// of ASCII escape sequences which is implemented in most terminal emulators as of today. /// Later this standard was extended and this implementation is a common denominator that is /// likely to be supported in most terminal emulators. pub const UIVT100 = struct { in_stream: std.fs.File, out_stream: std.fs.File, original_termois: ?os.termios, buffered_writer_ctx: RawBufferedWriterCtx, rows: u32, cols: u32, pub const Error = error{ NotTTY, NoAnsiEscapeSequences, NoWindowSize, } || os.TermiosSetError || std.fs.File.WriteError; const Self = @This(); const write_buffer_size = 4096; /// Control Sequence Introducer, see console_codes(4) const csi = "\x1b["; const status_line_width = 1; pub fn init() Error!Self { const in_stream = io.getStdIn(); const out_stream = io.getStdOut(); if (!in_stream.isTty()) return Error.NotTTY; if (!out_stream.supportsAnsiEscapeCodes()) return Error.NoAnsiEscapeSequences; var uivt100 = UIVT100{ .in_stream = in_stream, .out_stream = out_stream, .original_termois = try os.tcgetattr(in_stream.handle), .buffered_writer_ctx = RawBufferedWriterCtx{ .unbuffered_writer = out_stream.writer() }, .rows = undefined, .cols = undefined, }; try uivt100.updateWindowSize(); return uivt100; } pub fn setup(self: *Self) Error!void { // Black magic, see https://github.com/antirez/kilo var raw_termios = self.original_termois.?; raw_termios.iflag &= ~(@as(os.tcflag_t, os.BRKINT) | os.ICRNL | os.INPCK | os.ISTRIP | os.IXON); raw_termios.oflag &= ~(@as(os.tcflag_t, os.OPOST)); raw_termios.cflag |= os.CS8; raw_termios.lflag &= ~(@as(os.tcflag_t, os.ECHO) | os.ICANON | os.IEXTEN | os.ISIG); // Polling read, doesn't block raw_termios.cc[os.VMIN] = 0; raw_termios.cc[os.VTIME] = 0; try os.tcsetattr(self.in_stream.handle, os.TCSA.FLUSH, raw_termios); } pub fn teardown(self: *Self) void { if (self.original_termois) |termios| { os.tcsetattr(self.in_stream.handle, os.TCSA.FLUSH, termios) catch |err| { std.debug.print("UIVT100.teardown failed with {}\n", .{err}); }; self.original_termois = null; } } fn nextByte(self: *Self) ?u8 { return self.in_stream.reader().readByte() catch |err| switch (err) { error.EndOfStream => return null, error.NotOpenForReading => return null, else => { std.debug.print("Unexpected error: {}\r\n", .{err}); return 0; }, }; } pub fn nextKey(self: *Self) ?kisa.Key { if (self.nextByte()) |byte| { if (byte == 3) { return kisa.Key.ctrl('c'); } return kisa.Key.ascii(byte); } else { return null; } } // Do type magic to expose buffered writer in 2 modes: // * raw_writer - we don't try to do anything smart, mostly for console codes // * writer - we try to do what is expected when writing to a screen const RawUnbufferedWriter = io.Writer(std.fs.File, std.fs.File.WriteError, std.fs.File.write); const RawBufferedWriterCtx = io.BufferedWriter(write_buffer_size, RawUnbufferedWriter); pub const RawBufferedWriter = RawBufferedWriterCtx.Writer; pub const BufferedWriter = io.Writer(*UIVT100, RawBufferedWriterCtx.Error, writerfn); fn raw_writer(self: *Self) RawBufferedWriter { return self.buffered_writer_ctx.writer(); } pub fn writer(self: *Self) BufferedWriter { return .{ .context = self }; } fn writerfn(self: *Self, string: []const u8) !usize { for (string) |ch| { if (ch == '\n') try self.raw_writer().writeByte('\r'); try self.raw_writer().writeByte(ch); } return string.len; } pub fn clear(self: *Self) !void { try self.ccEraseDisplay(); try self.ccMoveCursor(1, 1); } // All our output is buffered, when we actually want to display something to the screen, // this function should be called. Buffered output is better for performance and it // avoids cursor flickering. // This function should not be used as a part of other functions inside a frontend // implementation. Instead it should be used inside `UI` for building more complex // control flows. pub fn refresh(self: *Self) !void { try self.buffered_writer_ctx.flush(); } pub fn textAreaRows(self: Self) u32 { return self.rows - status_line_width; } pub fn textAreaCols(self: Self) u32 { return self.cols; } pub fn moveCursor(self: *Self, direction: MoveDirection, number: u32) !void { switch (direction) { .up => { try self.ccMoveCursorUp(number); }, .down => { try self.ccMoveCursorDown(number); }, .right => { try self.ccMoveCursorRight(number); }, .left => { try self.ccMoveCursorLeft(number); }, } } fn getWindowSize(self: Self, rows: *u32, cols: *u32) !void { while (true) { var window_size: os.linux.winsize = undefined; const fd = @bitCast(usize, @as(isize, self.in_stream.handle)); switch (os.linux.syscall3(.ioctl, fd, os.linux.TIOCGWINSZ, @ptrToInt(&window_size))) { 0 => { rows.* = window_size.ws_row; cols.* = window_size.ws_col; return; }, os.EINTR => continue, else => return Error.NoWindowSize, } } } fn updateWindowSize(self: *Self) !void { var rows: u32 = undefined; var cols: u32 = undefined; try self.getWindowSize(&rows, &cols); self.rows = rows; self.cols = cols; } // "cc" stands for "console code", see console_codes(4). // Some of the names clash with the desired names of public-facing API functions, // so we use a prefix to disambiguate them. Every console code should be in a separate // function so that it has a name and has an easy opportunity for parameterization. fn ccEraseDisplay(self: *Self) !void { try self.raw_writer().print("{s}2J", .{csi}); } fn ccMoveCursor(self: *Self, row: u32, col: u32) !void { try self.raw_writer().print("{s}{d};{d}H", .{ csi, row, col }); } fn ccMoveCursorUp(self: *Self, number: u32) !void { try self.raw_writer().print("{s}{d}A", .{ csi, number }); } fn ccMoveCursorDown(self: *Self, number: u32) !void { try self.raw_writer().print("{s}{d}B", .{ csi, number }); } fn ccMoveCursorRight(self: *Self, number: u32) !void { try self.raw_writer().print("{s}{d}C", .{ csi, number }); } fn ccMoveCursorLeft(self: *Self, number: u32) !void { try self.raw_writer().print("{s}{d}D", .{ csi, number }); } fn ccHideCursor(self: *Self) !void { try self.raw_writer().print("{s}?25l", .{csi}); } fn ccShowCursor(self: *Self) !void { try self.raw_writer().print("{s}?25h", .{csi}); } }; const help_string = \\Usage: kisa file \\ ; fn numberWidth(number: u32) u32 { var result: u32 = 0; var n = number; while (n != 0) : (n /= 10) { result += 1; } return result; }
src/main.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const mem = std.mem; const path = std.fs.path; const assert = std.debug.assert; const target_util = @import("target.zig"); const Compilation = @import("Compilation.zig"); const build_options = @import("build_options"); pub const CRTFile = enum { crti_o, crtn_o, crt1_o, rcrt1_o, scrt1_o, libc_a, }; pub fn buildCRTFile(comp: *Compilation, crt_file: CRTFile) !void { if (!build_options.have_llvm) { return error.ZigCompilerNotBuiltWithLLVMExtensions; } const gpa = comp.gpa; var arena_allocator = std.heap.ArenaAllocator.init(gpa); defer arena_allocator.deinit(); const arena = &arena_allocator.allocator; switch (crt_file) { .crti_o => { var args = std.ArrayList([]const u8).init(arena); try add_cc_args(comp, arena, &args, false); try args.appendSlice(&[_][]const u8{ "-Qunused-arguments", }); return comp.build_crt_file("crti", .Obj, &[1]Compilation.CSourceFile{ .{ .src_path = try start_asm_path(comp, arena, "crti.s"), .extra_flags = args.items, }, }); }, .crtn_o => { var args = std.ArrayList([]const u8).init(arena); try add_cc_args(comp, arena, &args, false); try args.appendSlice(&[_][]const u8{ "-Qunused-arguments", }); return comp.build_crt_file("crtn", .Obj, &[1]Compilation.CSourceFile{ .{ .src_path = try start_asm_path(comp, arena, "crtn.s"), .extra_flags = args.items, }, }); }, .crt1_o => { var args = std.ArrayList([]const u8).init(arena); try add_cc_args(comp, arena, &args, false); try args.appendSlice(&[_][]const u8{ "-fno-stack-protector", "-DCRT", }); return comp.build_crt_file("crt1", .Obj, &[1]Compilation.CSourceFile{ .{ .src_path = try comp.zig_lib_directory.join(arena, &[_][]const u8{ "libc", "musl", "crt", "crt1.c", }), .extra_flags = args.items, }, }); }, .rcrt1_o => { var args = std.ArrayList([]const u8).init(arena); try add_cc_args(comp, arena, &args, false); try args.appendSlice(&[_][]const u8{ "-fPIC", "-fno-stack-protector", "-DCRT", }); return comp.build_crt_file("rcrt1", .Obj, &[1]Compilation.CSourceFile{ .{ .src_path = try comp.zig_lib_directory.join(arena, &[_][]const u8{ "libc", "musl", "crt", "rcrt1.c", }), .extra_flags = args.items, }, }); }, .scrt1_o => { var args = std.ArrayList([]const u8).init(arena); try add_cc_args(comp, arena, &args, false); try args.appendSlice(&[_][]const u8{ "-fPIC", "-fno-stack-protector", "-DCRT", }); return comp.build_crt_file("Scrt1", .Obj, &[1]Compilation.CSourceFile{ .{ .src_path = try comp.zig_lib_directory.join(arena, &[_][]const u8{ "libc", "musl", "crt", "Scrt1.c", }), .extra_flags = args.items, }, }); }, .libc_a => { // When there is a src/<arch>/foo.* then it should substitute for src/foo.* // Even a .s file can substitute for a .c file. const target = comp.getTarget(); const arch_name = target_util.archMuslName(target.cpu.arch); var source_table = std.StringArrayHashMap(Ext).init(comp.gpa); defer source_table.deinit(); try source_table.ensureCapacity(compat_time32_files.len + src_files.len); for (src_files) |src_file| { try addSrcFile(arena, &source_table, src_file); } const time32_compat_arch_list = [_][]const u8{ "arm", "i386", "mips", "powerpc" }; for (time32_compat_arch_list) |time32_compat_arch| { if (mem.eql(u8, arch_name, time32_compat_arch)) { for (compat_time32_files) |compat_time32_file| { try addSrcFile(arena, &source_table, compat_time32_file); } } } var c_source_files = std.ArrayList(Compilation.CSourceFile).init(comp.gpa); defer c_source_files.deinit(); var override_path = std.ArrayList(u8).init(comp.gpa); defer override_path.deinit(); const s = path.sep_str; for (source_table.items()) |entry| { const src_file = entry.key; const ext = entry.value; const dirname = path.dirname(src_file).?; const basename = path.basename(src_file); const noextbasename = mem.split(basename, ".").next().?; const before_arch_dir = path.dirname(dirname).?; const dirbasename = path.basename(dirname); var is_arch_specific = false; // Architecture-specific implementations are under a <arch>/ folder. if (is_musl_arch_name(dirbasename)) { if (!mem.eql(u8, dirbasename, arch_name)) continue; // Not the architecture we're compiling for. is_arch_specific = true; } if (!is_arch_specific) { // Look for an arch specific override. override_path.shrinkRetainingCapacity(0); try override_path.writer().print("{}" ++ s ++ "{}" ++ s ++ "{}.s", .{ dirname, arch_name, noextbasename, }); if (source_table.contains(override_path.items)) continue; override_path.shrinkRetainingCapacity(0); try override_path.writer().print("{}" ++ s ++ "{}" ++ s ++ "{}.S", .{ dirname, arch_name, noextbasename, }); if (source_table.contains(override_path.items)) continue; override_path.shrinkRetainingCapacity(0); try override_path.writer().print("{}" ++ s ++ "{}" ++ s ++ "{}.c", .{ dirname, arch_name, noextbasename, }); if (source_table.contains(override_path.items)) continue; } var args = std.ArrayList([]const u8).init(arena); try add_cc_args(comp, arena, &args, ext == .o3); try args.appendSlice(&[_][]const u8{ "-Qunused-arguments", "-w", // disable all warnings }); const c_source_file = try c_source_files.addOne(); c_source_file.* = .{ .src_path = try comp.zig_lib_directory.join(arena, &[_][]const u8{ "libc", src_file }), .extra_flags = args.items, }; } return comp.build_crt_file("c", .Lib, c_source_files.items); }, } } fn is_musl_arch_name(name: []const u8) bool { const musl_arch_names = [_][]const u8{ "aarch64", "arm", "generic", "i386", "m68k", "microblaze", "mips", "mips64", "mipsn32", "or1k", "powerpc", "powerpc64", "riscv64", "s390x", "sh", "x32", "x86_64", }; for (musl_arch_names) |musl_arch_name| { if (mem.eql(u8, musl_arch_name, name)) { return true; } } return false; } const Ext = enum { assembly, normal, o3, }; fn addSrcFile(arena: *Allocator, source_table: *std.StringArrayHashMap(Ext), file_path: []const u8) !void { const ext: Ext = ext: { if (mem.endsWith(u8, file_path, ".c")) { if (mem.startsWith(u8, file_path, "musl/src/malloc/") or mem.startsWith(u8, file_path, "musl/src/string/") or mem.startsWith(u8, file_path, "musl/src/internal/")) { break :ext .o3; } else { break :ext .assembly; } } else if (mem.endsWith(u8, file_path, ".s") or mem.endsWith(u8, file_path, ".S")) { break :ext .assembly; } else { unreachable; } }; // TODO do this at comptime on the comptime data rather than at runtime // probably best to wait until self-hosted is done and our comptime execution // is faster and uses less memory. const key = if (path.sep != '/') blk: { const mutable_file_path = try arena.dupe(u8, file_path); for (mutable_file_path) |*c| { if (c.* == '/') { c.* = path.sep; } } break :blk mutable_file_path; } else file_path; source_table.putAssumeCapacityNoClobber(key, ext); } fn add_cc_args( comp: *Compilation, arena: *Allocator, args: *std.ArrayList([]const u8), want_O3: bool, ) error{OutOfMemory}!void { const target = comp.getTarget(); const arch_name = target_util.archMuslName(target.cpu.arch); const os_name = @tagName(target.os.tag); const triple = try std.fmt.allocPrint(arena, "{}-{}-musl", .{ arch_name, os_name }); const o_arg = if (want_O3) "-O3" else "-Os"; try args.appendSlice(&[_][]const u8{ "-std=c99", "-ffreestanding", // Musl adds these args to builds with gcc but clang does not support them. //"-fexcess-precision=standard", //"-frounding-math", "-Wa,--noexecstack", "-D_XOPEN_SOURCE=700", "-I", try comp.zig_lib_directory.join(arena, &[_][]const u8{ "libc", "musl", "arch", arch_name }), "-I", try comp.zig_lib_directory.join(arena, &[_][]const u8{ "libc", "musl", "arch", "generic" }), "-I", try comp.zig_lib_directory.join(arena, &[_][]const u8{ "libc", "musl", "src", "include" }), "-I", try comp.zig_lib_directory.join(arena, &[_][]const u8{ "libc", "musl", "src", "internal" }), "-I", try comp.zig_lib_directory.join(arena, &[_][]const u8{ "libc", "musl", "include" }), "-I", try comp.zig_lib_directory.join(arena, &[_][]const u8{ "libc", "include", triple }), "-I", try comp.zig_lib_directory.join(arena, &[_][]const u8{ "libc", "include", "generic-musl" }), o_arg, "-fomit-frame-pointer", "-fno-unwind-tables", "-fno-asynchronous-unwind-tables", "-ffunction-sections", "-fdata-sections", }); } fn start_asm_path(comp: *Compilation, arena: *Allocator, basename: []const u8) ![]const u8 { const target = comp.getTarget(); return comp.zig_lib_directory.join(arena, &[_][]const u8{ "libc", "musl", "crt", target_util.archMuslName(target.cpu.arch), basename, }); } const src_files = [_][]const u8{ "musl/src/aio/aio.c", "musl/src/aio/aio_suspend.c", "musl/src/aio/lio_listio.c", "musl/src/complex/__cexp.c", "musl/src/complex/__cexpf.c", "musl/src/complex/cabs.c", "musl/src/complex/cabsf.c", "musl/src/complex/cabsl.c", "musl/src/complex/cacos.c", "musl/src/complex/cacosf.c", "musl/src/complex/cacosh.c", "musl/src/complex/cacoshf.c", "musl/src/complex/cacoshl.c", "musl/src/complex/cacosl.c", "musl/src/complex/carg.c", "musl/src/complex/cargf.c", "musl/src/complex/cargl.c", "musl/src/complex/casin.c", "musl/src/complex/casinf.c", "musl/src/complex/casinh.c", "musl/src/complex/casinhf.c", "musl/src/complex/casinhl.c", "musl/src/complex/casinl.c", "musl/src/complex/catan.c", "musl/src/complex/catanf.c", "musl/src/complex/catanh.c", "musl/src/complex/catanhf.c", "musl/src/complex/catanhl.c", "musl/src/complex/catanl.c", "musl/src/complex/ccos.c", "musl/src/complex/ccosf.c", "musl/src/complex/ccosh.c", "musl/src/complex/ccoshf.c", "musl/src/complex/ccoshl.c", "musl/src/complex/ccosl.c", "musl/src/complex/cexp.c", "musl/src/complex/cexpf.c", "musl/src/complex/cexpl.c", "musl/src/complex/cimag.c", "musl/src/complex/cimagf.c", "musl/src/complex/cimagl.c", "musl/src/complex/clog.c", "musl/src/complex/clogf.c", "musl/src/complex/clogl.c", "musl/src/complex/conj.c", "musl/src/complex/conjf.c", "musl/src/complex/conjl.c", "musl/src/complex/cpow.c", "musl/src/complex/cpowf.c", "musl/src/complex/cpowl.c", "musl/src/complex/cproj.c", "musl/src/complex/cprojf.c", "musl/src/complex/cprojl.c", "musl/src/complex/creal.c", "musl/src/complex/crealf.c", "musl/src/complex/creall.c", "musl/src/complex/csin.c", "musl/src/complex/csinf.c", "musl/src/complex/csinh.c", "musl/src/complex/csinhf.c", "musl/src/complex/csinhl.c", "musl/src/complex/csinl.c", "musl/src/complex/csqrt.c", "musl/src/complex/csqrtf.c", "musl/src/complex/csqrtl.c", "musl/src/complex/ctan.c", "musl/src/complex/ctanf.c", "musl/src/complex/ctanh.c", "musl/src/complex/ctanhf.c", "musl/src/complex/ctanhl.c", "musl/src/complex/ctanl.c", "musl/src/conf/confstr.c", "musl/src/conf/fpathconf.c", "musl/src/conf/legacy.c", "musl/src/conf/pathconf.c", "musl/src/conf/sysconf.c", "musl/src/crypt/crypt.c", "musl/src/crypt/crypt_blowfish.c", "musl/src/crypt/crypt_des.c", "musl/src/crypt/crypt_md5.c", "musl/src/crypt/crypt_r.c", "musl/src/crypt/crypt_sha256.c", "musl/src/crypt/crypt_sha512.c", "musl/src/crypt/encrypt.c", "musl/src/ctype/__ctype_b_loc.c", "musl/src/ctype/__ctype_get_mb_cur_max.c", "musl/src/ctype/__ctype_tolower_loc.c", "musl/src/ctype/__ctype_toupper_loc.c", "musl/src/ctype/isalnum.c", "musl/src/ctype/isalpha.c", "musl/src/ctype/isascii.c", "musl/src/ctype/isblank.c", "musl/src/ctype/iscntrl.c", "musl/src/ctype/isdigit.c", "musl/src/ctype/isgraph.c", "musl/src/ctype/islower.c", "musl/src/ctype/isprint.c", "musl/src/ctype/ispunct.c", "musl/src/ctype/isspace.c", "musl/src/ctype/isupper.c", "musl/src/ctype/iswalnum.c", "musl/src/ctype/iswalpha.c", "musl/src/ctype/iswblank.c", "musl/src/ctype/iswcntrl.c", "musl/src/ctype/iswctype.c", "musl/src/ctype/iswdigit.c", "musl/src/ctype/iswgraph.c", "musl/src/ctype/iswlower.c", "musl/src/ctype/iswprint.c", "musl/src/ctype/iswpunct.c", "musl/src/ctype/iswspace.c", "musl/src/ctype/iswupper.c", "musl/src/ctype/iswxdigit.c", "musl/src/ctype/isxdigit.c", "musl/src/ctype/toascii.c", "musl/src/ctype/tolower.c", "musl/src/ctype/toupper.c", "musl/src/ctype/towctrans.c", "musl/src/ctype/wcswidth.c", "musl/src/ctype/wctrans.c", "musl/src/ctype/wcwidth.c", "musl/src/dirent/alphasort.c", "musl/src/dirent/closedir.c", "musl/src/dirent/dirfd.c", "musl/src/dirent/fdopendir.c", "musl/src/dirent/opendir.c", "musl/src/dirent/readdir.c", "musl/src/dirent/readdir_r.c", "musl/src/dirent/rewinddir.c", "musl/src/dirent/scandir.c", "musl/src/dirent/seekdir.c", "musl/src/dirent/telldir.c", "musl/src/dirent/versionsort.c", "musl/src/env/__environ.c", "musl/src/env/__init_tls.c", "musl/src/env/__libc_start_main.c", "musl/src/env/__reset_tls.c", "musl/src/env/__stack_chk_fail.c", "musl/src/env/clearenv.c", "musl/src/env/getenv.c", "musl/src/env/putenv.c", "musl/src/env/secure_getenv.c", "musl/src/env/setenv.c", "musl/src/env/unsetenv.c", "musl/src/errno/__errno_location.c", "musl/src/errno/strerror.c", "musl/src/exit/_Exit.c", "musl/src/exit/abort.c", "musl/src/exit/arm/__aeabi_atexit.c", "musl/src/exit/assert.c", "musl/src/exit/at_quick_exit.c", "musl/src/exit/atexit.c", "musl/src/exit/exit.c", "musl/src/exit/quick_exit.c", "musl/src/fcntl/creat.c", "musl/src/fcntl/fcntl.c", "musl/src/fcntl/open.c", "musl/src/fcntl/openat.c", "musl/src/fcntl/posix_fadvise.c", "musl/src/fcntl/posix_fallocate.c", "musl/src/fenv/__flt_rounds.c", "musl/src/fenv/aarch64/fenv.s", "musl/src/fenv/arm/fenv-hf.S", "musl/src/fenv/arm/fenv.c", "musl/src/fenv/fegetexceptflag.c", "musl/src/fenv/feholdexcept.c", "musl/src/fenv/fenv.c", "musl/src/fenv/fesetexceptflag.c", "musl/src/fenv/fesetround.c", "musl/src/fenv/feupdateenv.c", "musl/src/fenv/i386/fenv.s", "musl/src/fenv/m68k/fenv.c", "musl/src/fenv/mips/fenv-sf.c", "musl/src/fenv/mips/fenv.S", "musl/src/fenv/mips64/fenv-sf.c", "musl/src/fenv/mips64/fenv.S", "musl/src/fenv/mipsn32/fenv-sf.c", "musl/src/fenv/mipsn32/fenv.S", "musl/src/fenv/powerpc/fenv-sf.c", "musl/src/fenv/powerpc/fenv.S", "musl/src/fenv/powerpc64/fenv.c", "musl/src/fenv/riscv64/fenv-sf.c", "musl/src/fenv/riscv64/fenv.S", "musl/src/fenv/s390x/fenv.c", "musl/src/fenv/sh/fenv-nofpu.c", "musl/src/fenv/sh/fenv.S", "musl/src/fenv/x32/fenv.s", "musl/src/fenv/x86_64/fenv.s", "musl/src/internal/defsysinfo.c", "musl/src/internal/floatscan.c", "musl/src/internal/i386/defsysinfo.s", "musl/src/internal/intscan.c", "musl/src/internal/libc.c", "musl/src/internal/procfdname.c", "musl/src/internal/sh/__shcall.c", "musl/src/internal/shgetc.c", "musl/src/internal/syscall_ret.c", "musl/src/internal/vdso.c", "musl/src/internal/version.c", "musl/src/ipc/ftok.c", "musl/src/ipc/msgctl.c", "musl/src/ipc/msgget.c", "musl/src/ipc/msgrcv.c", "musl/src/ipc/msgsnd.c", "musl/src/ipc/semctl.c", "musl/src/ipc/semget.c", "musl/src/ipc/semop.c", "musl/src/ipc/semtimedop.c", "musl/src/ipc/shmat.c", "musl/src/ipc/shmctl.c", "musl/src/ipc/shmdt.c", "musl/src/ipc/shmget.c", "musl/src/ldso/__dlsym.c", "musl/src/ldso/aarch64/dlsym.s", "musl/src/ldso/aarch64/tlsdesc.s", "musl/src/ldso/arm/dlsym.s", "musl/src/ldso/arm/dlsym_time64.S", "musl/src/ldso/arm/find_exidx.c", "musl/src/ldso/arm/tlsdesc.S", "musl/src/ldso/dl_iterate_phdr.c", "musl/src/ldso/dladdr.c", "musl/src/ldso/dlclose.c", "musl/src/ldso/dlerror.c", "musl/src/ldso/dlinfo.c", "musl/src/ldso/dlopen.c", "musl/src/ldso/dlsym.c", "musl/src/ldso/i386/dlsym.s", "musl/src/ldso/i386/dlsym_time64.S", "musl/src/ldso/i386/tlsdesc.s", "musl/src/ldso/m68k/dlsym.s", "musl/src/ldso/m68k/dlsym_time64.S", "musl/src/ldso/microblaze/dlsym.s", "musl/src/ldso/microblaze/dlsym_time64.S", "musl/src/ldso/mips/dlsym.s", "musl/src/ldso/mips/dlsym_time64.S", "musl/src/ldso/mips64/dlsym.s", "musl/src/ldso/mipsn32/dlsym.s", "musl/src/ldso/mipsn32/dlsym_time64.S", "musl/src/ldso/or1k/dlsym.s", "musl/src/ldso/or1k/dlsym_time64.S", "musl/src/ldso/powerpc/dlsym.s", "musl/src/ldso/powerpc/dlsym_time64.S", "musl/src/ldso/powerpc64/dlsym.s", "musl/src/ldso/riscv64/dlsym.s", "musl/src/ldso/s390x/dlsym.s", "musl/src/ldso/sh/dlsym.s", "musl/src/ldso/sh/dlsym_time64.S", "musl/src/ldso/tlsdesc.c", "musl/src/ldso/x32/dlsym.s", "musl/src/ldso/x86_64/dlsym.s", "musl/src/ldso/x86_64/tlsdesc.s", "musl/src/legacy/cuserid.c", "musl/src/legacy/daemon.c", "musl/src/legacy/err.c", "musl/src/legacy/euidaccess.c", "musl/src/legacy/ftw.c", "musl/src/legacy/futimes.c", "musl/src/legacy/getdtablesize.c", "musl/src/legacy/getloadavg.c", "musl/src/legacy/getpagesize.c", "musl/src/legacy/getpass.c", "musl/src/legacy/getusershell.c", "musl/src/legacy/isastream.c", "musl/src/legacy/lutimes.c", "musl/src/legacy/ulimit.c", "musl/src/legacy/utmpx.c", "musl/src/legacy/valloc.c", "musl/src/linux/adjtime.c", "musl/src/linux/adjtimex.c", "musl/src/linux/arch_prctl.c", "musl/src/linux/brk.c", "musl/src/linux/cache.c", "musl/src/linux/cap.c", "musl/src/linux/chroot.c", "musl/src/linux/clock_adjtime.c", "musl/src/linux/clone.c", "musl/src/linux/copy_file_range.c", "musl/src/linux/epoll.c", "musl/src/linux/eventfd.c", "musl/src/linux/fallocate.c", "musl/src/linux/fanotify.c", "musl/src/linux/flock.c", "musl/src/linux/getdents.c", "musl/src/linux/getrandom.c", "musl/src/linux/inotify.c", "musl/src/linux/ioperm.c", "musl/src/linux/iopl.c", "musl/src/linux/klogctl.c", "musl/src/linux/membarrier.c", "musl/src/linux/memfd_create.c", "musl/src/linux/mlock2.c", "musl/src/linux/module.c", "musl/src/linux/mount.c", "musl/src/linux/name_to_handle_at.c", "musl/src/linux/open_by_handle_at.c", "musl/src/linux/personality.c", "musl/src/linux/pivot_root.c", "musl/src/linux/ppoll.c", "musl/src/linux/prctl.c", "musl/src/linux/prlimit.c", "musl/src/linux/process_vm.c", "musl/src/linux/ptrace.c", "musl/src/linux/quotactl.c", "musl/src/linux/readahead.c", "musl/src/linux/reboot.c", "musl/src/linux/remap_file_pages.c", "musl/src/linux/sbrk.c", "musl/src/linux/sendfile.c", "musl/src/linux/setfsgid.c", "musl/src/linux/setfsuid.c", "musl/src/linux/setgroups.c", "musl/src/linux/sethostname.c", "musl/src/linux/setns.c", "musl/src/linux/settimeofday.c", "musl/src/linux/signalfd.c", "musl/src/linux/splice.c", "musl/src/linux/stime.c", "musl/src/linux/swap.c", "musl/src/linux/sync_file_range.c", "musl/src/linux/syncfs.c", "musl/src/linux/sysinfo.c", "musl/src/linux/tee.c", "musl/src/linux/timerfd.c", "musl/src/linux/unshare.c", "musl/src/linux/utimes.c", "musl/src/linux/vhangup.c", "musl/src/linux/vmsplice.c", "musl/src/linux/wait3.c", "musl/src/linux/wait4.c", "musl/src/linux/x32/sysinfo.c", "musl/src/linux/xattr.c", "musl/src/locale/__lctrans.c", "musl/src/locale/__mo_lookup.c", "musl/src/locale/bind_textdomain_codeset.c", "musl/src/locale/c_locale.c", "musl/src/locale/catclose.c", "musl/src/locale/catgets.c", "musl/src/locale/catopen.c", "musl/src/locale/dcngettext.c", "musl/src/locale/duplocale.c", "musl/src/locale/freelocale.c", "musl/src/locale/iconv.c", "musl/src/locale/iconv_close.c", "musl/src/locale/langinfo.c", "musl/src/locale/locale_map.c", "musl/src/locale/localeconv.c", "musl/src/locale/newlocale.c", "musl/src/locale/pleval.c", "musl/src/locale/setlocale.c", "musl/src/locale/strcoll.c", "musl/src/locale/strfmon.c", "musl/src/locale/strxfrm.c", "musl/src/locale/textdomain.c", "musl/src/locale/uselocale.c", "musl/src/locale/wcscoll.c", "musl/src/locale/wcsxfrm.c", "musl/src/malloc/calloc.c", "musl/src/malloc/lite_malloc.c", "musl/src/malloc/mallocng/aligned_alloc.c", "musl/src/malloc/mallocng/donate.c", "musl/src/malloc/mallocng/free.c", "musl/src/malloc/mallocng/malloc.c", "musl/src/malloc/mallocng/malloc_usable_size.c", "musl/src/malloc/mallocng/realloc.c", "musl/src/malloc/memalign.c", "musl/src/malloc/posix_memalign.c", "musl/src/malloc/replaced.c", "musl/src/math/__cos.c", "musl/src/math/__cosdf.c", "musl/src/math/__cosl.c", "musl/src/math/__expo2.c", "musl/src/math/__expo2f.c", "musl/src/math/__fpclassify.c", "musl/src/math/__fpclassifyf.c", "musl/src/math/__fpclassifyl.c", "musl/src/math/__invtrigl.c", "musl/src/math/__math_divzero.c", "musl/src/math/__math_divzerof.c", "musl/src/math/__math_invalid.c", "musl/src/math/__math_invalidf.c", "musl/src/math/__math_oflow.c", "musl/src/math/__math_oflowf.c", "musl/src/math/__math_uflow.c", "musl/src/math/__math_uflowf.c", "musl/src/math/__math_xflow.c", "musl/src/math/__math_xflowf.c", "musl/src/math/__polevll.c", "musl/src/math/__rem_pio2.c", "musl/src/math/__rem_pio2_large.c", "musl/src/math/__rem_pio2f.c", "musl/src/math/__rem_pio2l.c", "musl/src/math/__signbit.c", "musl/src/math/__signbitf.c", "musl/src/math/__signbitl.c", "musl/src/math/__sin.c", "musl/src/math/__sindf.c", "musl/src/math/__sinl.c", "musl/src/math/__tan.c", "musl/src/math/__tandf.c", "musl/src/math/__tanl.c", "musl/src/math/aarch64/ceil.c", "musl/src/math/aarch64/ceilf.c", "musl/src/math/aarch64/fabs.c", "musl/src/math/aarch64/fabsf.c", "musl/src/math/aarch64/floor.c", "musl/src/math/aarch64/floorf.c", "musl/src/math/aarch64/fma.c", "musl/src/math/aarch64/fmaf.c", "musl/src/math/aarch64/fmax.c", "musl/src/math/aarch64/fmaxf.c", "musl/src/math/aarch64/fmin.c", "musl/src/math/aarch64/fminf.c", "musl/src/math/aarch64/llrint.c", "musl/src/math/aarch64/llrintf.c", "musl/src/math/aarch64/llround.c", "musl/src/math/aarch64/llroundf.c", "musl/src/math/aarch64/lrint.c", "musl/src/math/aarch64/lrintf.c", "musl/src/math/aarch64/lround.c", "musl/src/math/aarch64/lroundf.c", "musl/src/math/aarch64/nearbyint.c", "musl/src/math/aarch64/nearbyintf.c", "musl/src/math/aarch64/rint.c", "musl/src/math/aarch64/rintf.c", "musl/src/math/aarch64/round.c", "musl/src/math/aarch64/roundf.c", "musl/src/math/aarch64/sqrt.c", "musl/src/math/aarch64/sqrtf.c", "musl/src/math/aarch64/trunc.c", "musl/src/math/aarch64/truncf.c", "musl/src/math/acos.c", "musl/src/math/acosf.c", "musl/src/math/acosh.c", "musl/src/math/acoshf.c", "musl/src/math/acoshl.c", "musl/src/math/acosl.c", "musl/src/math/arm/fabs.c", "musl/src/math/arm/fabsf.c", "musl/src/math/arm/fma.c", "musl/src/math/arm/fmaf.c", "musl/src/math/arm/sqrt.c", "musl/src/math/arm/sqrtf.c", "musl/src/math/asin.c", "musl/src/math/asinf.c", "musl/src/math/asinh.c", "musl/src/math/asinhf.c", "musl/src/math/asinhl.c", "musl/src/math/asinl.c", "musl/src/math/atan.c", "musl/src/math/atan2.c", "musl/src/math/atan2f.c", "musl/src/math/atan2l.c", "musl/src/math/atanf.c", "musl/src/math/atanh.c", "musl/src/math/atanhf.c", "musl/src/math/atanhl.c", "musl/src/math/atanl.c", "musl/src/math/cbrt.c", "musl/src/math/cbrtf.c", "musl/src/math/cbrtl.c", "musl/src/math/ceil.c", "musl/src/math/ceilf.c", "musl/src/math/ceill.c", "musl/src/math/copysign.c", "musl/src/math/copysignf.c", "musl/src/math/copysignl.c", "musl/src/math/cos.c", "musl/src/math/cosf.c", "musl/src/math/cosh.c", "musl/src/math/coshf.c", "musl/src/math/coshl.c", "musl/src/math/cosl.c", "musl/src/math/erf.c", "musl/src/math/erff.c", "musl/src/math/erfl.c", "musl/src/math/exp.c", "musl/src/math/exp10.c", "musl/src/math/exp10f.c", "musl/src/math/exp10l.c", "musl/src/math/exp2.c", "musl/src/math/exp2f.c", "musl/src/math/exp2f_data.c", "musl/src/math/exp2l.c", "musl/src/math/exp_data.c", "musl/src/math/expf.c", "musl/src/math/expl.c", "musl/src/math/expm1.c", "musl/src/math/expm1f.c", "musl/src/math/expm1l.c", "musl/src/math/fabs.c", "musl/src/math/fabsf.c", "musl/src/math/fabsl.c", "musl/src/math/fdim.c", "musl/src/math/fdimf.c", "musl/src/math/fdiml.c", "musl/src/math/finite.c", "musl/src/math/finitef.c", "musl/src/math/floor.c", "musl/src/math/floorf.c", "musl/src/math/floorl.c", "musl/src/math/fma.c", "musl/src/math/fmaf.c", "musl/src/math/fmal.c", "musl/src/math/fmax.c", "musl/src/math/fmaxf.c", "musl/src/math/fmaxl.c", "musl/src/math/fmin.c", "musl/src/math/fminf.c", "musl/src/math/fminl.c", "musl/src/math/fmod.c", "musl/src/math/fmodf.c", "musl/src/math/fmodl.c", "musl/src/math/frexp.c", "musl/src/math/frexpf.c", "musl/src/math/frexpl.c", "musl/src/math/hypot.c", "musl/src/math/hypotf.c", "musl/src/math/hypotl.c", "musl/src/math/i386/__invtrigl.s", "musl/src/math/i386/acos.s", "musl/src/math/i386/acosf.s", "musl/src/math/i386/acosl.s", "musl/src/math/i386/asin.s", "musl/src/math/i386/asinf.s", "musl/src/math/i386/asinl.s", "musl/src/math/i386/atan.s", "musl/src/math/i386/atan2.s", "musl/src/math/i386/atan2f.s", "musl/src/math/i386/atan2l.s", "musl/src/math/i386/atanf.s", "musl/src/math/i386/atanl.s", "musl/src/math/i386/ceil.s", "musl/src/math/i386/ceilf.s", "musl/src/math/i386/ceill.s", "musl/src/math/i386/exp2l.s", "musl/src/math/i386/exp_ld.s", "musl/src/math/i386/expl.s", "musl/src/math/i386/expm1l.s", "musl/src/math/i386/fabs.c", "musl/src/math/i386/fabsf.c", "musl/src/math/i386/fabsl.c", "musl/src/math/i386/floor.s", "musl/src/math/i386/floorf.s", "musl/src/math/i386/floorl.s", "musl/src/math/i386/fmod.c", "musl/src/math/i386/fmodf.c", "musl/src/math/i386/fmodl.c", "musl/src/math/i386/hypot.s", "musl/src/math/i386/hypotf.s", "musl/src/math/i386/ldexp.s", "musl/src/math/i386/ldexpf.s", "musl/src/math/i386/ldexpl.s", "musl/src/math/i386/llrint.c", "musl/src/math/i386/llrintf.c", "musl/src/math/i386/llrintl.c", "musl/src/math/i386/log.s", "musl/src/math/i386/log10.s", "musl/src/math/i386/log10f.s", "musl/src/math/i386/log10l.s", "musl/src/math/i386/log1p.s", "musl/src/math/i386/log1pf.s", "musl/src/math/i386/log1pl.s", "musl/src/math/i386/log2.s", "musl/src/math/i386/log2f.s", "musl/src/math/i386/log2l.s", "musl/src/math/i386/logf.s", "musl/src/math/i386/logl.s", "musl/src/math/i386/lrint.c", "musl/src/math/i386/lrintf.c", "musl/src/math/i386/lrintl.c", "musl/src/math/i386/remainder.c", "musl/src/math/i386/remainderf.c", "musl/src/math/i386/remainderl.c", "musl/src/math/i386/remquo.s", "musl/src/math/i386/remquof.s", "musl/src/math/i386/remquol.s", "musl/src/math/i386/rint.c", "musl/src/math/i386/rintf.c", "musl/src/math/i386/rintl.c", "musl/src/math/i386/scalbln.s", "musl/src/math/i386/scalblnf.s", "musl/src/math/i386/scalblnl.s", "musl/src/math/i386/scalbn.s", "musl/src/math/i386/scalbnf.s", "musl/src/math/i386/scalbnl.s", "musl/src/math/i386/sqrt.c", "musl/src/math/i386/sqrtf.c", "musl/src/math/i386/sqrtl.c", "musl/src/math/i386/trunc.s", "musl/src/math/i386/truncf.s", "musl/src/math/i386/truncl.s", "musl/src/math/ilogb.c", "musl/src/math/ilogbf.c", "musl/src/math/ilogbl.c", "musl/src/math/j0.c", "musl/src/math/j0f.c", "musl/src/math/j1.c", "musl/src/math/j1f.c", "musl/src/math/jn.c", "musl/src/math/jnf.c", "musl/src/math/ldexp.c", "musl/src/math/ldexpf.c", "musl/src/math/ldexpl.c", "musl/src/math/lgamma.c", "musl/src/math/lgamma_r.c", "musl/src/math/lgammaf.c", "musl/src/math/lgammaf_r.c", "musl/src/math/lgammal.c", "musl/src/math/llrint.c", "musl/src/math/llrintf.c", "musl/src/math/llrintl.c", "musl/src/math/llround.c", "musl/src/math/llroundf.c", "musl/src/math/llroundl.c", "musl/src/math/log.c", "musl/src/math/log10.c", "musl/src/math/log10f.c", "musl/src/math/log10l.c", "musl/src/math/log1p.c", "musl/src/math/log1pf.c", "musl/src/math/log1pl.c", "musl/src/math/log2.c", "musl/src/math/log2_data.c", "musl/src/math/log2f.c", "musl/src/math/log2f_data.c", "musl/src/math/log2l.c", "musl/src/math/log_data.c", "musl/src/math/logb.c", "musl/src/math/logbf.c", "musl/src/math/logbl.c", "musl/src/math/logf.c", "musl/src/math/logf_data.c", "musl/src/math/logl.c", "musl/src/math/lrint.c", "musl/src/math/lrintf.c", "musl/src/math/lrintl.c", "musl/src/math/lround.c", "musl/src/math/lroundf.c", "musl/src/math/lroundl.c", "musl/src/math/m68k/sqrtl.c", "musl/src/math/mips/fabs.c", "musl/src/math/mips/fabsf.c", "musl/src/math/mips/sqrt.c", "musl/src/math/mips/sqrtf.c", "musl/src/math/modf.c", "musl/src/math/modff.c", "musl/src/math/modfl.c", "musl/src/math/nan.c", "musl/src/math/nanf.c", "musl/src/math/nanl.c", "musl/src/math/nearbyint.c", "musl/src/math/nearbyintf.c", "musl/src/math/nearbyintl.c", "musl/src/math/nextafter.c", "musl/src/math/nextafterf.c", "musl/src/math/nextafterl.c", "musl/src/math/nexttoward.c", "musl/src/math/nexttowardf.c", "musl/src/math/nexttowardl.c", "musl/src/math/pow.c", "musl/src/math/pow_data.c", "musl/src/math/powerpc/fabs.c", "musl/src/math/powerpc/fabsf.c", "musl/src/math/powerpc/fma.c", "musl/src/math/powerpc/fmaf.c", "musl/src/math/powerpc/sqrt.c", "musl/src/math/powerpc/sqrtf.c", "musl/src/math/powerpc64/ceil.c", "musl/src/math/powerpc64/ceilf.c", "musl/src/math/powerpc64/fabs.c", "musl/src/math/powerpc64/fabsf.c", "musl/src/math/powerpc64/floor.c", "musl/src/math/powerpc64/floorf.c", "musl/src/math/powerpc64/fma.c", "musl/src/math/powerpc64/fmaf.c", "musl/src/math/powerpc64/fmax.c", "musl/src/math/powerpc64/fmaxf.c", "musl/src/math/powerpc64/fmin.c", "musl/src/math/powerpc64/fminf.c", "musl/src/math/powerpc64/lrint.c", "musl/src/math/powerpc64/lrintf.c", "musl/src/math/powerpc64/lround.c", "musl/src/math/powerpc64/lroundf.c", "musl/src/math/powerpc64/round.c", "musl/src/math/powerpc64/roundf.c", "musl/src/math/powerpc64/sqrt.c", "musl/src/math/powerpc64/sqrtf.c", "musl/src/math/powerpc64/trunc.c", "musl/src/math/powerpc64/truncf.c", "musl/src/math/powf.c", "musl/src/math/powf_data.c", "musl/src/math/powl.c", "musl/src/math/remainder.c", "musl/src/math/remainderf.c", "musl/src/math/remainderl.c", "musl/src/math/remquo.c", "musl/src/math/remquof.c", "musl/src/math/remquol.c", "musl/src/math/rint.c", "musl/src/math/rintf.c", "musl/src/math/rintl.c", "musl/src/math/riscv64/copysign.c", "musl/src/math/riscv64/copysignf.c", "musl/src/math/riscv64/fabs.c", "musl/src/math/riscv64/fabsf.c", "musl/src/math/riscv64/fma.c", "musl/src/math/riscv64/fmaf.c", "musl/src/math/riscv64/fmax.c", "musl/src/math/riscv64/fmaxf.c", "musl/src/math/riscv64/fmin.c", "musl/src/math/riscv64/fminf.c", "musl/src/math/riscv64/sqrt.c", "musl/src/math/riscv64/sqrtf.c", "musl/src/math/round.c", "musl/src/math/roundf.c", "musl/src/math/roundl.c", "musl/src/math/s390x/ceil.c", "musl/src/math/s390x/ceilf.c", "musl/src/math/s390x/ceill.c", "musl/src/math/s390x/fabs.c", "musl/src/math/s390x/fabsf.c", "musl/src/math/s390x/fabsl.c", "musl/src/math/s390x/floor.c", "musl/src/math/s390x/floorf.c", "musl/src/math/s390x/floorl.c", "musl/src/math/s390x/fma.c", "musl/src/math/s390x/fmaf.c", "musl/src/math/s390x/nearbyint.c", "musl/src/math/s390x/nearbyintf.c", "musl/src/math/s390x/nearbyintl.c", "musl/src/math/s390x/rint.c", "musl/src/math/s390x/rintf.c", "musl/src/math/s390x/rintl.c", "musl/src/math/s390x/round.c", "musl/src/math/s390x/roundf.c", "musl/src/math/s390x/roundl.c", "musl/src/math/s390x/sqrt.c", "musl/src/math/s390x/sqrtf.c", "musl/src/math/s390x/sqrtl.c", "musl/src/math/s390x/trunc.c", "musl/src/math/s390x/truncf.c", "musl/src/math/s390x/truncl.c", "musl/src/math/scalb.c", "musl/src/math/scalbf.c", "musl/src/math/scalbln.c", "musl/src/math/scalblnf.c", "musl/src/math/scalblnl.c", "musl/src/math/scalbn.c", "musl/src/math/scalbnf.c", "musl/src/math/scalbnl.c", "musl/src/math/signgam.c", "musl/src/math/significand.c", "musl/src/math/significandf.c", "musl/src/math/sin.c", "musl/src/math/sincos.c", "musl/src/math/sincosf.c", "musl/src/math/sincosl.c", "musl/src/math/sinf.c", "musl/src/math/sinh.c", "musl/src/math/sinhf.c", "musl/src/math/sinhl.c", "musl/src/math/sinl.c", "musl/src/math/sqrt.c", "musl/src/math/sqrtf.c", "musl/src/math/sqrtl.c", "musl/src/math/tan.c", "musl/src/math/tanf.c", "musl/src/math/tanh.c", "musl/src/math/tanhf.c", "musl/src/math/tanhl.c", "musl/src/math/tanl.c", "musl/src/math/tgamma.c", "musl/src/math/tgammaf.c", "musl/src/math/tgammal.c", "musl/src/math/trunc.c", "musl/src/math/truncf.c", "musl/src/math/truncl.c", "musl/src/math/x32/__invtrigl.s", "musl/src/math/x32/acosl.s", "musl/src/math/x32/asinl.s", "musl/src/math/x32/atan2l.s", "musl/src/math/x32/atanl.s", "musl/src/math/x32/ceill.s", "musl/src/math/x32/exp2l.s", "musl/src/math/x32/expl.s", "musl/src/math/x32/expm1l.s", "musl/src/math/x32/fabs.s", "musl/src/math/x32/fabsf.s", "musl/src/math/x32/fabsl.s", "musl/src/math/x32/floorl.s", "musl/src/math/x32/fma.c", "musl/src/math/x32/fmaf.c", "musl/src/math/x32/fmodl.s", "musl/src/math/x32/llrint.s", "musl/src/math/x32/llrintf.s", "musl/src/math/x32/llrintl.s", "musl/src/math/x32/log10l.s", "musl/src/math/x32/log1pl.s", "musl/src/math/x32/log2l.s", "musl/src/math/x32/logl.s", "musl/src/math/x32/lrint.s", "musl/src/math/x32/lrintf.s", "musl/src/math/x32/lrintl.s", "musl/src/math/x32/remainderl.s", "musl/src/math/x32/rintl.s", "musl/src/math/x32/sqrt.s", "musl/src/math/x32/sqrtf.s", "musl/src/math/x32/sqrtl.s", "musl/src/math/x32/truncl.s", "musl/src/math/x86_64/__invtrigl.s", "musl/src/math/x86_64/acosl.s", "musl/src/math/x86_64/asinl.s", "musl/src/math/x86_64/atan2l.s", "musl/src/math/x86_64/atanl.s", "musl/src/math/x86_64/ceill.s", "musl/src/math/x86_64/exp2l.s", "musl/src/math/x86_64/expl.s", "musl/src/math/x86_64/expm1l.s", "musl/src/math/x86_64/fabs.c", "musl/src/math/x86_64/fabsf.c", "musl/src/math/x86_64/fabsl.c", "musl/src/math/x86_64/floorl.s", "musl/src/math/x86_64/fma.c", "musl/src/math/x86_64/fmaf.c", "musl/src/math/x86_64/fmodl.c", "musl/src/math/x86_64/llrint.c", "musl/src/math/x86_64/llrintf.c", "musl/src/math/x86_64/llrintl.c", "musl/src/math/x86_64/log10l.s", "musl/src/math/x86_64/log1pl.s", "musl/src/math/x86_64/log2l.s", "musl/src/math/x86_64/logl.s", "musl/src/math/x86_64/lrint.c", "musl/src/math/x86_64/lrintf.c", "musl/src/math/x86_64/lrintl.c", "musl/src/math/x86_64/remainderl.c", "musl/src/math/x86_64/remquol.c", "musl/src/math/x86_64/rintl.c", "musl/src/math/x86_64/sqrt.c", "musl/src/math/x86_64/sqrtf.c", "musl/src/math/x86_64/sqrtl.c", "musl/src/math/x86_64/truncl.s", "musl/src/misc/a64l.c", "musl/src/misc/basename.c", "musl/src/misc/dirname.c", "musl/src/misc/ffs.c", "musl/src/misc/ffsl.c", "musl/src/misc/ffsll.c", "musl/src/misc/fmtmsg.c", "musl/src/misc/forkpty.c", "musl/src/misc/get_current_dir_name.c", "musl/src/misc/getauxval.c", "musl/src/misc/getdomainname.c", "musl/src/misc/getentropy.c", "musl/src/misc/gethostid.c", "musl/src/misc/getopt.c", "musl/src/misc/getopt_long.c", "musl/src/misc/getpriority.c", "musl/src/misc/getresgid.c", "musl/src/misc/getresuid.c", "musl/src/misc/getrlimit.c", "musl/src/misc/getrusage.c", "musl/src/misc/getsubopt.c", "musl/src/misc/initgroups.c", "musl/src/misc/ioctl.c", "musl/src/misc/issetugid.c", "musl/src/misc/lockf.c", "musl/src/misc/login_tty.c", "musl/src/misc/mntent.c", "musl/src/misc/nftw.c", "musl/src/misc/openpty.c", "musl/src/misc/ptsname.c", "musl/src/misc/pty.c", "musl/src/misc/realpath.c", "musl/src/misc/setdomainname.c", "musl/src/misc/setpriority.c", "musl/src/misc/setrlimit.c", "musl/src/misc/syscall.c", "musl/src/misc/syslog.c", "musl/src/misc/uname.c", "musl/src/misc/wordexp.c", "musl/src/mman/madvise.c", "musl/src/mman/mincore.c", "musl/src/mman/mlock.c", "musl/src/mman/mlockall.c", "musl/src/mman/mmap.c", "musl/src/mman/mprotect.c", "musl/src/mman/mremap.c", "musl/src/mman/msync.c", "musl/src/mman/munlock.c", "musl/src/mman/munlockall.c", "musl/src/mman/munmap.c", "musl/src/mman/posix_madvise.c", "musl/src/mman/shm_open.c", "musl/src/mq/mq_close.c", "musl/src/mq/mq_getattr.c", "musl/src/mq/mq_notify.c", "musl/src/mq/mq_open.c", "musl/src/mq/mq_receive.c", "musl/src/mq/mq_send.c", "musl/src/mq/mq_setattr.c", "musl/src/mq/mq_timedreceive.c", "musl/src/mq/mq_timedsend.c", "musl/src/mq/mq_unlink.c", "musl/src/multibyte/btowc.c", "musl/src/multibyte/c16rtomb.c", "musl/src/multibyte/c32rtomb.c", "musl/src/multibyte/internal.c", "musl/src/multibyte/mblen.c", "musl/src/multibyte/mbrlen.c", "musl/src/multibyte/mbrtoc16.c", "musl/src/multibyte/mbrtoc32.c", "musl/src/multibyte/mbrtowc.c", "musl/src/multibyte/mbsinit.c", "musl/src/multibyte/mbsnrtowcs.c", "musl/src/multibyte/mbsrtowcs.c", "musl/src/multibyte/mbstowcs.c", "musl/src/multibyte/mbtowc.c", "musl/src/multibyte/wcrtomb.c", "musl/src/multibyte/wcsnrtombs.c", "musl/src/multibyte/wcsrtombs.c", "musl/src/multibyte/wcstombs.c", "musl/src/multibyte/wctob.c", "musl/src/multibyte/wctomb.c", "musl/src/network/accept.c", "musl/src/network/accept4.c", "musl/src/network/bind.c", "musl/src/network/connect.c", "musl/src/network/dn_comp.c", "musl/src/network/dn_expand.c", "musl/src/network/dn_skipname.c", "musl/src/network/dns_parse.c", "musl/src/network/ent.c", "musl/src/network/ether.c", "musl/src/network/freeaddrinfo.c", "musl/src/network/gai_strerror.c", "musl/src/network/getaddrinfo.c", "musl/src/network/gethostbyaddr.c", "musl/src/network/gethostbyaddr_r.c", "musl/src/network/gethostbyname.c", "musl/src/network/gethostbyname2.c", "musl/src/network/gethostbyname2_r.c", "musl/src/network/gethostbyname_r.c", "musl/src/network/getifaddrs.c", "musl/src/network/getnameinfo.c", "musl/src/network/getpeername.c", "musl/src/network/getservbyname.c", "musl/src/network/getservbyname_r.c", "musl/src/network/getservbyport.c", "musl/src/network/getservbyport_r.c", "musl/src/network/getsockname.c", "musl/src/network/getsockopt.c", "musl/src/network/h_errno.c", "musl/src/network/herror.c", "musl/src/network/hstrerror.c", "musl/src/network/htonl.c", "musl/src/network/htons.c", "musl/src/network/if_freenameindex.c", "musl/src/network/if_indextoname.c", "musl/src/network/if_nameindex.c", "musl/src/network/if_nametoindex.c", "musl/src/network/in6addr_any.c", "musl/src/network/in6addr_loopback.c", "musl/src/network/inet_addr.c", "musl/src/network/inet_aton.c", "musl/src/network/inet_legacy.c", "musl/src/network/inet_ntoa.c", "musl/src/network/inet_ntop.c", "musl/src/network/inet_pton.c", "musl/src/network/listen.c", "musl/src/network/lookup_ipliteral.c", "musl/src/network/lookup_name.c", "musl/src/network/lookup_serv.c", "musl/src/network/netlink.c", "musl/src/network/netname.c", "musl/src/network/ns_parse.c", "musl/src/network/ntohl.c", "musl/src/network/ntohs.c", "musl/src/network/proto.c", "musl/src/network/recv.c", "musl/src/network/recvfrom.c", "musl/src/network/recvmmsg.c", "musl/src/network/recvmsg.c", "musl/src/network/res_init.c", "musl/src/network/res_mkquery.c", "musl/src/network/res_msend.c", "musl/src/network/res_query.c", "musl/src/network/res_querydomain.c", "musl/src/network/res_send.c", "musl/src/network/res_state.c", "musl/src/network/resolvconf.c", "musl/src/network/send.c", "musl/src/network/sendmmsg.c", "musl/src/network/sendmsg.c", "musl/src/network/sendto.c", "musl/src/network/serv.c", "musl/src/network/setsockopt.c", "musl/src/network/shutdown.c", "musl/src/network/sockatmark.c", "musl/src/network/socket.c", "musl/src/network/socketpair.c", "musl/src/passwd/fgetgrent.c", "musl/src/passwd/fgetpwent.c", "musl/src/passwd/fgetspent.c", "musl/src/passwd/getgr_a.c", "musl/src/passwd/getgr_r.c", "musl/src/passwd/getgrent.c", "musl/src/passwd/getgrent_a.c", "musl/src/passwd/getgrouplist.c", "musl/src/passwd/getpw_a.c", "musl/src/passwd/getpw_r.c", "musl/src/passwd/getpwent.c", "musl/src/passwd/getpwent_a.c", "musl/src/passwd/getspent.c", "musl/src/passwd/getspnam.c", "musl/src/passwd/getspnam_r.c", "musl/src/passwd/lckpwdf.c", "musl/src/passwd/nscd_query.c", "musl/src/passwd/putgrent.c", "musl/src/passwd/putpwent.c", "musl/src/passwd/putspent.c", "musl/src/prng/__rand48_step.c", "musl/src/prng/__seed48.c", "musl/src/prng/drand48.c", "musl/src/prng/lcong48.c", "musl/src/prng/lrand48.c", "musl/src/prng/mrand48.c", "musl/src/prng/rand.c", "musl/src/prng/rand_r.c", "musl/src/prng/random.c", "musl/src/prng/seed48.c", "musl/src/prng/srand48.c", "musl/src/process/arm/vfork.s", "musl/src/process/execl.c", "musl/src/process/execle.c", "musl/src/process/execlp.c", "musl/src/process/execv.c", "musl/src/process/execve.c", "musl/src/process/execvp.c", "musl/src/process/fexecve.c", "musl/src/process/fork.c", "musl/src/process/i386/vfork.s", "musl/src/process/posix_spawn.c", "musl/src/process/posix_spawn_file_actions_addchdir.c", "musl/src/process/posix_spawn_file_actions_addclose.c", "musl/src/process/posix_spawn_file_actions_adddup2.c", "musl/src/process/posix_spawn_file_actions_addfchdir.c", "musl/src/process/posix_spawn_file_actions_addopen.c", "musl/src/process/posix_spawn_file_actions_destroy.c", "musl/src/process/posix_spawn_file_actions_init.c", "musl/src/process/posix_spawnattr_destroy.c", "musl/src/process/posix_spawnattr_getflags.c", "musl/src/process/posix_spawnattr_getpgroup.c", "musl/src/process/posix_spawnattr_getsigdefault.c", "musl/src/process/posix_spawnattr_getsigmask.c", "musl/src/process/posix_spawnattr_init.c", "musl/src/process/posix_spawnattr_sched.c", "musl/src/process/posix_spawnattr_setflags.c", "musl/src/process/posix_spawnattr_setpgroup.c", "musl/src/process/posix_spawnattr_setsigdefault.c", "musl/src/process/posix_spawnattr_setsigmask.c", "musl/src/process/posix_spawnp.c", "musl/src/process/s390x/vfork.s", "musl/src/process/sh/vfork.s", "musl/src/process/system.c", "musl/src/process/vfork.c", "musl/src/process/wait.c", "musl/src/process/waitid.c", "musl/src/process/waitpid.c", "musl/src/process/x32/vfork.s", "musl/src/process/x86_64/vfork.s", "musl/src/regex/fnmatch.c", "musl/src/regex/glob.c", "musl/src/regex/regcomp.c", "musl/src/regex/regerror.c", "musl/src/regex/regexec.c", "musl/src/regex/tre-mem.c", "musl/src/sched/affinity.c", "musl/src/sched/sched_cpucount.c", "musl/src/sched/sched_get_priority_max.c", "musl/src/sched/sched_getcpu.c", "musl/src/sched/sched_getparam.c", "musl/src/sched/sched_getscheduler.c", "musl/src/sched/sched_rr_get_interval.c", "musl/src/sched/sched_setparam.c", "musl/src/sched/sched_setscheduler.c", "musl/src/sched/sched_yield.c", "musl/src/search/hsearch.c", "musl/src/search/insque.c", "musl/src/search/lsearch.c", "musl/src/search/tdelete.c", "musl/src/search/tdestroy.c", "musl/src/search/tfind.c", "musl/src/search/tsearch.c", "musl/src/search/twalk.c", "musl/src/select/poll.c", "musl/src/select/pselect.c", "musl/src/select/select.c", "musl/src/setjmp/aarch64/longjmp.s", "musl/src/setjmp/aarch64/setjmp.s", "musl/src/setjmp/arm/longjmp.S", "musl/src/setjmp/arm/setjmp.S", "musl/src/setjmp/i386/longjmp.s", "musl/src/setjmp/i386/setjmp.s", "musl/src/setjmp/longjmp.c", "musl/src/setjmp/m68k/longjmp.s", "musl/src/setjmp/m68k/setjmp.s", "musl/src/setjmp/microblaze/longjmp.s", "musl/src/setjmp/microblaze/setjmp.s", "musl/src/setjmp/mips/longjmp.S", "musl/src/setjmp/mips/setjmp.S", "musl/src/setjmp/mips64/longjmp.S", "musl/src/setjmp/mips64/setjmp.S", "musl/src/setjmp/mipsn32/longjmp.S", "musl/src/setjmp/mipsn32/setjmp.S", "musl/src/setjmp/or1k/longjmp.s", "musl/src/setjmp/or1k/setjmp.s", "musl/src/setjmp/powerpc/longjmp.S", "musl/src/setjmp/powerpc/setjmp.S", "musl/src/setjmp/powerpc64/longjmp.s", "musl/src/setjmp/powerpc64/setjmp.s", "musl/src/setjmp/riscv64/longjmp.S", "musl/src/setjmp/riscv64/setjmp.S", "musl/src/setjmp/s390x/longjmp.s", "musl/src/setjmp/s390x/setjmp.s", "musl/src/setjmp/setjmp.c", "musl/src/setjmp/sh/longjmp.S", "musl/src/setjmp/sh/setjmp.S", "musl/src/setjmp/x32/longjmp.s", "musl/src/setjmp/x32/setjmp.s", "musl/src/setjmp/x86_64/longjmp.s", "musl/src/setjmp/x86_64/setjmp.s", "musl/src/signal/aarch64/restore.s", "musl/src/signal/aarch64/sigsetjmp.s", "musl/src/signal/arm/restore.s", "musl/src/signal/arm/sigsetjmp.s", "musl/src/signal/block.c", "musl/src/signal/getitimer.c", "musl/src/signal/i386/restore.s", "musl/src/signal/i386/sigsetjmp.s", "musl/src/signal/kill.c", "musl/src/signal/killpg.c", "musl/src/signal/m68k/sigsetjmp.s", "musl/src/signal/microblaze/restore.s", "musl/src/signal/microblaze/sigsetjmp.s", "musl/src/signal/mips/restore.s", "musl/src/signal/mips/sigsetjmp.s", "musl/src/signal/mips64/restore.s", "musl/src/signal/mips64/sigsetjmp.s", "musl/src/signal/mipsn32/restore.s", "musl/src/signal/mipsn32/sigsetjmp.s", "musl/src/signal/or1k/sigsetjmp.s", "musl/src/signal/powerpc/restore.s", "musl/src/signal/powerpc/sigsetjmp.s", "musl/src/signal/powerpc64/restore.s", "musl/src/signal/powerpc64/sigsetjmp.s", "musl/src/signal/psiginfo.c", "musl/src/signal/psignal.c", "musl/src/signal/raise.c", "musl/src/signal/restore.c", "musl/src/signal/riscv64/restore.s", "musl/src/signal/riscv64/sigsetjmp.s", "musl/src/signal/s390x/restore.s", "musl/src/signal/s390x/sigsetjmp.s", "musl/src/signal/setitimer.c", "musl/src/signal/sh/restore.s", "musl/src/signal/sh/sigsetjmp.s", "musl/src/signal/sigaction.c", "musl/src/signal/sigaddset.c", "musl/src/signal/sigaltstack.c", "musl/src/signal/sigandset.c", "musl/src/signal/sigdelset.c", "musl/src/signal/sigemptyset.c", "musl/src/signal/sigfillset.c", "musl/src/signal/sighold.c", "musl/src/signal/sigignore.c", "musl/src/signal/siginterrupt.c", "musl/src/signal/sigisemptyset.c", "musl/src/signal/sigismember.c", "musl/src/signal/siglongjmp.c", "musl/src/signal/signal.c", "musl/src/signal/sigorset.c", "musl/src/signal/sigpause.c", "musl/src/signal/sigpending.c", "musl/src/signal/sigprocmask.c", "musl/src/signal/sigqueue.c", "musl/src/signal/sigrelse.c", "musl/src/signal/sigrtmax.c", "musl/src/signal/sigrtmin.c", "musl/src/signal/sigset.c", "musl/src/signal/sigsetjmp.c", "musl/src/signal/sigsetjmp_tail.c", "musl/src/signal/sigsuspend.c", "musl/src/signal/sigtimedwait.c", "musl/src/signal/sigwait.c", "musl/src/signal/sigwaitinfo.c", "musl/src/signal/x32/getitimer.c", "musl/src/signal/x32/restore.s", "musl/src/signal/x32/setitimer.c", "musl/src/signal/x32/sigsetjmp.s", "musl/src/signal/x86_64/restore.s", "musl/src/signal/x86_64/sigsetjmp.s", "musl/src/stat/__xstat.c", "musl/src/stat/chmod.c", "musl/src/stat/fchmod.c", "musl/src/stat/fchmodat.c", "musl/src/stat/fstat.c", "musl/src/stat/fstatat.c", "musl/src/stat/futimens.c", "musl/src/stat/futimesat.c", "musl/src/stat/lchmod.c", "musl/src/stat/lstat.c", "musl/src/stat/mkdir.c", "musl/src/stat/mkdirat.c", "musl/src/stat/mkfifo.c", "musl/src/stat/mkfifoat.c", "musl/src/stat/mknod.c", "musl/src/stat/mknodat.c", "musl/src/stat/stat.c", "musl/src/stat/statvfs.c", "musl/src/stat/umask.c", "musl/src/stat/utimensat.c", "musl/src/stdio/__fclose_ca.c", "musl/src/stdio/__fdopen.c", "musl/src/stdio/__fmodeflags.c", "musl/src/stdio/__fopen_rb_ca.c", "musl/src/stdio/__lockfile.c", "musl/src/stdio/__overflow.c", "musl/src/stdio/__stdio_close.c", "musl/src/stdio/__stdio_exit.c", "musl/src/stdio/__stdio_read.c", "musl/src/stdio/__stdio_seek.c", "musl/src/stdio/__stdio_write.c", "musl/src/stdio/__stdout_write.c", "musl/src/stdio/__toread.c", "musl/src/stdio/__towrite.c", "musl/src/stdio/__uflow.c", "musl/src/stdio/asprintf.c", "musl/src/stdio/clearerr.c", "musl/src/stdio/dprintf.c", "musl/src/stdio/ext.c", "musl/src/stdio/ext2.c", "musl/src/stdio/fclose.c", "musl/src/stdio/feof.c", "musl/src/stdio/ferror.c", "musl/src/stdio/fflush.c", "musl/src/stdio/fgetc.c", "musl/src/stdio/fgetln.c", "musl/src/stdio/fgetpos.c", "musl/src/stdio/fgets.c", "musl/src/stdio/fgetwc.c", "musl/src/stdio/fgetws.c", "musl/src/stdio/fileno.c", "musl/src/stdio/flockfile.c", "musl/src/stdio/fmemopen.c", "musl/src/stdio/fopen.c", "musl/src/stdio/fopencookie.c", "musl/src/stdio/fprintf.c", "musl/src/stdio/fputc.c", "musl/src/stdio/fputs.c", "musl/src/stdio/fputwc.c", "musl/src/stdio/fputws.c", "musl/src/stdio/fread.c", "musl/src/stdio/freopen.c", "musl/src/stdio/fscanf.c", "musl/src/stdio/fseek.c", "musl/src/stdio/fsetpos.c", "musl/src/stdio/ftell.c", "musl/src/stdio/ftrylockfile.c", "musl/src/stdio/funlockfile.c", "musl/src/stdio/fwide.c", "musl/src/stdio/fwprintf.c", "musl/src/stdio/fwrite.c", "musl/src/stdio/fwscanf.c", "musl/src/stdio/getc.c", "musl/src/stdio/getc_unlocked.c", "musl/src/stdio/getchar.c", "musl/src/stdio/getchar_unlocked.c", "musl/src/stdio/getdelim.c", "musl/src/stdio/getline.c", "musl/src/stdio/gets.c", "musl/src/stdio/getw.c", "musl/src/stdio/getwc.c", "musl/src/stdio/getwchar.c", "musl/src/stdio/ofl.c", "musl/src/stdio/ofl_add.c", "musl/src/stdio/open_memstream.c", "musl/src/stdio/open_wmemstream.c", "musl/src/stdio/pclose.c", "musl/src/stdio/perror.c", "musl/src/stdio/popen.c", "musl/src/stdio/printf.c", "musl/src/stdio/putc.c", "musl/src/stdio/putc_unlocked.c", "musl/src/stdio/putchar.c", "musl/src/stdio/putchar_unlocked.c", "musl/src/stdio/puts.c", "musl/src/stdio/putw.c", "musl/src/stdio/putwc.c", "musl/src/stdio/putwchar.c", "musl/src/stdio/remove.c", "musl/src/stdio/rename.c", "musl/src/stdio/rewind.c", "musl/src/stdio/scanf.c", "musl/src/stdio/setbuf.c", "musl/src/stdio/setbuffer.c", "musl/src/stdio/setlinebuf.c", "musl/src/stdio/setvbuf.c", "musl/src/stdio/snprintf.c", "musl/src/stdio/sprintf.c", "musl/src/stdio/sscanf.c", "musl/src/stdio/stderr.c", "musl/src/stdio/stdin.c", "musl/src/stdio/stdout.c", "musl/src/stdio/swprintf.c", "musl/src/stdio/swscanf.c", "musl/src/stdio/tempnam.c", "musl/src/stdio/tmpfile.c", "musl/src/stdio/tmpnam.c", "musl/src/stdio/ungetc.c", "musl/src/stdio/ungetwc.c", "musl/src/stdio/vasprintf.c", "musl/src/stdio/vdprintf.c", "musl/src/stdio/vfprintf.c", "musl/src/stdio/vfscanf.c", "musl/src/stdio/vfwprintf.c", "musl/src/stdio/vfwscanf.c", "musl/src/stdio/vprintf.c", "musl/src/stdio/vscanf.c", "musl/src/stdio/vsnprintf.c", "musl/src/stdio/vsprintf.c", "musl/src/stdio/vsscanf.c", "musl/src/stdio/vswprintf.c", "musl/src/stdio/vswscanf.c", "musl/src/stdio/vwprintf.c", "musl/src/stdio/vwscanf.c", "musl/src/stdio/wprintf.c", "musl/src/stdio/wscanf.c", "musl/src/stdlib/abs.c", "musl/src/stdlib/atof.c", "musl/src/stdlib/atoi.c", "musl/src/stdlib/atol.c", "musl/src/stdlib/atoll.c", "musl/src/stdlib/bsearch.c", "musl/src/stdlib/div.c", "musl/src/stdlib/ecvt.c", "musl/src/stdlib/fcvt.c", "musl/src/stdlib/gcvt.c", "musl/src/stdlib/imaxabs.c", "musl/src/stdlib/imaxdiv.c", "musl/src/stdlib/labs.c", "musl/src/stdlib/ldiv.c", "musl/src/stdlib/llabs.c", "musl/src/stdlib/lldiv.c", "musl/src/stdlib/qsort.c", "musl/src/stdlib/strtod.c", "musl/src/stdlib/strtol.c", "musl/src/stdlib/wcstod.c", "musl/src/stdlib/wcstol.c", "musl/src/string/aarch64/memcpy.S", "musl/src/string/aarch64/memset.S", "musl/src/string/arm/__aeabi_memcpy.s", "musl/src/string/arm/__aeabi_memset.s", "musl/src/string/arm/memcpy.S", "musl/src/string/bcmp.c", "musl/src/string/bcopy.c", "musl/src/string/bzero.c", "musl/src/string/explicit_bzero.c", "musl/src/string/i386/memcpy.s", "musl/src/string/i386/memmove.s", "musl/src/string/i386/memset.s", "musl/src/string/index.c", "musl/src/string/memccpy.c", "musl/src/string/memchr.c", "musl/src/string/memcmp.c", "musl/src/string/memcpy.c", "musl/src/string/memmem.c", "musl/src/string/memmove.c", "musl/src/string/mempcpy.c", "musl/src/string/memrchr.c", "musl/src/string/memset.c", "musl/src/string/rindex.c", "musl/src/string/stpcpy.c", "musl/src/string/stpncpy.c", "musl/src/string/strcasecmp.c", "musl/src/string/strcasestr.c", "musl/src/string/strcat.c", "musl/src/string/strchr.c", "musl/src/string/strchrnul.c", "musl/src/string/strcmp.c", "musl/src/string/strcpy.c", "musl/src/string/strcspn.c", "musl/src/string/strdup.c", "musl/src/string/strerror_r.c", "musl/src/string/strlcat.c", "musl/src/string/strlcpy.c", "musl/src/string/strlen.c", "musl/src/string/strncasecmp.c", "musl/src/string/strncat.c", "musl/src/string/strncmp.c", "musl/src/string/strncpy.c", "musl/src/string/strndup.c", "musl/src/string/strnlen.c", "musl/src/string/strpbrk.c", "musl/src/string/strrchr.c", "musl/src/string/strsep.c", "musl/src/string/strsignal.c", "musl/src/string/strspn.c", "musl/src/string/strstr.c", "musl/src/string/strtok.c", "musl/src/string/strtok_r.c", "musl/src/string/strverscmp.c", "musl/src/string/swab.c", "musl/src/string/wcpcpy.c", "musl/src/string/wcpncpy.c", "musl/src/string/wcscasecmp.c", "musl/src/string/wcscasecmp_l.c", "musl/src/string/wcscat.c", "musl/src/string/wcschr.c", "musl/src/string/wcscmp.c", "musl/src/string/wcscpy.c", "musl/src/string/wcscspn.c", "musl/src/string/wcsdup.c", "musl/src/string/wcslen.c", "musl/src/string/wcsncasecmp.c", "musl/src/string/wcsncasecmp_l.c", "musl/src/string/wcsncat.c", "musl/src/string/wcsncmp.c", "musl/src/string/wcsncpy.c", "musl/src/string/wcsnlen.c", "musl/src/string/wcspbrk.c", "musl/src/string/wcsrchr.c", "musl/src/string/wcsspn.c", "musl/src/string/wcsstr.c", "musl/src/string/wcstok.c", "musl/src/string/wcswcs.c", "musl/src/string/wmemchr.c", "musl/src/string/wmemcmp.c", "musl/src/string/wmemcpy.c", "musl/src/string/wmemmove.c", "musl/src/string/wmemset.c", "musl/src/string/x86_64/memcpy.s", "musl/src/string/x86_64/memmove.s", "musl/src/string/x86_64/memset.s", "musl/src/temp/__randname.c", "musl/src/temp/mkdtemp.c", "musl/src/temp/mkostemp.c", "musl/src/temp/mkostemps.c", "musl/src/temp/mkstemp.c", "musl/src/temp/mkstemps.c", "musl/src/temp/mktemp.c", "musl/src/termios/cfgetospeed.c", "musl/src/termios/cfmakeraw.c", "musl/src/termios/cfsetospeed.c", "musl/src/termios/tcdrain.c", "musl/src/termios/tcflow.c", "musl/src/termios/tcflush.c", "musl/src/termios/tcgetattr.c", "musl/src/termios/tcgetsid.c", "musl/src/termios/tcsendbreak.c", "musl/src/termios/tcsetattr.c", "musl/src/thread/__lock.c", "musl/src/thread/__set_thread_area.c", "musl/src/thread/__syscall_cp.c", "musl/src/thread/__timedwait.c", "musl/src/thread/__tls_get_addr.c", "musl/src/thread/__unmapself.c", "musl/src/thread/__wait.c", "musl/src/thread/aarch64/__set_thread_area.s", "musl/src/thread/aarch64/__unmapself.s", "musl/src/thread/aarch64/clone.s", "musl/src/thread/aarch64/syscall_cp.s", "musl/src/thread/arm/__aeabi_read_tp.s", "musl/src/thread/arm/__set_thread_area.c", "musl/src/thread/arm/__unmapself.s", "musl/src/thread/arm/atomics.s", "musl/src/thread/arm/clone.s", "musl/src/thread/arm/syscall_cp.s", "musl/src/thread/call_once.c", "musl/src/thread/clone.c", "musl/src/thread/cnd_broadcast.c", "musl/src/thread/cnd_destroy.c", "musl/src/thread/cnd_init.c", "musl/src/thread/cnd_signal.c", "musl/src/thread/cnd_timedwait.c", "musl/src/thread/cnd_wait.c", "musl/src/thread/default_attr.c", "musl/src/thread/i386/__set_thread_area.s", "musl/src/thread/i386/__unmapself.s", "musl/src/thread/i386/clone.s", "musl/src/thread/i386/syscall_cp.s", "musl/src/thread/i386/tls.s", "musl/src/thread/lock_ptc.c", "musl/src/thread/m68k/__m68k_read_tp.s", "musl/src/thread/m68k/clone.s", "musl/src/thread/m68k/syscall_cp.s", "musl/src/thread/microblaze/__set_thread_area.s", "musl/src/thread/microblaze/__unmapself.s", "musl/src/thread/microblaze/clone.s", "musl/src/thread/microblaze/syscall_cp.s", "musl/src/thread/mips/__unmapself.s", "musl/src/thread/mips/clone.s", "musl/src/thread/mips/syscall_cp.s", "musl/src/thread/mips64/__unmapself.s", "musl/src/thread/mips64/clone.s", "musl/src/thread/mips64/syscall_cp.s", "musl/src/thread/mipsn32/__unmapself.s", "musl/src/thread/mipsn32/clone.s", "musl/src/thread/mipsn32/syscall_cp.s", "musl/src/thread/mtx_destroy.c", "musl/src/thread/mtx_init.c", "musl/src/thread/mtx_lock.c", "musl/src/thread/mtx_timedlock.c", "musl/src/thread/mtx_trylock.c", "musl/src/thread/mtx_unlock.c", "musl/src/thread/or1k/__set_thread_area.s", "musl/src/thread/or1k/__unmapself.s", "musl/src/thread/or1k/clone.s", "musl/src/thread/or1k/syscall_cp.s", "musl/src/thread/powerpc/__set_thread_area.s", "musl/src/thread/powerpc/__unmapself.s", "musl/src/thread/powerpc/clone.s", "musl/src/thread/powerpc/syscall_cp.s", "musl/src/thread/powerpc64/__set_thread_area.s", "musl/src/thread/powerpc64/__unmapself.s", "musl/src/thread/powerpc64/clone.s", "musl/src/thread/powerpc64/syscall_cp.s", "musl/src/thread/pthread_atfork.c", "musl/src/thread/pthread_attr_destroy.c", "musl/src/thread/pthread_attr_get.c", "musl/src/thread/pthread_attr_init.c", "musl/src/thread/pthread_attr_setdetachstate.c", "musl/src/thread/pthread_attr_setguardsize.c", "musl/src/thread/pthread_attr_setinheritsched.c", "musl/src/thread/pthread_attr_setschedparam.c", "musl/src/thread/pthread_attr_setschedpolicy.c", "musl/src/thread/pthread_attr_setscope.c", "musl/src/thread/pthread_attr_setstack.c", "musl/src/thread/pthread_attr_setstacksize.c", "musl/src/thread/pthread_barrier_destroy.c", "musl/src/thread/pthread_barrier_init.c", "musl/src/thread/pthread_barrier_wait.c", "musl/src/thread/pthread_barrierattr_destroy.c", "musl/src/thread/pthread_barrierattr_init.c", "musl/src/thread/pthread_barrierattr_setpshared.c", "musl/src/thread/pthread_cancel.c", "musl/src/thread/pthread_cleanup_push.c", "musl/src/thread/pthread_cond_broadcast.c", "musl/src/thread/pthread_cond_destroy.c", "musl/src/thread/pthread_cond_init.c", "musl/src/thread/pthread_cond_signal.c", "musl/src/thread/pthread_cond_timedwait.c", "musl/src/thread/pthread_cond_wait.c", "musl/src/thread/pthread_condattr_destroy.c", "musl/src/thread/pthread_condattr_init.c", "musl/src/thread/pthread_condattr_setclock.c", "musl/src/thread/pthread_condattr_setpshared.c", "musl/src/thread/pthread_create.c", "musl/src/thread/pthread_detach.c", "musl/src/thread/pthread_equal.c", "musl/src/thread/pthread_getattr_np.c", "musl/src/thread/pthread_getconcurrency.c", "musl/src/thread/pthread_getcpuclockid.c", "musl/src/thread/pthread_getschedparam.c", "musl/src/thread/pthread_getspecific.c", "musl/src/thread/pthread_join.c", "musl/src/thread/pthread_key_create.c", "musl/src/thread/pthread_kill.c", "musl/src/thread/pthread_mutex_consistent.c", "musl/src/thread/pthread_mutex_destroy.c", "musl/src/thread/pthread_mutex_getprioceiling.c", "musl/src/thread/pthread_mutex_init.c", "musl/src/thread/pthread_mutex_lock.c", "musl/src/thread/pthread_mutex_setprioceiling.c", "musl/src/thread/pthread_mutex_timedlock.c", "musl/src/thread/pthread_mutex_trylock.c", "musl/src/thread/pthread_mutex_unlock.c", "musl/src/thread/pthread_mutexattr_destroy.c", "musl/src/thread/pthread_mutexattr_init.c", "musl/src/thread/pthread_mutexattr_setprotocol.c", "musl/src/thread/pthread_mutexattr_setpshared.c", "musl/src/thread/pthread_mutexattr_setrobust.c", "musl/src/thread/pthread_mutexattr_settype.c", "musl/src/thread/pthread_once.c", "musl/src/thread/pthread_rwlock_destroy.c", "musl/src/thread/pthread_rwlock_init.c", "musl/src/thread/pthread_rwlock_rdlock.c", "musl/src/thread/pthread_rwlock_timedrdlock.c", "musl/src/thread/pthread_rwlock_timedwrlock.c", "musl/src/thread/pthread_rwlock_tryrdlock.c", "musl/src/thread/pthread_rwlock_trywrlock.c", "musl/src/thread/pthread_rwlock_unlock.c", "musl/src/thread/pthread_rwlock_wrlock.c", "musl/src/thread/pthread_rwlockattr_destroy.c", "musl/src/thread/pthread_rwlockattr_init.c", "musl/src/thread/pthread_rwlockattr_setpshared.c", "musl/src/thread/pthread_self.c", "musl/src/thread/pthread_setattr_default_np.c", "musl/src/thread/pthread_setcancelstate.c", "musl/src/thread/pthread_setcanceltype.c", "musl/src/thread/pthread_setconcurrency.c", "musl/src/thread/pthread_setname_np.c", "musl/src/thread/pthread_setschedparam.c", "musl/src/thread/pthread_setschedprio.c", "musl/src/thread/pthread_setspecific.c", "musl/src/thread/pthread_sigmask.c", "musl/src/thread/pthread_spin_destroy.c", "musl/src/thread/pthread_spin_init.c", "musl/src/thread/pthread_spin_lock.c", "musl/src/thread/pthread_spin_trylock.c", "musl/src/thread/pthread_spin_unlock.c", "musl/src/thread/pthread_testcancel.c", "musl/src/thread/riscv64/__set_thread_area.s", "musl/src/thread/riscv64/__unmapself.s", "musl/src/thread/riscv64/clone.s", "musl/src/thread/riscv64/syscall_cp.s", "musl/src/thread/s390x/__set_thread_area.s", "musl/src/thread/s390x/__tls_get_offset.s", "musl/src/thread/s390x/__unmapself.s", "musl/src/thread/s390x/clone.s", "musl/src/thread/s390x/syscall_cp.s", "musl/src/thread/sem_destroy.c", "musl/src/thread/sem_getvalue.c", "musl/src/thread/sem_init.c", "musl/src/thread/sem_open.c", "musl/src/thread/sem_post.c", "musl/src/thread/sem_timedwait.c", "musl/src/thread/sem_trywait.c", "musl/src/thread/sem_unlink.c", "musl/src/thread/sem_wait.c", "musl/src/thread/sh/__set_thread_area.c", "musl/src/thread/sh/__unmapself.c", "musl/src/thread/sh/__unmapself_mmu.s", "musl/src/thread/sh/atomics.s", "musl/src/thread/sh/clone.s", "musl/src/thread/sh/syscall_cp.s", "musl/src/thread/synccall.c", "musl/src/thread/syscall_cp.c", "musl/src/thread/thrd_create.c", "musl/src/thread/thrd_exit.c", "musl/src/thread/thrd_join.c", "musl/src/thread/thrd_sleep.c", "musl/src/thread/thrd_yield.c", "musl/src/thread/tls.c", "musl/src/thread/tss_create.c", "musl/src/thread/tss_delete.c", "musl/src/thread/tss_set.c", "musl/src/thread/vmlock.c", "musl/src/thread/x32/__set_thread_area.s", "musl/src/thread/x32/__unmapself.s", "musl/src/thread/x32/clone.s", "musl/src/thread/x32/syscall_cp.s", "musl/src/thread/x86_64/__set_thread_area.s", "musl/src/thread/x86_64/__unmapself.s", "musl/src/thread/x86_64/clone.s", "musl/src/thread/x86_64/syscall_cp.s", "musl/src/time/__map_file.c", "musl/src/time/__month_to_secs.c", "musl/src/time/__secs_to_tm.c", "musl/src/time/__tm_to_secs.c", "musl/src/time/__tz.c", "musl/src/time/__year_to_secs.c", "musl/src/time/asctime.c", "musl/src/time/asctime_r.c", "musl/src/time/clock.c", "musl/src/time/clock_getcpuclockid.c", "musl/src/time/clock_getres.c", "musl/src/time/clock_gettime.c", "musl/src/time/clock_nanosleep.c", "musl/src/time/clock_settime.c", "musl/src/time/ctime.c", "musl/src/time/ctime_r.c", "musl/src/time/difftime.c", "musl/src/time/ftime.c", "musl/src/time/getdate.c", "musl/src/time/gettimeofday.c", "musl/src/time/gmtime.c", "musl/src/time/gmtime_r.c", "musl/src/time/localtime.c", "musl/src/time/localtime_r.c", "musl/src/time/mktime.c", "musl/src/time/nanosleep.c", "musl/src/time/strftime.c", "musl/src/time/strptime.c", "musl/src/time/time.c", "musl/src/time/timegm.c", "musl/src/time/timer_create.c", "musl/src/time/timer_delete.c", "musl/src/time/timer_getoverrun.c", "musl/src/time/timer_gettime.c", "musl/src/time/timer_settime.c", "musl/src/time/times.c", "musl/src/time/timespec_get.c", "musl/src/time/utime.c", "musl/src/time/wcsftime.c", "musl/src/unistd/_exit.c", "musl/src/unistd/access.c", "musl/src/unistd/acct.c", "musl/src/unistd/alarm.c", "musl/src/unistd/chdir.c", "musl/src/unistd/chown.c", "musl/src/unistd/close.c", "musl/src/unistd/ctermid.c", "musl/src/unistd/dup.c", "musl/src/unistd/dup2.c", "musl/src/unistd/dup3.c", "musl/src/unistd/faccessat.c", "musl/src/unistd/fchdir.c", "musl/src/unistd/fchown.c", "musl/src/unistd/fchownat.c", "musl/src/unistd/fdatasync.c", "musl/src/unistd/fsync.c", "musl/src/unistd/ftruncate.c", "musl/src/unistd/getcwd.c", "musl/src/unistd/getegid.c", "musl/src/unistd/geteuid.c", "musl/src/unistd/getgid.c", "musl/src/unistd/getgroups.c", "musl/src/unistd/gethostname.c", "musl/src/unistd/getlogin.c", "musl/src/unistd/getlogin_r.c", "musl/src/unistd/getpgid.c", "musl/src/unistd/getpgrp.c", "musl/src/unistd/getpid.c", "musl/src/unistd/getppid.c", "musl/src/unistd/getsid.c", "musl/src/unistd/getuid.c", "musl/src/unistd/isatty.c", "musl/src/unistd/lchown.c", "musl/src/unistd/link.c", "musl/src/unistd/linkat.c", "musl/src/unistd/lseek.c", "musl/src/unistd/mips/pipe.s", "musl/src/unistd/mips64/pipe.s", "musl/src/unistd/mipsn32/lseek.c", "musl/src/unistd/mipsn32/pipe.s", "musl/src/unistd/nice.c", "musl/src/unistd/pause.c", "musl/src/unistd/pipe.c", "musl/src/unistd/pipe2.c", "musl/src/unistd/posix_close.c", "musl/src/unistd/pread.c", "musl/src/unistd/preadv.c", "musl/src/unistd/pwrite.c", "musl/src/unistd/pwritev.c", "musl/src/unistd/read.c", "musl/src/unistd/readlink.c", "musl/src/unistd/readlinkat.c", "musl/src/unistd/readv.c", "musl/src/unistd/renameat.c", "musl/src/unistd/rmdir.c", "musl/src/unistd/setegid.c", "musl/src/unistd/seteuid.c", "musl/src/unistd/setgid.c", "musl/src/unistd/setpgid.c", "musl/src/unistd/setpgrp.c", "musl/src/unistd/setregid.c", "musl/src/unistd/setresgid.c", "musl/src/unistd/setresuid.c", "musl/src/unistd/setreuid.c", "musl/src/unistd/setsid.c", "musl/src/unistd/setuid.c", "musl/src/unistd/setxid.c", "musl/src/unistd/sh/pipe.s", "musl/src/unistd/sleep.c", "musl/src/unistd/symlink.c", "musl/src/unistd/symlinkat.c", "musl/src/unistd/sync.c", "musl/src/unistd/tcgetpgrp.c", "musl/src/unistd/tcsetpgrp.c", "musl/src/unistd/truncate.c", "musl/src/unistd/ttyname.c", "musl/src/unistd/ttyname_r.c", "musl/src/unistd/ualarm.c", "musl/src/unistd/unlink.c", "musl/src/unistd/unlinkat.c", "musl/src/unistd/usleep.c", "musl/src/unistd/write.c", "musl/src/unistd/writev.c", "musl/src/unistd/x32/lseek.c", }; const compat_time32_files = [_][]const u8{ "musl/compat/time32/__xstat.c", "musl/compat/time32/adjtime32.c", "musl/compat/time32/adjtimex_time32.c", "musl/compat/time32/aio_suspend_time32.c", "musl/compat/time32/clock_adjtime32.c", "musl/compat/time32/clock_getres_time32.c", "musl/compat/time32/clock_gettime32.c", "musl/compat/time32/clock_nanosleep_time32.c", "musl/compat/time32/clock_settime32.c", "musl/compat/time32/cnd_timedwait_time32.c", "musl/compat/time32/ctime32.c", "musl/compat/time32/ctime32_r.c", "musl/compat/time32/difftime32.c", "musl/compat/time32/fstat_time32.c", "musl/compat/time32/fstatat_time32.c", "musl/compat/time32/ftime32.c", "musl/compat/time32/futimens_time32.c", "musl/compat/time32/futimes_time32.c", "musl/compat/time32/futimesat_time32.c", "musl/compat/time32/getitimer_time32.c", "musl/compat/time32/getrusage_time32.c", "musl/compat/time32/gettimeofday_time32.c", "musl/compat/time32/gmtime32.c", "musl/compat/time32/gmtime32_r.c", "musl/compat/time32/localtime32.c", "musl/compat/time32/localtime32_r.c", "musl/compat/time32/lstat_time32.c", "musl/compat/time32/lutimes_time32.c", "musl/compat/time32/mktime32.c", "musl/compat/time32/mq_timedreceive_time32.c", "musl/compat/time32/mq_timedsend_time32.c", "musl/compat/time32/mtx_timedlock_time32.c", "musl/compat/time32/nanosleep_time32.c", "musl/compat/time32/ppoll_time32.c", "musl/compat/time32/pselect_time32.c", "musl/compat/time32/pthread_cond_timedwait_time32.c", "musl/compat/time32/pthread_mutex_timedlock_time32.c", "musl/compat/time32/pthread_rwlock_timedrdlock_time32.c", "musl/compat/time32/pthread_rwlock_timedwrlock_time32.c", "musl/compat/time32/pthread_timedjoin_np_time32.c", "musl/compat/time32/recvmmsg_time32.c", "musl/compat/time32/sched_rr_get_interval_time32.c", "musl/compat/time32/select_time32.c", "musl/compat/time32/sem_timedwait_time32.c", "musl/compat/time32/semtimedop_time32.c", "musl/compat/time32/setitimer_time32.c", "musl/compat/time32/settimeofday_time32.c", "musl/compat/time32/sigtimedwait_time32.c", "musl/compat/time32/stat_time32.c", "musl/compat/time32/stime32.c", "musl/compat/time32/thrd_sleep_time32.c", "musl/compat/time32/time32.c", "musl/compat/time32/time32gm.c", "musl/compat/time32/timer_gettime32.c", "musl/compat/time32/timer_settime32.c", "musl/compat/time32/timerfd_gettime32.c", "musl/compat/time32/timerfd_settime32.c", "musl/compat/time32/timespec_get_time32.c", "musl/compat/time32/utime_time32.c", "musl/compat/time32/utimensat_time32.c", "musl/compat/time32/utimes_time32.c", "musl/compat/time32/wait3_time32.c", "musl/compat/time32/wait4_time32.c", };
src/musl.zig
const std = @import("std"); const string = []const u8; const gpa = std.heap.c_allocator; const inquirer = @import("inquirer"); const detectlicense = @import("detect-license"); const knownfolders = @import("known-folders"); const ini = @import("ini"); const u = @import("./../util/index.zig"); // // const s_in_y = std.time.s_per_week * 52; pub fn execute(args: [][]u8) !void { _ = args; std.debug.print("This utility will walk you through creating a zig.mod file.\n", .{}); std.debug.print("That will give a good launching off point to get your next project started.\n", .{}); std.debug.print("Use `zigmod aq add <pkg>` to add a dependency from https://aquila.red/\n", .{}); std.debug.print("Press ^C at any time to quit.\n", .{}); std.debug.print("\n", .{}); const stdout = std.io.getStdOut().writer(); const stdin = std.io.getStdIn().reader(); const cwd = std.fs.cwd(); const id = try inquirer.answer(stdout, "ID (this gets autogenerated):", string, "{s}", try u.random_string(gpa, 48)); const ptype = try inquirer.forEnum(stdout, stdin, "Are you making an application or a library?", gpa, enum { exe, lib }, null); const name = try inquirer.forString(stdout, stdin, "package name:", gpa, u.detect_pkgname(gpa, u.try_index(string, args, 0, ""), "") catch |err| switch (err) { error.NoBuildZig => { u.fail("init requires a build.zig file", .{}); }, else => return err, }); const entry = if (ptype == .lib) try inquirer.forString(stdout, stdin, "package entry point:", gpa, u.detct_mainfile(gpa, u.try_index(string, args, 1, ""), null, name) catch |err| switch (err) { error.CantFindMain => null, else => return err, }) else null; const license = try inquirer.forString(stdout, stdin, "license:", gpa, try detectlicense.detectInDir(gpa, cwd)); const description = try inquirer.forString(stdout, stdin, "description:", gpa, null); std.debug.print("\n", .{}); std.debug.print("About to write local zig.mod:\n", .{}); std.debug.print("\n", .{}); switch (ptype) { .exe => try writeExeManifest(stdout, id, name, license, description), .lib => try writeLibManifest(stdout, id, name, entry.?, license, description), } std.debug.print("\n", .{}); switch (try inquirer.forConfirm(stdout, stdin, "Is this okay?", gpa)) { false => { std.debug.print("okay. quitting...", .{}); return; }, true => { const file = try cwd.createFile("zig.mod", .{}); defer file.close(); const w = file.writer(); switch (ptype) { .exe => try writeExeManifest(w, id, name, license, description), .lib => try writeLibManifest(w, id, name, entry.?, license, description), } std.debug.print("\n", .{}); u.print("Successfully initialized new package {s}!\n", .{name}); }, } // ask about LICENSE if (!(try u.does_file_exist(null, "LICENSE"))) { if (detectlicense.licenses.find(license)) |text| { if (try inquirer.forConfirm(stdout, stdin, "It appears you don't have a LICENSE file defined, would you like init to add it for you?", gpa)) { var realtext = text; realtext = try std.mem.replaceOwned(u8, gpa, realtext, "<year>", try inquirer.answer( stdout, "year:", string, "{s}", try std.fmt.allocPrint(gpa, "{d}", .{1970 + @divFloor(std.time.timestamp(), s_in_y)}), )); realtext = try std.mem.replaceOwned(u8, gpa, realtext, "<copyright holders>", try inquirer.forString( stdout, stdin, "copyright holder's name:", gpa, try guessCopyrightName(), )); const file = try cwd.createFile("LICENSE", .{}); defer file.close(); const w = file.writer(); try w.writeAll(realtext); } } } // ask about .gitignore if (try u.does_folder_exist(".git")) { const do = try inquirer.forConfirm(stdout, stdin, "It appears you're using git. Do you want init to add Zigmod to your .gitignore?", gpa); if (do) { const exists = try u.does_file_exist(null, ".gitignore"); const file: std.fs.File = try (if (exists) cwd.openFile(".gitignore", .{ .read = true, .write = true }) else cwd.createFile(".gitignore", .{})); defer file.close(); const len = try file.getEndPos(); if (len > 0) try file.seekTo(len - 1); const w = file.writer(); if (len > 0 and (try file.reader().readByte()) != '\n') { try w.writeAll("\n"); } if (!exists) try w.writeAll("zig-*\n"); try w.writeAll(".zigmod\n"); try w.writeAll("deps.zig\n"); } } // ask about .gitattributes if (try u.does_folder_exist(".git")) { const do = try inquirer.forConfirm(stdout, stdin, "It appears you're using git. Do you want init to add Zigmod to your .gitattributes?", gpa); if (do) { const exists = try u.does_file_exist(null, ".gitattributes"); const file: std.fs.File = try (if (exists) cwd.openFile(".gitattributes", .{ .read = true, .write = true }) else cwd.createFile(".gitattributes", .{})); defer file.close(); const len = try file.getEndPos(); if (len > 0) try file.seekTo(len - 1); const w = file.writer(); if (len > 0 and (try file.reader().readByte()) != '\n') { try w.writeAll("\n"); } if (!exists) try w.writeAll("* text=auto\n"); if (!exists) try w.writeAll("*.zig text eol=lf # See https://github.com/ziglang/zig-spec/issues/38\n"); try w.writeAll("zig.mod text eol=lf\n"); try w.writeAll("zigmod.* text eol=lf\n"); try w.writeAll("zig.mod linguist-language=YAML\n"); try w.writeAll("zig.mod gitlab-language=yaml\n"); } } } pub fn writeExeManifest(w: std.fs.File.Writer, id: string, name: string, license: ?string, description: ?string) !void { try w.print("id: {s}\n", .{id}); try w.print("name: {s}\n", .{name}); if (license) |_| try w.print("license: {s}\n", .{license.?}); if (description) |_| try w.print("description: {s}\n", .{description.?}); try w.print("dev_dependencies:\n", .{}); } pub fn writeLibManifest(w: std.fs.File.Writer, id: string, name: string, entry: string, license: string, description: string) !void { try w.print("id: {s}\n", .{id}); try w.print("name: {s}\n", .{name}); try w.print("main: {s}\n", .{entry}); try w.print("license: {s}\n", .{license}); try w.print("description: {s}\n", .{description}); try w.print("dependencies:\n", .{}); } fn guessCopyrightName() !?string { const home = (try knownfolders.open(gpa, .home, .{})).?; if (!(try u.does_file_exist(home, ".gitconfig"))) return null; const file = try home.openFile(".gitconfig", .{}); const content = try file.reader().readAllAlloc(gpa, 1024 * 1024); var iniO = try ini.parseIntoMap(content, gpa); return iniO.map.get("user.name"); }
src/cmd/init.zig
const Archive = @This(); const std = @import("std"); const fmt = std.fmt; const fs = std.fs; const mem = std.mem; const log = std.log.scoped(.archive); const Allocator = std.mem.Allocator; file: fs.File, name: []const u8, // We need to differentiate between inferred and output archive type, as other ar // programs "just handle" any valid archive for parsing, regarldess of what a // user has specified - the user specification should only matter for writing // archives. inferred_archive_type: ArchiveType, output_archive_type: ArchiveType, files: std.ArrayListUnmanaged(ArchivedFile), // Use it so we can easily lookup files indices when inserting! // TODO: A trie is probably a lot better here filename_to_index: std.StringArrayHashMapUnmanaged(u64), pub const ArchiveType = enum { ambiguous, gnu, gnuthin, gnu64, bsd, darwin64, // darwin_32 *is* bsd coff, // (windows) }; pub const Operation = enum { insert, delete, move, print_contents, quick_append, ranlib, print_names, extract, }; pub const Modifier = enum { none, create, // disables creation warning zero_timestamp, }; // All archive files start with this magic string pub const magic_string = "!<arch>\n"; pub const magic_thin = "!<thin>\n"; // GNU constants pub const gnu_first_line_buffer_length = 60; pub const gnu_string_table_seek_pos = magic_string.len + gnu_first_line_buffer_length; // BSD constants pub const bsd_name_length_signifier = "#1/"; pub const bsd_symdef_magic = "__.SYMDEF"; // The format (unparsed) of the archive per-file header // NOTE: The reality is more complex than this as different mechanisms // have been devised for storing the names of files which exceed 16 byte! pub const Header = extern struct { ar_name: [16]u8, ar_date: [12]u8, ar_uid: [6]u8, ar_gid: [6]u8, ar_mode: [8]u8, ar_size: [10]u8, ar_fmag: [2]u8, }; pub const Contents = struct { bytes: []u8, length: u64, // mode: u64, // TODO: dellocation pub fn write(self: *const Contents, out_stream: anytype, stderr: anytype) !void { try out_stream.writeAll(self.bytes); _ = stderr; } }; // An internal represantion of files being archived pub const ArchivedFile = struct { name: []const u8, contents: Contents, }; pub fn getDefaultArchiveTypeFromHost() ArchiveType { // TODO: Set this based on the current platform you are using the tool // on! return .gnu; } pub fn create( file: fs.File, name: []const u8, output_archive_type: ArchiveType, ) Archive { return Archive{ .file = file, .name = name, .inferred_archive_type = .ambiguous, .output_archive_type = output_archive_type, .files = .{}, .filename_to_index = .{}, }; } // TODO: This needs to be integrated into the workflow // used for parsing. (use same error handling workflow etc.) /// Use same naming scheme for objects (as found elsewhere in the file). pub fn finalize(self: *Archive, allocator: *Allocator) !void { // Overwrite all contents try self.file.seekTo(0); if (self.output_archive_type == .ambiguous) { // Set output archive type of one we might just have parsed... self.output_archive_type = self.inferred_archive_type; } if (self.output_archive_type == .ambiguous) { // if output archive type is still ambiguous (none was inferred, and // none was set) then we need to infer it from the host platform! self.output_archive_type = getDefaultArchiveTypeFromHost(); } const writer = self.file.writer(); try writer.writeAll(if (self.output_archive_type == .gnuthin) magic_thin else magic_string); const header_names = try allocator.alloc([16]u8, self.files.items.len); switch (self.output_archive_type) { .gnu, .gnuthin, .gnu64 => { // GNU format: Create string table var string_table = std.ArrayList(u8).init(allocator); defer string_table.deinit(); // Generate the complete string table for (self.files.items) |file, index| { const is_the_name_allowed = (file.name.len < 16) and (self.output_archive_type != .gnuthin); // If the file is small enough to fit in header, then just write it there // Otherwise, add it to string table and add a reference to its location const name = if (is_the_name_allowed) try mem.concat(allocator, u8, &.{ file.name, "/" }) else try std.fmt.allocPrint(allocator, "/{}", .{blk: { // Get the position of the file in string table const pos = string_table.items.len; // Now add the file name to string table try string_table.appendSlice(file.name); try string_table.appendSlice("/\n"); break :blk pos; }}); defer allocator.free(name); // Edit the header _ = try std.fmt.bufPrint(&(header_names[index]), "{s: <16}", .{name}); } // Write the string table itself { if (string_table.items.len != 0) { try writer.print("//{s}{: <10}`\n{s}", .{ " " ** 46, string_table.items.len, string_table.items }); } } }, .bsd, .darwin64 => { // BSD format: Just write the length of the name in header for (self.files.items) |file, index| { _ = try std.fmt.bufPrint(&(header_names[index]), "#1/{: <13}", .{file.name.len}); } }, else => unreachable, } // Write the files for (self.files.items) |file, index| { // Write the header // For now, we just write a garbage value to header.name and resolve it later var headerBuffer: [@sizeOf(Header)]u8 = undefined; _ = try std.fmt.bufPrint( &headerBuffer, "{s: <16}{: <12}{: <6}{: <6}{o: <8}{: <10}`\n", .{ &header_names[index], 0, 0, 0, 0, file.contents.length }, ); // TODO: handle errors _ = try writer.write(&headerBuffer); // Write the name of the file in the data section if (self.output_archive_type == .bsd) { try writer.writeAll(file.name); } if (self.output_archive_type != .gnuthin) try file.contents.write(writer, null); } // Truncate the file size try self.file.setEndPos(try self.file.getPos()); } pub fn deleteFiles(self: *Archive, file_names: [][]const u8) !void { // For the list of given file names, find the entry in self.files // and remove it from self.files. for (file_names) |file_name| { for (self.files.items) |file, index| { if (std.mem.eql(u8, file.name, file_name)) { _ = self.files.orderedRemove(index); break; } } } } pub fn extract(self: *Archive, file_names: [][]const u8) !void { if (self.inferred_archive_type == .gnuthin) { // TODO: better error return error.ExtractingFromThin; } for (self.files.items) |archived_file| { for (file_names) |file_name| { if (std.mem.eql(u8, archived_file.name, file_name)) { const file = try std.fs.cwd().createFile(archived_file.name, .{}); defer file.close(); try file.writeAll(archived_file.contents.bytes); break; } } } } pub fn insertFiles(self: *Archive, allocator: *Allocator, file_names: [][]const u8) !void { for (file_names) |file_name| { // Open the file and read all of its contents const file = try std.fs.cwd().openFile(file_name, .{ .read = true }); const file_stats = try file.stat(); const archived_file = ArchivedFile{ .name = file_name, // TODO: sort out the file-name with respect to path .contents = Contents{ .bytes = try file.readToEndAlloc(allocator, std.math.maxInt(usize)), .length = file_stats.size, // .mode = file_stats.mode, }, }; // A trie-based datastructure would be better for this! const getOrPutResult = try self.filename_to_index.getOrPut(allocator, archived_file.name); if (getOrPutResult.found_existing) { const existing_index = getOrPutResult.value_ptr.*; self.files.items[existing_index] = archived_file; } else { getOrPutResult.value_ptr.* = self.files.items.len; try self.files.append(allocator, archived_file); } } } pub fn parse(self: *Archive, allocator: *Allocator, stderr: anytype) !void { const reader = self.file.reader(); { // Is the magic header found at the start of the archive? var magic: [magic_string.len]u8 = undefined; const bytes_read = try reader.read(&magic); if (bytes_read == 0) { // Archive is empty and that is ok! return; } if (bytes_read < magic_string.len) { try stderr.print("File too short to be an archive\n", .{}); return error.NotArchive; } const is_thin_archive = mem.eql(u8, &magic, magic_thin); if (is_thin_archive) self.inferred_archive_type = .gnuthin; if (!(mem.eql(u8, &magic, magic_string) or is_thin_archive)) { try stderr.print("Invalid magic string: expected '{s}' or '{s}', found '{s}'\n", .{ magic_string, magic_thin, magic }); return error.NotArchive; } } var gnu_symbol_table_contents: []u8 = undefined; var string_table_contents: []u8 = undefined; var has_gnu_symbol_table = false; { // https://www.freebsd.org/cgi/man.cgi?query=ar&sektion=5 // Process string/symbol tables and/or try to infer archive type! var starting_seek_pos = magic_string.len; while (true) { var first_line_buffer: [gnu_first_line_buffer_length]u8 = undefined; const has_line_to_process = result: { const chars_read = reader.read(&first_line_buffer) catch |err| switch (err) { else => |e| return e, }; if (chars_read < first_line_buffer.len) { break :result false; } break :result true; }; if (has_line_to_process) { if (mem.eql(u8, first_line_buffer[0..2], "//"[0..2])) { switch (self.inferred_archive_type) { .ambiguous => self.inferred_archive_type = .gnu, .gnu, .gnuthin, .gnu64 => {}, else => { try stderr.print("Came across gnu-style string table in {} archive\n", .{self.inferred_archive_type}); return error.NotArchive; }, } const table_size_string = first_line_buffer[48..58]; const table_size = try fmt.parseInt(u32, mem.trim(u8, table_size_string, " "), 10); string_table_contents = try allocator.alloc(u8, table_size); // TODO: actually error handle not expected number of bytes being read! _ = try reader.read(string_table_contents); // starting_seek_pos = starting_seek_pos + first_line_buffer.len + table_size; break; } else if (!has_gnu_symbol_table and first_line_buffer[0] == '/') { has_gnu_symbol_table = true; switch (self.inferred_archive_type) { .ambiguous => self.inferred_archive_type = .gnu, .gnu, .gnuthin, .gnu64 => {}, else => { try stderr.print("Came across gnu-style symbol table in {} archive\n", .{self.inferred_archive_type}); return error.NotArchive; }, } const table_size_string = first_line_buffer[48..58]; const table_size = try fmt.parseInt(u32, mem.trim(u8, table_size_string, " "), 10); gnu_symbol_table_contents = try allocator.alloc(u8, table_size); _ = try reader.read(gnu_symbol_table_contents); // TODO: Calculate number of entries in symbol table // TODO: Create an array that is that size // TODO: Put all the strings in that array // TODO: Print them? // TODO: actually error handle not expected number of bytes being read! starting_seek_pos = starting_seek_pos + first_line_buffer.len + table_size; } else { try reader.context.seekTo(starting_seek_pos); break; } } } } var is_first = true; while (true) { const archive_header = reader.readStruct(Header) catch |err| switch (err) { error.EndOfStream => break, else => |e| return e, }; // the lifetime of the archive headers will matched that of the parsed files (for now) // so we can take a reference to the strings stored there directly! var trimmed_archive_name = mem.trim(u8, &archive_header.ar_name, " "); // Check against gnu naming properties const ends_with_gnu_slash = (trimmed_archive_name[trimmed_archive_name.len - 1] == '/'); var gnu_offset_value: u32 = 0; const starts_with_gnu_offset = trimmed_archive_name[0] == '/'; if (starts_with_gnu_offset) { gnu_offset_value = try fmt.parseInt(u32, trimmed_archive_name[1..trimmed_archive_name.len], 10); } const must_be_gnu = ends_with_gnu_slash or starts_with_gnu_offset or has_gnu_symbol_table; // Check against bsd naming properties const starts_with_bsd_name_length = (trimmed_archive_name.len >= 2) and mem.eql(u8, trimmed_archive_name[0..2], bsd_name_length_signifier[0..2]); const could_be_bsd = starts_with_bsd_name_length; // TODO: Have a proper mechanism for erroring on the wrong types of archive. switch (self.inferred_archive_type) { .ambiguous => { if (must_be_gnu) { self.inferred_archive_type = .gnu; } else if (could_be_bsd) { self.inferred_archive_type = .bsd; } else { return error.TODO; } }, .gnu, .gnuthin, .gnu64 => { if (!must_be_gnu) { try stderr.print("Error parsing archive header name - format of {s} wasn't gnu compatible\n", .{trimmed_archive_name}); return error.BadArchive; } }, .bsd, .darwin64 => { if (must_be_gnu) { try stderr.print("Error parsing archive header name - format of {s} wasn't bsd compatible\n", .{trimmed_archive_name}); return error.BadArchive; } }, else => { if (must_be_gnu) { return error.TODO; } return error.TODO; }, } if (ends_with_gnu_slash) { // slice-off the slash trimmed_archive_name = trimmed_archive_name[0 .. trimmed_archive_name.len - 1]; } if (starts_with_gnu_offset) { const name_offset_in_string_table = try fmt.parseInt(u32, mem.trim(u8, trimmed_archive_name[1..trimmed_archive_name.len], " "), 10); // Navigate to the start of the string in the string table const string_start = string_table_contents[name_offset_in_string_table..string_table_contents.len]; // Find the end of the string (which is always a newline) const end_string_index = mem.indexOf(u8, string_start, "\n"); if (end_string_index == null) { try stderr.print("Error parsing name in string table, couldn't find terminating character\n", .{}); return error.NotArchive; } const string_full = string_start[0..end_string_index.?]; // String must have a forward slash before the newline, so check that // is there and remove it as well! if (string_full[string_full.len - 1] != '/') { try stderr.print("Error parsing name in string table, didn't find '/' before terminating newline\n", .{}); return error.NotArchive; } // Referencing the slice directly is fine as same bumb allocator is // used as for the rest of the datastructure! trimmed_archive_name = string_full[0 .. string_full.len - 1]; } var seek_forward_amount = try fmt.parseInt(u32, mem.trim(u8, &archive_header.ar_size, " "), 10); // Make sure that these allocations get properly disposed of later! if (starts_with_bsd_name_length) { trimmed_archive_name = trimmed_archive_name[bsd_name_length_signifier.len..trimmed_archive_name.len]; const archive_name_length = fmt.parseInt(u32, trimmed_archive_name, 10) catch { try stderr.print("Error parsing bsd-style string length\n", .{}); return error.NotArchive; }; if (is_first) { // TODO: make sure this does a check on self.inferred_archive_type! // This could be the symbol table! So parse that here! const current_seek_pos = try reader.context.getPos(); var symbol_magic_check_buffer: [bsd_symdef_magic.len]u8 = undefined; // TODO: handle not reading enough characters! _ = try reader.read(&symbol_magic_check_buffer); if (mem.eql(u8, bsd_symdef_magic, &symbol_magic_check_buffer)) { // We have a symbol table! // TODO: parse symbol table, we just skip it for now... seek_forward_amount = seek_forward_amount - @as(u32, symbol_magic_check_buffer.len); try reader.context.seekBy(seek_forward_amount); continue; } try reader.context.seekTo(current_seek_pos); } is_first = false; const archive_name_buffer = try allocator.alloc(u8, archive_name_length); // TODO: proper error handling and length checking here! _ = try reader.read(archive_name_buffer); seek_forward_amount = seek_forward_amount - archive_name_length; // strip null characters from name - TODO find documentation on this // could not find documentation on this being needed, but some archivers // seems to insert these (for alignment reasons?) trimmed_archive_name = mem.trim(u8, archive_name_buffer, "\x00"); } else { const archive_name_buffer = try allocator.alloc(u8, trimmed_archive_name.len); mem.copy(u8, archive_name_buffer, trimmed_archive_name); trimmed_archive_name = archive_name_buffer; } const parsed_file = ArchivedFile{ .name = trimmed_archive_name, .contents = Contents{ .bytes = try allocator.alloc(u8, seek_forward_amount), .length = seek_forward_amount, }, }; if (self.inferred_archive_type == .gnuthin) { var thin_file = try std.fs.cwd().openFile(trimmed_archive_name, .{}); defer thin_file.close(); try thin_file.reader().readNoEof(parsed_file.contents.bytes); } else { try reader.readNoEof(parsed_file.contents.bytes); } try self.filename_to_index.put(allocator, trimmed_archive_name, self.files.items.len); try self.files.append(allocator, parsed_file); } } pub const MRIParser = struct { script: []const u8, archive: ?Archive, file_name: ?[]const u8, const CommandType = enum { open, create, createthin, addmod, list, delete, extract, save, clear, end, }; const Self = @This(); pub fn init(allocator: *Allocator, file: fs.File) !Self { const self = Self{ .script = try file.readToEndAlloc(allocator, std.math.maxInt(usize)), .archive = null, .file_name = null, }; return self; } // Returns the next token fn getToken(iter: *mem.SplitIterator(u8)) ?[]const u8 { while (iter.next()) |tok| { if (mem.startsWith(u8, tok, "*")) break; if (mem.startsWith(u8, tok, ";")) break; return tok; } return null; } // Returns a slice of tokens fn getTokenLine(allocator: *Allocator, iter: *mem.SplitIterator(u8)) ![][]const u8 { var list = std.ArrayList([]const u8).init(allocator); while (getToken(iter)) |tok| { try list.append(tok); } return list.toOwnedSlice(); } pub fn execute(self: *Self, allocator: *Allocator, stdout: fs.File.Writer, stderr: fs.File.Writer) !void { // Split the file into lines var parser = mem.split(u8, self.script, "\n"); while (parser.next()) |line| { // Split the line by spaces var line_parser = mem.split(u8, line, " "); if (getToken(&line_parser)) |tok| { var command_name = try allocator.dupe(u8, tok); defer allocator.free(command_name); _ = std.ascii.lowerString(command_name, tok); if (std.meta.stringToEnum(CommandType, command_name)) |command| { if (self.archive) |archive| { switch (command) { .addmod => { const file_names = try getTokenLine(allocator, &line_parser); defer allocator.free(file_names); try self.archive.?.insertFiles(allocator, file_names); }, .list => { // TODO: verbose output for (archive.files.items) |parsed_file| { try stdout.print("{s}\n", .{parsed_file.name}); } }, .delete => { const file_names = try getTokenLine(allocator, &line_parser); try self.archive.?.deleteFiles(file_names); }, .extract => { const file_names = try getTokenLine(allocator, &line_parser); try self.archive.?.extract(file_names); }, .save => { try self.archive.?.finalize(allocator); }, .clear => { // This is a bit of a hack but its reliable. // Instead of clearing out unsaved changes, we re-open the current file, which overwrites the changes. const file = try fs.cwd().openFile(self.file_name.?, .{ .write = true }); self.archive = Archive.create(file, self.file_name.?); try self.archive.?.parse(allocator, stderr); }, .end => return, else => { try stderr.print( "Archive `{s}` is currently open.\nThe command `{s}` can only be executed when no current archive is active.\n", .{ self.file_name.?, command_name }, ); return error.ArchiveAlreadyOpen; }, } } else { switch (command) { .open => { const file_name = getToken(&line_parser).?; const file = try fs.cwd().openFile(file_name, .{ .write = true }); self.archive = Archive.create(file, file_name); self.file_name = file_name; try self.archive.?.parse(allocator, stderr); }, .create, .createthin => { // TODO: Thin archives creation const file_name = getToken(&line_parser).?; const file = try fs.cwd().createFile(file_name, .{ .read = true }); self.archive = Archive.create(file, file_name); self.file_name = file_name; try self.archive.?.parse(allocator, stderr); }, .end => return, else => { try stderr.print("No currently active archive found.\nThe command `{s}` can only be executed when there is an opened archive.\n", .{command_name}); return error.NoCurrentArchive; }, } } } } } } };
src/archive/Archive.zig
const std = @import("std"); const builtin = @import("builtin"); const assert = std.debug.assert; var x: i32 = 1; test "create a coroutine and cancel it" { var da = std.heap.DirectAllocator.init(); defer da.deinit(); const p = try async<&da.allocator> simpleAsyncFn(); comptime assert(@typeOf(p) == promise->void); cancel p; assert(x == 2); } async fn simpleAsyncFn() void { x += 1; suspend; x += 1; } test "coroutine suspend, resume, cancel" { var da = std.heap.DirectAllocator.init(); defer da.deinit(); seq('a'); const p = try async<&da.allocator> testAsyncSeq(); seq('c'); resume p; seq('f'); cancel p; seq('g'); assert(std.mem.eql(u8, points, "abcdefg")); } async fn testAsyncSeq() void { defer seq('e'); seq('b'); suspend; seq('d'); } var points = []u8.{0} ** "abcdefg".len; var index: usize = 0; fn seq(c: u8) void { points[index] = c; index += 1; } test "coroutine suspend with block" { var da = std.heap.DirectAllocator.init(); defer da.deinit(); const p = try async<&da.allocator> testSuspendBlock(); std.debug.assert(!result); resume a_promise; std.debug.assert(result); cancel p; } var a_promise: promise = undefined; var result = false; async fn testSuspendBlock() void { suspend { comptime assert(@typeOf(@handle()) == promise->void); a_promise = @handle(); } //Test to make sure that @handle() works as advertised (issue #1296) //var our_handle: promise = @handle(); assert(a_promise == @handle()); result = true; } var await_a_promise: promise = undefined; var await_final_result: i32 = 0; test "coroutine await" { var da = std.heap.DirectAllocator.init(); defer da.deinit(); await_seq('a'); const p = async<&da.allocator> await_amain() catch unreachable; await_seq('f'); resume await_a_promise; await_seq('i'); assert(await_final_result == 1234); assert(std.mem.eql(u8, await_points, "abcdefghi")); } async fn await_amain() void { await_seq('b'); const p = async await_another() catch unreachable; await_seq('e'); await_final_result = await p; await_seq('h'); } async fn await_another() i32 { await_seq('c'); suspend { await_seq('d'); await_a_promise = @handle(); } await_seq('g'); return 1234; } var await_points = []u8.{0} ** "abcdefghi".len; var await_seq_index: usize = 0; fn await_seq(c: u8) void { await_points[await_seq_index] = c; await_seq_index += 1; } var early_final_result: i32 = 0; test "coroutine await early return" { var da = std.heap.DirectAllocator.init(); defer da.deinit(); early_seq('a'); const p = async<&da.allocator> early_amain() catch @panic("out of memory"); early_seq('f'); assert(early_final_result == 1234); assert(std.mem.eql(u8, early_points, "abcdef")); } async fn early_amain() void { early_seq('b'); const p = async early_another() catch @panic("out of memory"); early_seq('d'); early_final_result = await p; early_seq('e'); } async fn early_another() i32 { early_seq('c'); return 1234; } var early_points = []u8.{0} ** "abcdef".len; var early_seq_index: usize = 0; fn early_seq(c: u8) void { early_points[early_seq_index] = c; early_seq_index += 1; } test "coro allocation failure" { var failing_allocator = std.debug.FailingAllocator.init(std.debug.global_allocator, 0); if (async<&failing_allocator.allocator> asyncFuncThatNeverGetsRun()) { @panic("expected allocation failure"); } else |err| switch (err) { error.OutOfMemory => {}, } } async fn asyncFuncThatNeverGetsRun() void { @panic("coro frame allocation should fail"); } test "async function with dot syntax" { const S = struct.{ var y: i32 = 1; async fn foo() void { y += 1; suspend; } }; var da = std.heap.DirectAllocator.init(); defer da.deinit(); const p = try async<&da.allocator> S.foo(); cancel p; assert(S.y == 2); } test "async fn pointer in a struct field" { var data: i32 = 1; const Foo = struct.{ bar: async<*std.mem.Allocator> fn (*i32) void, }; var foo = Foo.{ .bar = simpleAsyncFn2 }; var da = std.heap.DirectAllocator.init(); defer da.deinit(); const p = (async<&da.allocator> foo.bar(&data)) catch unreachable; assert(data == 2); cancel p; assert(data == 4); } async<*std.mem.Allocator> fn simpleAsyncFn2(y: *i32) void { defer y.* += 2; y.* += 1; suspend; } test "async fn with inferred error set" { var da = std.heap.DirectAllocator.init(); defer da.deinit(); const p = (async<&da.allocator> failing()) catch unreachable; resume p; cancel p; } async fn failing() !void { suspend; return error.Fail; } test "error return trace across suspend points - early return" { const p = nonFailing(); resume p; var da = std.heap.DirectAllocator.init(); defer da.deinit(); const p2 = try async<&da.allocator> printTrace(p); cancel p2; } test "error return trace across suspend points - async return" { const p = nonFailing(); const p2 = try async<std.debug.global_allocator> printTrace(p); resume p; cancel p2; } // TODO https://github.com/ziglang/zig/issues/760 fn nonFailing() (promise->error!void) { return async<std.debug.global_allocator> suspendThenFail() catch unreachable; } async fn suspendThenFail() error!void { suspend; return error.Fail; } async fn printTrace(p: promise->error!void) void { (await p) catch |e| { std.debug.assert(e == error.Fail); if (@errorReturnTrace()) |trace| { assert(trace.index == 1); } else switch (builtin.mode) { builtin.Mode.Debug, builtin.Mode.ReleaseSafe => @panic("expected return trace"), builtin.Mode.ReleaseFast, builtin.Mode.ReleaseSmall => {}, } }; } test "break from suspend" { var buf: [500]u8 = undefined; var a = &std.heap.FixedBufferAllocator.init(buf[0..]).allocator; var my_result: i32 = 1; const p = try async<a> testBreakFromSuspend(&my_result); cancel p; std.debug.assert(my_result == 2); } async fn testBreakFromSuspend(my_result: *i32) void { suspend { resume @handle(); } my_result.* += 1; suspend; my_result.* += 1; }
test/cases/coroutines.zig
const std = @import("std"); const types = @import("types.zig"); const URI = @import("uri.zig"); const analysis = @import("analysis.zig"); const DocumentStore = @This(); pub const Handle = struct { document: types.TextDocument, count: usize, import_uris: std.ArrayList([]const u8), pub fn uri(handle: Handle) []const u8 { return handle.document.uri; } /// Returns a zig AST, with all its errors. pub fn tree(handle: Handle, allocator: *std.mem.Allocator) !*std.zig.ast.Tree { return try std.zig.parse(allocator, handle.document.text); } }; allocator: *std.mem.Allocator, handles: std.StringHashMap(Handle), std_uri: ?[]const u8, pub fn init(self: *DocumentStore, allocator: *std.mem.Allocator, zig_lib_path: ?[]const u8) !void { self.allocator = allocator; self.handles = std.StringHashMap(Handle).init(allocator); errdefer self.handles.deinit(); if (zig_lib_path) |zpath| { const std_path = std.fs.path.resolve(allocator, &[_][]const u8 { zpath, "./std/std.zig" }) catch |err| block: { std.debug.warn("Failed to resolve zig std library path, error: {}\n", .{err}); self.std_uri = null; return; }; defer allocator.free(std_path); // Get the std_path as a URI, so we can just append to it! self.std_uri = try URI.fromPath(allocator, std_path); std.debug.warn("Standard library base uri: {}\n", .{self.std_uri}); } else { self.std_uri = null; } } /// This function asserts the document is not open yet and takes ownership /// of the uri and text passed in. fn newDocument(self: *DocumentStore, uri: []const u8, text: []u8) !*Handle { std.debug.warn("Opened document: {}\n", .{uri}); var handle = Handle{ .count = 1, .import_uris = std.ArrayList([]const u8).init(self.allocator), .document = .{ .uri = uri, .text = text, .mem = text, }, }; try self.checkSanity(&handle); const kv = try self.handles.getOrPutValue(uri, handle); return &kv.value; } pub fn openDocument(self: *DocumentStore, uri: []const u8, text: []const u8) !*Handle { if (self.handles.get(uri)) |entry| { std.debug.warn("Document already open: {}, incrementing count\n", .{uri}); entry.value.count += 1; std.debug.warn("New count: {}\n", .{entry.value.count}); return &entry.value; } const duped_text = try std.mem.dupe(self.allocator, u8, text); errdefer self.allocator.free(duped_text); const duped_uri = try std.mem.dupe(self.allocator, u8, uri); errdefer self.allocator.free(duped_uri); return try self.newDocument(duped_uri, duped_text); } fn decrementCount(self: *DocumentStore, uri: []const u8) void { if (self.handles.get(uri)) |entry| { entry.value.count -= 1; if (entry.value.count > 0) return; std.debug.warn("Freeing document: {}\n", .{uri}); self.allocator.free(entry.value.document.mem); for (entry.value.import_uris.items) |import_uri| { self.decrementCount(import_uri); self.allocator.free(import_uri); } entry.value.import_uris.deinit(); const uri_key = entry.key; self.handles.removeAssertDiscard(uri); self.allocator.free(uri_key); } } pub fn closeDocument(self: *DocumentStore, uri: []const u8) void { self.decrementCount(uri); } pub fn getHandle(self: *DocumentStore, uri: []const u8) ?*Handle { if (self.handles.get(uri)) |entry| { return &entry.value; } return null; } // Check if the document text is now sane, move it to sane_text if so. fn checkSanity(self: *DocumentStore, handle: *Handle) !void { const tree = try handle.tree(self.allocator); defer tree.deinit(); std.debug.warn("New text for document {}\n", .{handle.uri()}); // TODO: Better algorithm or data structure? // Removing the imports is costly since they live in an array list // Perhaps we should use an AutoHashMap([]const u8, {}) ? // Try to detect removed imports and decrement their counts. if (handle.import_uris.items.len == 0) return; const import_strs = try analysis.collectImports(self.allocator, tree); defer self.allocator.free(import_strs); const still_exist = try self.allocator.alloc(bool, handle.import_uris.items.len); defer self.allocator.free(still_exist); for (still_exist) |*ex| { ex.* = false; } for (import_strs) |str| { const uri = (try uriFromImportStr(self, handle.*, str)) orelse continue; defer self.allocator.free(uri); var idx: usize = 0; exists_loop: while (idx < still_exist.len) : (idx += 1) { if (still_exist[idx]) continue; if (std.mem.eql(u8, handle.import_uris.items[idx], uri)) { still_exist[idx] = true; break :exists_loop; } } } // Go through still_exist, remove the items that are false and decrement their handle counts. var offset: usize = 0; var idx: usize = 0; while (idx < still_exist.len) : (idx += 1) { if (still_exist[idx]) continue; std.debug.warn("Import removed: {}\n", .{handle.import_uris.items[idx - offset]}); const uri = handle.import_uris.orderedRemove(idx - offset); offset += 1; self.closeDocument(uri); self.allocator.free(uri); } } pub fn applyChanges(self: *DocumentStore, handle: *Handle, content_changes: std.json.Array) !void { const document = &handle.document; for (content_changes.items) |change| { if (change.Object.getValue("range")) |range| { const start_pos = types.Position{ .line = range.Object.getValue("start").?.Object.getValue("line").?.Integer, .character = range.Object.getValue("start").?.Object.getValue("character").?.Integer }; const end_pos = types.Position{ .line = range.Object.getValue("end").?.Object.getValue("line").?.Integer, .character = range.Object.getValue("end").?.Object.getValue("character").?.Integer }; const change_text = change.Object.getValue("text").?.String; const start_index = try document.positionToIndex(start_pos); const end_index = try document.positionToIndex(end_pos); const old_len = document.text.len; const new_len = old_len + change_text.len; if (new_len > document.mem.len) { // We need to reallocate memory. // We reallocate twice the current filesize or the new length, if it's more than that // so that we can reduce the amount of realloc calls. // We can tune this to find a better size if needed. const realloc_len = std.math.max(2 * old_len, new_len); document.mem = try self.allocator.realloc(document.mem, realloc_len); } // The first part of the string, [0 .. start_index] need not be changed. // We then copy the last part of the string, [end_index ..] to its // new position, [start_index + change_len .. ] std.mem.copy(u8, document.mem[start_index + change_text.len..][0 .. old_len - end_index], document.mem[end_index .. old_len]); // Finally, we copy the changes over. std.mem.copy(u8, document.mem[start_index..][0 .. change_text.len], change_text); // Reset the text substring. document.text = document.mem[0 .. new_len]; } else { const change_text = change.Object.getValue("text").?.String; const old_len = document.text.len; if (change_text.len > document.mem.len) { // Like above. const realloc_len = std.math.max(2 * old_len, change_text.len); document.mem = try self.allocator.realloc(document.mem, realloc_len); } std.mem.copy(u8, document.mem[0 .. change_text.len], change_text); document.text = document.mem[0 .. change_text.len]; } } try self.checkSanity(handle); } fn uriFromImportStr(store: *DocumentStore, handle: Handle, import_str: []const u8) !?[]const u8 { return if (std.mem.eql(u8, import_str, "std")) if (store.std_uri) |std_root_uri| try std.mem.dupe(store.allocator, u8, std_root_uri) else { std.debug.warn("Cannot resolve std library import, path is null.\n", .{}); return null; } else b: { // Find relative uri const path = try URI.parse(store.allocator, handle.uri()); defer store.allocator.free(path); const dir_path = std.fs.path.dirname(path) orelse ""; const import_path = try std.fs.path.resolve(store.allocator, &[_][]const u8 { dir_path, import_str }); defer store.allocator.free(import_path); break :b (try URI.fromPath(store.allocator, import_path)); }; } pub const AnalysisContext = struct { store: *DocumentStore, handle: *Handle, // This arena is used for temporary allocations while analyzing, // not for the tree allocations. arena: *std.heap.ArenaAllocator, tree: *std.zig.ast.Tree, scope_nodes: []*std.zig.ast.Node, pub fn onImport(self: *AnalysisContext, import_str: []const u8) !?*std.zig.ast.Node { const allocator = self.store.allocator; const final_uri = (try uriFromImportStr(self.store, self.handle.*, import_str)) orelse return null; std.debug.warn("Import final URI: {}\n", .{final_uri}); var consumed_final_uri = false; defer if (!consumed_final_uri) allocator.free(final_uri); // Check if we already imported this. for (self.handle.import_uris.items) |uri| { // If we did, set our new handle and return the parsed tree root node. if (std.mem.eql(u8, uri, final_uri)) { self.handle = self.store.getHandle(final_uri) orelse return null; self.tree.deinit(); self.tree = try self.handle.tree(allocator); return &self.tree.root_node.base; } } // New import. // Check if the import is already opened by others. if (self.store.getHandle(final_uri)) |new_handle| { // If it is, increment the count, set our new handle and return the parsed tree root node. new_handle.count += 1; self.handle = new_handle; self.tree.deinit(); self.tree = try self.handle.tree(allocator); return &self.tree.root_node.base; } // New document, read the file then call into openDocument. const file_path = try URI.parse(allocator, final_uri); defer allocator.free(file_path); var file = std.fs.cwd().openFile(file_path, .{}) catch { std.debug.warn("Cannot open import file {}\n", .{file_path}); return null; }; defer file.close(); const size = std.math.cast(usize, try file.getEndPos()) catch std.math.maxInt(usize); { const file_contents = try allocator.alloc(u8, size); errdefer allocator.free(file_contents); file.inStream().readNoEof(file_contents) catch { std.debug.warn("Could not read from file {}\n", .{file_path}); return null; }; // Add to import table of current handle. try self.handle.import_uris.append(final_uri); consumed_final_uri = true; // Swap handles and get new tree. // This takes ownership of the passed uri and text. const duped_final_uri = try std.mem.dupe(allocator, u8, final_uri); errdefer allocator.free(duped_final_uri); self.handle = try newDocument(self.store, duped_final_uri, file_contents); } // Free old tree, add new one if it exists. // If we return null, no one should access the tree. self.tree.deinit(); self.tree = try self.handle.tree(allocator); return &self.tree.root_node.base; } pub fn deinit(self: *AnalysisContext) void { self.tree.deinit(); } }; pub fn analysisContext(self: *DocumentStore, handle: *Handle, arena: *std.heap.ArenaAllocator, position: types.Position) !AnalysisContext { const tree = try handle.tree(self.allocator); return AnalysisContext{ .store = self, .handle = handle, .arena = arena, .tree = tree, .scope_nodes = try analysis.declsFromIndex(&arena.allocator, tree, try handle.document.positionToIndex(position)) }; } pub fn deinit(self: *DocumentStore) void { var entry_iterator = self.handles.iterator(); while (entry_iterator.next()) |entry| { self.allocator.free(entry.value.document.mem); for (entry.value.import_uris.items) |uri| { self.allocator.free(uri); } entry.value.import_uris.deinit(); self.allocator.free(entry.key); } self.handles.deinit(); if (self.std_uri) |uri| { self.allocator.free(uri); } }
src/document_store.zig
const std = @import("std"); const Image = @import("image.zig").Image; const Allocator = std.mem.Allocator; pub const PngError = error { InvalidHeader, InvalidFilter, UnsupportedFormat }; const ChunkStream = std.io.FixedBufferStream([]u8); // PNG files are made of chunks which have this structure: const Chunk = struct { length: u32, type: []const u8, data: []const u8, stream: ChunkStream, crc: u32, allocator: Allocator, pub fn deinit(self: *const Chunk) void { self.allocator.free(self.type); self.allocator.free(self.data); } // fancy Zig reflection for basically loading the chunk into a struct // for the experienced: this method is necessary instead of a simple @bitCast because of endianess, as // PNG uses big-endian. pub fn toStruct(self: *Chunk, comptime T: type) T { var result: T = undefined; var reader = self.stream.reader(); inline for (@typeInfo(T).Struct.fields) |field| { const fieldInfo = @typeInfo(field.field_type); switch (fieldInfo) { .Int => { const f = reader.readIntBig(field.field_type) catch unreachable; @field(result, field.name) = f; }, .Enum => |e| { const id = reader.readIntBig(e.tag_type) catch unreachable; @field(result, field.name) = @intToEnum(field.field_type, id); }, else => unreachable } } return result; } }; const ColorType = enum(u8) { Greyscale = 0, Truecolor = 2, IndexedColor = 3, GreyscaleAlpha = 4, TruecolorAlpha = 6 }; const CompressionMethod = enum(u8) { Deflate = 0, }; // Struct for the IHDR chunk, which contains most of metadata about the image. const IHDR = struct { width: u32, height: u32, bitDepth: u8, colorType: ColorType, compressionMethod: CompressionMethod, filterMethod: u8, interlaceMethod: u8 }; fn filterNone(_: []const u8, _: []u8, _: u32, _: usize, _: u8) callconv(.Inline) void { // line is already pre-filled with original data, so nothing to do } fn filterSub(_: []const u8, line: []u8, _: u32, _: usize, bytes: u8) callconv(.Inline) void { var pos: usize = bytes; while (pos < line.len) : (pos += 1) { line[pos] = line[pos] +% line[pos-bytes]; } } fn filterUp(image: []const u8, line: []u8, y: u32, start: usize, _: u8) callconv(.Inline) void { const width = line.len; if (y != 0) { var pos: usize = 0; while (pos < line.len) : (pos += 1) { line[pos] = line[pos] +% image[start+pos-width]; } } } fn filterAverage(image: []const u8, line: []u8, y: u32, start: usize, bytes: u8) callconv(.Inline) void { const width = line.len; var pos: usize = 0; while (pos < line.len) : (pos += 1) { var val: u9 = if (pos >= bytes) line[pos-bytes] else 0; if (y > 0) { val += image[pos+start-width]; // val = a + b } line[pos] = line[pos] +% @truncate(u8, val / 2); } } fn filterPaeth(image: []const u8, line: []u8, y: u32, start: usize, bytes: u8) callconv(.Inline) void { const width = line.len; var pos: usize = 0; while (pos < line.len) : (pos += 1) { const a: isize = if (pos >= bytes) line[pos-bytes] else 0; const b: isize = if (y > 0) image[pos+start-width] else 0; const c: isize = if (pos >= bytes and y > 0) image[pos+start-width-bytes] else 0; const p: isize = a + b - c; // the minimum value of p is -255, minus the maximum value of a/b/c, the minimum result is -510, so using unreachable is safe const pa = std.math.absInt(p - a) catch unreachable; const pb = std.math.absInt(p - b) catch unreachable; const pc = std.math.absInt(p - c) catch unreachable; if (pa <= pb and pa <= pc) { line[pos] = line[pos] +% @truncate(u8, @bitCast(usize, a)); } else if (pb <= pc) { line[pos] = line[pos] +% @truncate(u8, @bitCast(usize, b)); } else { line[pos] = line[pos] +% @truncate(u8, @bitCast(usize, c)); } } } fn readChunk(allocator: Allocator, reader: anytype) !Chunk { const length = try reader.readIntBig(u32); var chunkType = try allocator.alloc(u8, 4); _ = try reader.readAll(chunkType); var data = try allocator.alloc(u8, length); _ = try reader.readAll(data); const crc = try reader.readIntBig(u32); var stream = ChunkStream { .buffer = data, .pos = 0 }; return Chunk { .length = length, .type = chunkType, .data = data, .stream = stream, .crc = crc, .allocator = allocator }; } pub fn read(allocator: Allocator, unbufferedReader: anytype) !Image { var bufferedReader = std.io.BufferedReader(16*1024, @TypeOf(unbufferedReader)) { .unbuffered_reader = unbufferedReader }; const reader = bufferedReader.reader(); var signature = reader.readBytesNoEof(8) catch return error.UnsupportedFormat; if (!std.mem.eql(u8, signature[0..], "\x89PNG\r\n\x1A\n")) { return error.UnsupportedFormat; } var ihdrChunk = try readChunk(allocator, reader); defer ihdrChunk.deinit(); if (!std.mem.eql(u8, ihdrChunk.type, "IHDR")) { return error.InvalidHeader; // first chunk must ALWAYS be IHDR } const ihdr = ihdrChunk.toStruct(IHDR); if (ihdr.filterMethod != 0) { // there's only one filter method declared in the PNG specification // the error falls under InvalidHeader because InvalidFilter is for // the per-scanline filter type. return error.InvalidHeader; } var idatData = try allocator.alloc(u8, 0); defer allocator.free(idatData); while (true) { const chunk = try readChunk(allocator, reader); defer chunk.deinit(); if (std.mem.eql(u8, chunk.type, "IEND")) { break; } else if (std.mem.eql(u8, chunk.type, "IDAT")) { // image data const pos = idatData.len; // in PNG files, there can be multiple IDAT chunks, and their data must all be concatenated. idatData = try allocator.realloc(idatData, idatData.len + chunk.data.len); std.mem.copy(u8, idatData[pos..], chunk.data); } } // the following lines create a zlib stream over our concatenated data from IDAT chunks. var idatStream = std.io.fixedBufferStream(idatData); var zlibStream = try std.compress.zlib.zlibStream(allocator, idatStream.reader()); defer zlibStream.deinit(); var zlibReader = zlibStream.reader(); var idatBuffer = (std.io.BufferedReader(64*1024, @TypeOf(zlibReader)) { .unbuffered_reader = zlibReader }); const idatReader = idatBuffer.reader(); // allocate image data (TODO: support more than RGB) var bpp: u32 = 3; if (ihdr.colorType == .TruecolorAlpha) { bpp = 4; } const imageData = try allocator.alloc(u8, ihdr.width*ihdr.height*bpp); var y: u32 = 0; const Filter = fn(image: []const u8, line: []u8, y: u32, start: usize, bytes: u8) callconv(.Inline) void; const filters = [_]Filter {filterNone, filterSub, filterUp, filterAverage, filterPaeth}; if (ihdr.colorType == .Truecolor) { const bytesPerLine = ihdr.width * bpp; while (y < ihdr.height) { // in PNG files, each scanlines have a filter, it is used to have more efficient compression. const filterType = try idatReader.readByte(); const offset = y*bytesPerLine; var line = imageData[offset..offset+bytesPerLine]; _ = try idatReader.readAll(line); if (filterType >= filters.len) { return error.InvalidFilter; } inline for (filters) |filter, i| { if (filterType == i) { filter(imageData, line, y, offset, 3); } } y += 1; } return Image { .allocator = allocator, .data = imageData, .width = ihdr.width, .height = ihdr.height, .format = @import("image.zig").ImageFormat.RGB24 }; } else if (ihdr.colorType == .TruecolorAlpha and false) { const bytesPerLine = ihdr.width * bpp; var line = try allocator.alloc(u8, bytesPerLine); defer allocator.free(line); while (y < ihdr.height) { const filterType = try idatReader.readByte(); const offset = y*bytesPerLine; _ = try idatReader.readAll(line); if (filterType >= filters.len) { return error.InvalidFilter; } inline for (filters) |filter, i| { if (filterType == i) { filter(imageData, line, y, offset, 4); std.mem.copy(u8, imageData[offset..offset+bytesPerLine], line); } } y += 1; } return Image { .allocator = allocator, .data = imageData, .width = ihdr.width, .height = ihdr.height, .format = @import("image.zig").ImageFormat.RGBA32 }; } else { std.log.scoped(.didot).err("Unsupported PNG format: {}", .{ihdr.colorType}); return PngError.UnsupportedFormat; } }
didot-image/png.zig
const std = @import("std"); pub const pkgs = struct { pub const requestz = std.build.Pkg{ .name = "requestz", .path = .{ .path = ".gyro\\requestz-ducdetronquito-0.1.1-68845cbcc0c07d54a8cd287ad333ba84\\pkg\\src\\main.zig" }, .dependencies = &[_]std.build.Pkg{ std.build.Pkg{ .name = "http", .path = .{ .path = ".gyro\\http-ducdetronquito-0.1.3-02dd386aa7452ba02887b98078627854\\pkg\\src\\main.zig" }, }, std.build.Pkg{ .name = "h11", .path = .{ .path = ".gyro\\h11-ducdetronquito-0.1.1-5d7aa65ac782877d98cc6311a77ca7a8\\pkg\\src\\main.zig" }, .dependencies = &[_]std.build.Pkg{ std.build.Pkg{ .name = "http", .path = .{ .path = ".gyro\\http-ducdetronquito-0.1.3-02dd386aa7452ba02887b98078627854\\pkg\\src\\main.zig" }, }, }, }, std.build.Pkg{ .name = "iguanaTLS", .path = .{ .path = ".gyro\\iguanaTLS-alexnask-0d39a361639ad5469f8e4dcdaea35446bbe54b48\\pkg\\src\\main.zig" }, }, std.build.Pkg{ .name = "network", .path = .{ .path = ".gyro\\zig-network-MasterQ32-b9c91769d8ebd626c8e45b2abb05cbc28ccc50da\\pkg\\network.zig" }, }, }, }; pub const http = std.build.Pkg{ .name = "http", .path = .{ .path = ".gyro\\http-ducdetronquito-0.1.3-02dd386aa7452ba02887b98078627854\\pkg\\src\\main.zig" }, }; pub fn addAllTo(artifact: *std.build.LibExeObjStep) void { @setEvalBranchQuota(1_000_000); inline for (std.meta.declarations(pkgs)) |decl| { if (decl.is_pub and decl.data == .Var) { artifact.addPackage(@field(pkgs, decl.name)); } } } }; pub const exports = struct { pub const ddnsv6 = std.build.Pkg{ .name = "ddnsv6", .path = .{ .path = "src/main.zig" }, .dependencies = &.{ pkgs.requestz, pkgs.http, }, }; }; pub const base_dirs = struct { pub const requestz = ".gyro\\requestz-ducdetronquito-0.1.1-68845cbcc0c07d54a8cd287ad333ba84\\pkg"; pub const http = ".gyro\\http-ducdetronquito-0.1.3-02dd386aa7452ba02887b98078627854\\pkg"; };
deps.zig
const hc256 = @import("hc256"); const Hc256 = hc256.Hc256; const std = @import("std"); const testing = std.testing; test "Vector 1" { const key = [32]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; const iv = [32]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; var data = [32]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; const expected = [32]u8{ 0x5b, 0x07, 0x89, 0x85, 0xd8, 0xf6, 0xf3, 0x0d, 0x42, 0xc5, 0xc0, 0x2f, 0xa6, 0xb6, 0x79, 0x51, 0x53, 0xf0, 0x65, 0x34, 0x80, 0x1f, 0x89, 0xf2, 0x4e, 0x74, 0x24, 0x8b, 0x72, 0x0b, 0x48, 0x18, }; var cipher = Hc256.init(key, iv, true); cipher.applyStream(data[0..]); var i: usize = 0; while (i < 32) : (i += 1) try testing.expectEqual(expected[i], data[i]); } test "Vector 2" { const key = [32]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; const iv = [32]u8{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; var data = [32]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; const expected = [32]u8{ 0xaf, 0xe2, 0xa2, 0xbf, 0x4f, 0x17, 0xce, 0xe9, 0xfe, 0xc2, 0x05, 0x8b, 0xd1, 0xb1, 0x8b, 0xb1, 0x5f, 0xc0, 0x42, 0xee, 0x71, 0x2b, 0x31, 0x01, 0xdd, 0x50, 0x1f, 0xc6, 0x0b, 0x08, 0x2a, 0x50, }; var cipher = Hc256.init(key, iv, true); cipher.applyStream(data[0..13]); cipher.applyStream(data[13..]); var i: usize = 0; while (i < 14) : (i += 1) try testing.expectEqual(expected[i], data[i]); } test "Vector 3" { const key = [32]u8{ 0x55, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; const iv = [32]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; var data = [32]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; const expected = [32]u8{ 0x1c, 0x40, 0x4a, 0xfe, 0x4f, 0xe2, 0x5f, 0xed, 0x95, 0x8f, 0x9a, 0xd1, 0xae, 0x36, 0xc0, 0x6f, 0x88, 0xa6, 0x5a, 0x3c, 0xc0, 0xab, 0xe2, 0x23, 0xae, 0xb3, 0x90, 0x2f, 0x42, 0x0e, 0xd3, 0xa8, }; var cipher = Hc256.init(key, iv, false); cipher.applyStream(data[0..]); var i: usize = 0; while (i < 32) : (i += 1) try testing.expectEqual(expected[i], data[i]); }
tests/test-vectors.zig
const std = @import("std"); const log = std.log; const DFS = @import("utils.zig").DepthFirstIterator; const ast = @import("ast.zig"); const Node = ast.Node; const NodeKind = ast.NodeKind; pub const HTMLGenerator = struct { allocator: *std.mem.Allocator, start_node: *Node, label_node_map: std.StringHashMap(*Node.NodeData), pub const Error = error { ReferenceLabelNotFound, FormatBufferTooSmall, }; /// label_node_map is taken from the parser, but HTMLGenerator doesn't take ownership pub fn init( allocator: *std.mem.Allocator, start_node: *Node, label_node_map: std.StringHashMap(*Node.NodeData) ) HTMLGenerator { return HTMLGenerator{ .allocator = allocator, .start_node = start_node, .label_node_map = label_node_map, }; } inline fn report_error(comptime err_msg: []const u8, args: anytype) void { log.err(err_msg, args); } /// If out_stream is a bufferedWriter the caller is expected to call .flush() /// since the other out_streams don't have that method. // need to pass the writertype if we want an explicit error set by merging them pub fn write( self: *HTMLGenerator, comptime WriterType: type, out_stream: anytype ) (Error || WriterType.Error)!void { var dfs = DFS(Node, true).init(self.start_node); try out_stream.writeAll( \\<html> \\<head> \\<meta charset="utf-8"> \\<meta name="viewport" content="width=device-width, initial-scale=1.0"> \\<script id="MathJax-script" async src="vendor/mathjax-3.1.2/tex-svg-full.js"></script> \\<link type="text/css" rel="stylesheet" href="html/style.css"> \\</head> \\<body> \\<div class="content-wrapper"> ); var in_compact_list = false; while (dfs.next()) |node_info| { // bug in zig compiler: if a switch prong (without {}) doesn't handle an error // the start of the switch is reported as ignoring the error // std.debug.print("Node (end: {}): {}\n", .{ node_info.is_end, node_info.data.data }); switch (node_info.data.data) { .Document => continue, .Undefined, .Import => unreachable, // blocks like thematic break should never get both a start and end NodeInfo // since they can't contain other blocks .ThematicBreak => try out_stream.writeAll("<hr/>\n"), .Heading => |heading| { var hbuf: [4]u8 = undefined; _ = std.fmt.bufPrint(&hbuf, "h{}>\n", .{ heading.level }) catch return Error.FormatBufferTooSmall; if (node_info.is_end) { try out_stream.writeAll("</"); } else { try out_stream.writeByte('<'); } try out_stream.writeAll(&hbuf); }, .UnorderedList => |list| { if (!node_info.is_end) { in_compact_list = if (list.blank_lines > 0) false else true; try out_stream.writeAll("<ul>\n"); } else { try out_stream.writeAll("</ul>\n"); in_compact_list = HTMLGenerator.get_parents_list_compact_status(node_info.data); } }, .OrderedList => |list| { if (!node_info.is_end) { in_compact_list = if (list.blank_lines > 0) false else true; if (list.start_num == 1 and list.ol_type == '1') { try out_stream.writeAll("<ol>\n"); } else { var numbuf: [4]u8 = undefined; var numslice = std.fmt.bufPrint(&numbuf, "{}", .{ list.start_num }) catch return Error.FormatBufferTooSmall; try out_stream.writeAll("<ol start=\""); try out_stream.writeAll(numslice); try out_stream.writeAll("\" type=\""); try out_stream.writeByte(list.ol_type); try out_stream.writeAll("\">\n"); } } else { try out_stream.writeAll("</ol>\n"); in_compact_list = HTMLGenerator.get_parents_list_compact_status(node_info.data); } }, .UnorderedListItem, .OrderedListItem => { if (!node_info.is_end) { try out_stream.writeAll("<li>\n"); } else { try out_stream.writeAll("</li>\n"); } }, .FencedCode => |code| { if (!node_info.is_end) continue; // no \n since the whitespace is printed verbatim in a <pre> env try out_stream.writeAll("<pre><code>"); try out_stream.writeAll(code.code); try out_stream.writeAll("</code></pre>\n"); if (code.stdout) |out| { try out_stream.writeAll("Output:"); try out_stream.writeAll("<pre>\n"); try out_stream.writeAll(out); try out_stream.writeAll("</pre>\n"); } if (code.stderr) |err| { try out_stream.writeAll("Warnings:"); try out_stream.writeAll("<pre>\n"); try out_stream.writeAll(err); try out_stream.writeAll("</pre>\n"); } }, .MathInline => |math| { // \(...\) are the default MathJax inline delimiters instead of $...$ try out_stream.writeAll("\\("); try out_stream.writeAll(math.text); try out_stream.writeAll("\\)"); }, .MathMultiline => |math| { try out_stream.writeAll("$$"); try out_stream.writeAll(math.text); try out_stream.writeAll("$$\n"); }, .BlockQuote => { if (!node_info.is_end) { try out_stream.writeAll("<blockquote>\n"); } else { try out_stream.writeAll("</blockquote>\n"); } }, .Paragraph => { if (!in_compact_list) { if (!node_info.is_end) { try out_stream.writeAll("<p>\n"); } else { try out_stream.writeAll("</p>\n"); } } }, .BibEntry => { if (!node_info.is_end) { try out_stream.writeAll("<p>\n"); } else { try out_stream.writeAll("</p>\n"); } }, .Emphasis => { if (!node_info.is_end) { try out_stream.writeAll("<em>"); } else { try out_stream.writeAll("</em>"); } }, .StrongEmphasis => { if (!node_info.is_end) { try out_stream.writeAll("<strong>"); } else { try out_stream.writeAll("</strong>"); } }, .Strikethrough => { if (!node_info.is_end) { try out_stream.writeAll("<strike>"); } else { try out_stream.writeAll("</strike>"); } }, .Superscript => { if (!node_info.is_end) { try out_stream.writeAll("<sup>"); } else { try out_stream.writeAll("</sup>"); } }, .Subscript => { if (!node_info.is_end) { try out_stream.writeAll("<sub>"); } else { try out_stream.writeAll("</sub>"); } }, .SmallCaps => { if (!node_info.is_end) { try out_stream.writeAll("<span style=\"font-variant: small-caps;\">"); } else { try out_stream.writeAll("</span>"); } }, .Underline => { if (!node_info.is_end) { try out_stream.writeAll("<u>"); } else { try out_stream.writeAll("</u>"); } }, .CodeSpan => |code| { if (code.stdout) |out| { try out_stream.writeAll(out); } else { try out_stream.writeAll("<code>"); try out_stream.writeAll(code.code); try out_stream.writeAll("</code>"); } }, .Link => |link| { // TODO move this into a post pass after the frontend? var link_url: []const u8 = undefined; var link_title: ?[]const u8 = undefined; if (link.url) |url| { link_url = url; link_title = link.title; } else { // look up reference by label; must have one if url is null // returns optional ptr to entry const maybe_ref = self.label_node_map.get(link.label.?); if (maybe_ref) |ref| { link_url = ref.LinkRef.url.?; link_title = ref.LinkRef.title; } else { HTMLGenerator.report_error( "No reference definition could be found for label '{s}'!\n", .{ link.label.? }); return Error.ReferenceLabelNotFound; } } if (!node_info.is_end) { try out_stream.writeAll("<a href=\""); try out_stream.writeAll(link_url); try out_stream.writeByte('"'); if (link_title) |title| { try out_stream.writeAll("title=\""); try out_stream.writeAll(title); try out_stream.writeByte('"'); } try out_stream.writeByte('>'); } else { try out_stream.writeAll("</a>"); } }, .Image => |img| { var img_url: []const u8 = undefined; var img_title: ?[]const u8 = undefined; if (img.url) |url| { img_url = url; img_title = img.title; } else { // look up reference by label; must have one if url is null // returns optional ptr to entry const maybe_ref = self.label_node_map.get(img.label.?); if (maybe_ref) |ref| { img_url = ref.LinkRef.url.?; img_title = ref.LinkRef.title; } else { HTMLGenerator.report_error( "No reference definition could be found for label '{s}'!\n", .{ img.label.? }); return Error.ReferenceLabelNotFound; } } try out_stream.writeAll("<img src=\""); try out_stream.writeAll(img_url); try out_stream.writeAll("\" alt=\""); try out_stream.writeAll(img.alt); try out_stream.writeAll("\""); if (img_title) |title| { try out_stream.writeAll(" title=\""); try out_stream.writeAll(title); try out_stream.writeAll("\""); } try out_stream.writeAll(" />"); }, .BuiltinCall => |call| { if (!node_info.is_end) continue; switch (call.builtin_type) { // TODO fix for nodes like e.g. FencedCode, Heading .label => { try out_stream.writeAll("<span id=\""); try out_stream.writeAll(call.result.?.label); try out_stream.writeAll("\"></span>"); }, .ref => { const maybe_node = self.label_node_map.get(call.result.?.ref); if (maybe_node) |node| { try out_stream.writeAll("<a href=\"#"); try out_stream.writeAll(call.result.?.ref); try out_stream.writeAll("\">"); try out_stream.writeAll(@tagName(node.*)); try out_stream.writeAll("</a>"); } else { HTMLGenerator.report_error( "No corresponding label could be found for ref '{s}'!\n", .{ call.result.?.ref }); return Error.ReferenceLabelNotFound; } }, else => {}, } }, .HardLineBreak => try out_stream.writeAll("<br/>\n"), .SoftLineBreak => try out_stream.writeByte('\n'), .Text => |text| { if (node_info.data.first_child) |fc| { log.debug("Text node has child: {}\n", .{ fc.data }); } try out_stream.writeAll(text.text); }, else => continue, } } try out_stream.writeAll("</div></body>\n</html>"); } /// assumes current_list.parent is not null fn get_parents_list_compact_status(current_list: *Node) bool { // restore parent list's compact status if there is one return switch (current_list.parent.?.data) { NodeKind.OrderedListItem => blk: { // first parent is item, second is list itself break :blk current_list.parent.?.parent.?.data.OrderedList.blank_lines == 0; }, NodeKind.UnorderedListItem => blk: { // first parent is item, second is list itself break :blk current_list.parent.?.parent.?.data.UnorderedList.blank_lines == 0; }, // return true so paragraphs get rendered normally everywhere else else => false, }; } };
src/html.zig
const std = @import("std"); 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); } 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 md5 = std.crypto.Md5.init(); var pending = std.ArrayList(struct { letter: u8, index: usize, }).init(allocator); defer pending.deinit(); var answers: [100]usize = undefined; var found: usize = 0; var i: u64 = 1; while (found < 80) : (i += 1) { var buflen: usize = 0; var buf: [100]u8 = undefined; var input = std.fmt.bufPrint(&buf, "jlmsuwbz{}", .{i}) catch unreachable; var repeat: usize = 0; while (repeat <= 2016) : (repeat += 1) { var hash: [std.crypto.Md5.digest_length]u8 = undefined; std.crypto.Md5.hash(input, &hash); buflen = 0; for (hash) |h| { _ = std.fmt.bufPrint(buf[buflen .. buflen + 2], "{x:0>2}", .{h}) catch unreachable; buflen += 2; } input = buf[0..buflen]; } var is_first_tripplet = true; var seq = [5]u8{ 0, 0, 0, 0, 0 }; for (buf[0..buflen]) |c| { assert(c != 0); seq[0] = seq[1]; seq[1] = seq[2]; seq[2] = seq[3]; seq[3] = seq[4]; seq[4] = c; const interresting = seq[2] == c and seq[3] == c and seq[4] == c; const valid = interresting and seq[0] == c and seq[1] == c; if (valid) { for (pending.items) |*it, j| { if (it.letter == c and it.index + 1000 >= i and it.index != i) { answers[found] = it.index; found += 1; try stdout.print("found key at i='{}' (pair at {}, repeated char='{c}')\n", .{ it.index, i, c }); it.letter = 0; // used! } } } if (interresting and is_first_tripplet) { var dup = false; for (pending.items) |it| { dup = dup or (it.letter == c and it.index == i); } assert(!dup); is_first_tripplet = false; if (!dup) try pending.append(.{ .letter = c, .index = i }); } } // enleve les périmés... { var j: usize = 0; var len = pending.len; while (j < len) { if (pending.at(j).index + 1000 < i) { _ = pending.swapRemove(j); len -= 1; } else { j += 1; } } } } std.sort.sort(usize, answers[0..found], std.sort.asc(usize)); try stdout.print("key 64 at i='{}'\n", .{answers[63]}); }
2016/day14.zig
pub const DEDUP_CHUNKLIB_MAX_CHUNKS_ENUM = @as(u32, 1024); //-------------------------------------------------------------------------------- // Section: Types (24) //-------------------------------------------------------------------------------- const CLSID_DedupBackupSupport_Value = @import("../zig.zig").Guid.initString("73d6b2ad-2984-4715-b2e3-924c149744dd"); pub const CLSID_DedupBackupSupport = &CLSID_DedupBackupSupport_Value; pub const DEDUP_CONTAINER_EXTENT = extern struct { ContainerIndex: u32, StartOffset: i64, Length: i64, }; pub const DDP_FILE_EXTENT = extern struct { Length: i64, Offset: i64, }; pub const DEDUP_BACKUP_SUPPORT_PARAM_TYPE = enum(i32) { UNOPTIMIZED = 1, OPTIMIZED = 2, }; pub const DEDUP_RECONSTRUCT_UNOPTIMIZED = DEDUP_BACKUP_SUPPORT_PARAM_TYPE.UNOPTIMIZED; pub const DEDUP_RECONSTRUCT_OPTIMIZED = DEDUP_BACKUP_SUPPORT_PARAM_TYPE.OPTIMIZED; // TODO: this type is limited to platform 'windowsServer2012' const IID_IDedupReadFileCallback_Value = @import("../zig.zig").Guid.initString("7bacc67a-2f1d-42d0-897e-6ff62dd533bb"); pub const IID_IDedupReadFileCallback = &IID_IDedupReadFileCallback_Value; pub const IDedupReadFileCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, ReadBackupFile: fn( self: *const IDedupReadFileCallback, FileFullPath: ?BSTR, FileOffset: i64, SizeToRead: u32, FileBuffer: [*:0]u8, ReturnedSize: ?*u32, Flags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OrderContainersRestore: fn( self: *const IDedupReadFileCallback, NumberOfContainers: u32, ContainerPaths: [*]?BSTR, ReadPlanEntries: ?*u32, ReadPlan: [*]?*DEDUP_CONTAINER_EXTENT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PreviewContainerRead: fn( self: *const IDedupReadFileCallback, FileFullPath: ?BSTR, NumberOfReads: u32, ReadOffsets: [*]DDP_FILE_EXTENT, ) 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 IDedupReadFileCallback_ReadBackupFile(self: *const T, FileFullPath: ?BSTR, FileOffset: i64, SizeToRead: u32, FileBuffer: [*:0]u8, ReturnedSize: ?*u32, Flags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupReadFileCallback.VTable, self.vtable).ReadBackupFile(@ptrCast(*const IDedupReadFileCallback, self), FileFullPath, FileOffset, SizeToRead, FileBuffer, ReturnedSize, Flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDedupReadFileCallback_OrderContainersRestore(self: *const T, NumberOfContainers: u32, ContainerPaths: [*]?BSTR, ReadPlanEntries: ?*u32, ReadPlan: [*]?*DEDUP_CONTAINER_EXTENT) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupReadFileCallback.VTable, self.vtable).OrderContainersRestore(@ptrCast(*const IDedupReadFileCallback, self), NumberOfContainers, ContainerPaths, ReadPlanEntries, ReadPlan); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDedupReadFileCallback_PreviewContainerRead(self: *const T, FileFullPath: ?BSTR, NumberOfReads: u32, ReadOffsets: [*]DDP_FILE_EXTENT) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupReadFileCallback.VTable, self.vtable).PreviewContainerRead(@ptrCast(*const IDedupReadFileCallback, self), FileFullPath, NumberOfReads, ReadOffsets); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_IDedupBackupSupport_Value = @import("../zig.zig").Guid.initString("c719d963-2b2d-415e-acf7-7eb7ca596ff4"); pub const IID_IDedupBackupSupport = &IID_IDedupBackupSupport_Value; pub const IDedupBackupSupport = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, RestoreFiles: fn( self: *const IDedupBackupSupport, NumberOfFiles: u32, FileFullPaths: [*]?BSTR, Store: ?*IDedupReadFileCallback, Flags: u32, FileResults: [*]HRESULT, ) 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 IDedupBackupSupport_RestoreFiles(self: *const T, NumberOfFiles: u32, FileFullPaths: [*]?BSTR, Store: ?*IDedupReadFileCallback, Flags: u32, FileResults: [*]HRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupBackupSupport.VTable, self.vtable).RestoreFiles(@ptrCast(*const IDedupBackupSupport, self), NumberOfFiles, FileFullPaths, Store, Flags, FileResults); } };} pub usingnamespace MethodMixin(@This()); }; pub const DEDUP_SET_PARAM_TYPE = enum(i32) { MinChunkSizeBytes = 1, MaxChunkSizeBytes = 2, AvgChunkSizeBytes = 3, InvariantChunking = 4, DisableStrongHashComputation = 5, }; pub const DEDUP_PT_MinChunkSizeBytes = DEDUP_SET_PARAM_TYPE.MinChunkSizeBytes; pub const DEDUP_PT_MaxChunkSizeBytes = DEDUP_SET_PARAM_TYPE.MaxChunkSizeBytes; pub const DEDUP_PT_AvgChunkSizeBytes = DEDUP_SET_PARAM_TYPE.AvgChunkSizeBytes; pub const DEDUP_PT_InvariantChunking = DEDUP_SET_PARAM_TYPE.InvariantChunking; pub const DEDUP_PT_DisableStrongHashComputation = DEDUP_SET_PARAM_TYPE.DisableStrongHashComputation; pub const DEDUP_CHUNK_INFO_HASH32 = extern struct { ChunkFlags: u32, ChunkOffsetInStream: u64, ChunkSize: u64, HashVal: [32]u8, }; const IID_IDedupChunkLibrary_Value = @import("../zig.zig").Guid.initString("bb5144d7-2720-4dcc-8777-78597416ec23"); pub const IID_IDedupChunkLibrary = &IID_IDedupChunkLibrary_Value; pub const IDedupChunkLibrary = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, InitializeForPushBuffers: fn( self: *const IDedupChunkLibrary, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Uninitialize: fn( self: *const IDedupChunkLibrary, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetParameter: fn( self: *const IDedupChunkLibrary, dwParamType: u32, vParamValue: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, StartChunking: fn( self: *const IDedupChunkLibrary, iidIteratorInterfaceID: Guid, ppChunksEnum: ?*?*IUnknown, ) 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 IDedupChunkLibrary_InitializeForPushBuffers(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupChunkLibrary.VTable, self.vtable).InitializeForPushBuffers(@ptrCast(*const IDedupChunkLibrary, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDedupChunkLibrary_Uninitialize(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupChunkLibrary.VTable, self.vtable).Uninitialize(@ptrCast(*const IDedupChunkLibrary, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDedupChunkLibrary_SetParameter(self: *const T, dwParamType: u32, vParamValue: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupChunkLibrary.VTable, self.vtable).SetParameter(@ptrCast(*const IDedupChunkLibrary, self), dwParamType, vParamValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDedupChunkLibrary_StartChunking(self: *const T, iidIteratorInterfaceID: Guid, ppChunksEnum: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupChunkLibrary.VTable, self.vtable).StartChunking(@ptrCast(*const IDedupChunkLibrary, self), iidIteratorInterfaceID, ppChunksEnum); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDedupIterateChunksHash32_Value = @import("../zig.zig").Guid.initString("90b584d3-72aa-400f-9767-cad866a5a2d8"); pub const IID_IDedupIterateChunksHash32 = &IID_IDedupIterateChunksHash32_Value; pub const IDedupIterateChunksHash32 = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, PushBuffer: fn( self: *const IDedupIterateChunksHash32, pBuffer: [*:0]u8, ulBufferLength: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Next: fn( self: *const IDedupIterateChunksHash32, ulMaxChunks: u32, pArrChunks: [*]DEDUP_CHUNK_INFO_HASH32, pulFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Drain: fn( self: *const IDedupIterateChunksHash32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IDedupIterateChunksHash32, ) 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 IDedupIterateChunksHash32_PushBuffer(self: *const T, pBuffer: [*:0]u8, ulBufferLength: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupIterateChunksHash32.VTable, self.vtable).PushBuffer(@ptrCast(*const IDedupIterateChunksHash32, self), pBuffer, ulBufferLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDedupIterateChunksHash32_Next(self: *const T, ulMaxChunks: u32, pArrChunks: [*]DEDUP_CHUNK_INFO_HASH32, pulFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupIterateChunksHash32.VTable, self.vtable).Next(@ptrCast(*const IDedupIterateChunksHash32, self), ulMaxChunks, pArrChunks, pulFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDedupIterateChunksHash32_Drain(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupIterateChunksHash32.VTable, self.vtable).Drain(@ptrCast(*const IDedupIterateChunksHash32, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDedupIterateChunksHash32_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupIterateChunksHash32.VTable, self.vtable).Reset(@ptrCast(*const IDedupIterateChunksHash32, self)); } };} pub usingnamespace MethodMixin(@This()); }; pub const DedupDataPortManagerOption = enum(i32) { None = 0, AutoStart = 1, SkipReconciliation = 2, }; pub const DedupDataPortManagerOption_None = DedupDataPortManagerOption.None; pub const DedupDataPortManagerOption_AutoStart = DedupDataPortManagerOption.AutoStart; pub const DedupDataPortManagerOption_SkipReconciliation = DedupDataPortManagerOption.SkipReconciliation; pub const DedupDataPortVolumeStatus = enum(i32) { Unknown = 0, NotEnabled = 1, NotAvailable = 2, Initializing = 3, Ready = 4, Maintenance = 5, Shutdown = 6, }; pub const DedupDataPortVolumeStatus_Unknown = DedupDataPortVolumeStatus.Unknown; pub const DedupDataPortVolumeStatus_NotEnabled = DedupDataPortVolumeStatus.NotEnabled; pub const DedupDataPortVolumeStatus_NotAvailable = DedupDataPortVolumeStatus.NotAvailable; pub const DedupDataPortVolumeStatus_Initializing = DedupDataPortVolumeStatus.Initializing; pub const DedupDataPortVolumeStatus_Ready = DedupDataPortVolumeStatus.Ready; pub const DedupDataPortVolumeStatus_Maintenance = DedupDataPortVolumeStatus.Maintenance; pub const DedupDataPortVolumeStatus_Shutdown = DedupDataPortVolumeStatus.Shutdown; pub const DedupDataPortRequestStatus = enum(i32) { Unknown = 0, Queued = 1, Processing = 2, Partial = 3, Complete = 4, Failed = 5, }; pub const DedupDataPortRequestStatus_Unknown = DedupDataPortRequestStatus.Unknown; pub const DedupDataPortRequestStatus_Queued = DedupDataPortRequestStatus.Queued; pub const DedupDataPortRequestStatus_Processing = DedupDataPortRequestStatus.Processing; pub const DedupDataPortRequestStatus_Partial = DedupDataPortRequestStatus.Partial; pub const DedupDataPortRequestStatus_Complete = DedupDataPortRequestStatus.Complete; pub const DedupDataPortRequestStatus_Failed = DedupDataPortRequestStatus.Failed; pub const DedupChunkFlags = enum(i32) { None = 0, Compressed = 1, }; pub const DedupChunkFlags_None = DedupChunkFlags.None; pub const DedupChunkFlags_Compressed = DedupChunkFlags.Compressed; pub const DedupHash = extern struct { Hash: [32]u8, }; pub const DedupChunk = extern struct { Hash: DedupHash, Flags: DedupChunkFlags, LogicalSize: u32, DataSize: u32, }; pub const DedupStreamEntry = extern struct { Hash: DedupHash, LogicalSize: u32, Offset: u64, }; pub const DedupStream = extern struct { Path: ?BSTR, Offset: u64, Length: u64, ChunkCount: u32, }; pub const DedupChunkingAlgorithm = enum(i32) { Unknonwn = 0, V1 = 1, }; pub const DedupChunkingAlgorithm_Unknonwn = DedupChunkingAlgorithm.Unknonwn; pub const DedupChunkingAlgorithm_V1 = DedupChunkingAlgorithm.V1; pub const DedupHashingAlgorithm = enum(i32) { Unknonwn = 0, V1 = 1, }; pub const DedupHashingAlgorithm_Unknonwn = DedupHashingAlgorithm.Unknonwn; pub const DedupHashingAlgorithm_V1 = DedupHashingAlgorithm.V1; pub const DedupCompressionAlgorithm = enum(i32) { Unknonwn = 0, Xpress = 1, }; pub const DedupCompressionAlgorithm_Unknonwn = DedupCompressionAlgorithm.Unknonwn; pub const DedupCompressionAlgorithm_Xpress = DedupCompressionAlgorithm.Xpress; const CLSID_DedupDataPort_Value = @import("../zig.zig").Guid.initString("8f107207-1829-48b2-a64b-e61f8e0d9acb"); pub const CLSID_DedupDataPort = &CLSID_DedupDataPort_Value; const IID_IDedupDataPort_Value = @import("../zig.zig").Guid.initString("7963d734-40a9-4ea3-bbf6-5a89d26f7ae8"); pub const IID_IDedupDataPort = &IID_IDedupDataPort_Value; pub const IDedupDataPort = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetStatus: fn( self: *const IDedupDataPort, pStatus: ?*DedupDataPortVolumeStatus, pDataHeadroomMb: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LookupChunks: fn( self: *const IDedupDataPort, Count: u32, pHashes: [*]DedupHash, pRequestId: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertChunks: fn( self: *const IDedupDataPort, ChunkCount: u32, pChunkMetadata: [*]DedupChunk, DataByteCount: u32, pChunkData: [*:0]u8, pRequestId: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertChunksWithStream: fn( self: *const IDedupDataPort, ChunkCount: u32, pChunkMetadata: [*]DedupChunk, DataByteCount: u32, pChunkDataStream: ?*IStream, pRequestId: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CommitStreams: fn( self: *const IDedupDataPort, StreamCount: u32, pStreams: [*]DedupStream, EntryCount: u32, pEntries: [*]DedupStreamEntry, pRequestId: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CommitStreamsWithStream: fn( self: *const IDedupDataPort, StreamCount: u32, pStreams: [*]DedupStream, EntryCount: u32, pEntriesStream: ?*IStream, pRequestId: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStreams: fn( self: *const IDedupDataPort, StreamCount: u32, pStreamPaths: [*]?BSTR, pRequestId: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStreamsResults: fn( self: *const IDedupDataPort, RequestId: Guid, MaxWaitMs: u32, StreamEntryIndex: u32, pStreamCount: ?*u32, ppStreams: [*]?*DedupStream, pEntryCount: ?*u32, ppEntries: [*]?*DedupStreamEntry, pStatus: ?*DedupDataPortRequestStatus, ppItemResults: [*]?*HRESULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetChunks: fn( self: *const IDedupDataPort, Count: u32, pHashes: [*]DedupHash, pRequestId: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetChunksResults: fn( self: *const IDedupDataPort, RequestId: Guid, MaxWaitMs: u32, ChunkIndex: u32, pChunkCount: ?*u32, ppChunkMetadata: [*]?*DedupChunk, pDataByteCount: ?*u32, ppChunkData: [*]?*u8, pStatus: ?*DedupDataPortRequestStatus, ppItemResults: [*]?*HRESULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRequestStatus: fn( self: *const IDedupDataPort, RequestId: Guid, pStatus: ?*DedupDataPortRequestStatus, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRequestResults: fn( self: *const IDedupDataPort, RequestId: Guid, MaxWaitMs: u32, pBatchResult: ?*HRESULT, pBatchCount: ?*u32, pStatus: ?*DedupDataPortRequestStatus, ppItemResults: [*]?*HRESULT, ) 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 IDedupDataPort_GetStatus(self: *const T, pStatus: ?*DedupDataPortVolumeStatus, pDataHeadroomMb: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupDataPort.VTable, self.vtable).GetStatus(@ptrCast(*const IDedupDataPort, self), pStatus, pDataHeadroomMb); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDedupDataPort_LookupChunks(self: *const T, Count: u32, pHashes: [*]DedupHash, pRequestId: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupDataPort.VTable, self.vtable).LookupChunks(@ptrCast(*const IDedupDataPort, self), Count, pHashes, pRequestId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDedupDataPort_InsertChunks(self: *const T, ChunkCount: u32, pChunkMetadata: [*]DedupChunk, DataByteCount: u32, pChunkData: [*:0]u8, pRequestId: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupDataPort.VTable, self.vtable).InsertChunks(@ptrCast(*const IDedupDataPort, self), ChunkCount, pChunkMetadata, DataByteCount, pChunkData, pRequestId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDedupDataPort_InsertChunksWithStream(self: *const T, ChunkCount: u32, pChunkMetadata: [*]DedupChunk, DataByteCount: u32, pChunkDataStream: ?*IStream, pRequestId: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupDataPort.VTable, self.vtable).InsertChunksWithStream(@ptrCast(*const IDedupDataPort, self), ChunkCount, pChunkMetadata, DataByteCount, pChunkDataStream, pRequestId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDedupDataPort_CommitStreams(self: *const T, StreamCount: u32, pStreams: [*]DedupStream, EntryCount: u32, pEntries: [*]DedupStreamEntry, pRequestId: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupDataPort.VTable, self.vtable).CommitStreams(@ptrCast(*const IDedupDataPort, self), StreamCount, pStreams, EntryCount, pEntries, pRequestId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDedupDataPort_CommitStreamsWithStream(self: *const T, StreamCount: u32, pStreams: [*]DedupStream, EntryCount: u32, pEntriesStream: ?*IStream, pRequestId: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupDataPort.VTable, self.vtable).CommitStreamsWithStream(@ptrCast(*const IDedupDataPort, self), StreamCount, pStreams, EntryCount, pEntriesStream, pRequestId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDedupDataPort_GetStreams(self: *const T, StreamCount: u32, pStreamPaths: [*]?BSTR, pRequestId: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupDataPort.VTable, self.vtable).GetStreams(@ptrCast(*const IDedupDataPort, self), StreamCount, pStreamPaths, pRequestId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDedupDataPort_GetStreamsResults(self: *const T, RequestId: Guid, MaxWaitMs: u32, StreamEntryIndex: u32, pStreamCount: ?*u32, ppStreams: [*]?*DedupStream, pEntryCount: ?*u32, ppEntries: [*]?*DedupStreamEntry, pStatus: ?*DedupDataPortRequestStatus, ppItemResults: [*]?*HRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupDataPort.VTable, self.vtable).GetStreamsResults(@ptrCast(*const IDedupDataPort, self), RequestId, MaxWaitMs, StreamEntryIndex, pStreamCount, ppStreams, pEntryCount, ppEntries, pStatus, ppItemResults); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDedupDataPort_GetChunks(self: *const T, Count: u32, pHashes: [*]DedupHash, pRequestId: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupDataPort.VTable, self.vtable).GetChunks(@ptrCast(*const IDedupDataPort, self), Count, pHashes, pRequestId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDedupDataPort_GetChunksResults(self: *const T, RequestId: Guid, MaxWaitMs: u32, ChunkIndex: u32, pChunkCount: ?*u32, ppChunkMetadata: [*]?*DedupChunk, pDataByteCount: ?*u32, ppChunkData: [*]?*u8, pStatus: ?*DedupDataPortRequestStatus, ppItemResults: [*]?*HRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupDataPort.VTable, self.vtable).GetChunksResults(@ptrCast(*const IDedupDataPort, self), RequestId, MaxWaitMs, ChunkIndex, pChunkCount, ppChunkMetadata, pDataByteCount, ppChunkData, pStatus, ppItemResults); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDedupDataPort_GetRequestStatus(self: *const T, RequestId: Guid, pStatus: ?*DedupDataPortRequestStatus) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupDataPort.VTable, self.vtable).GetRequestStatus(@ptrCast(*const IDedupDataPort, self), RequestId, pStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDedupDataPort_GetRequestResults(self: *const T, RequestId: Guid, MaxWaitMs: u32, pBatchResult: ?*HRESULT, pBatchCount: ?*u32, pStatus: ?*DedupDataPortRequestStatus, ppItemResults: [*]?*HRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupDataPort.VTable, self.vtable).GetRequestResults(@ptrCast(*const IDedupDataPort, self), RequestId, MaxWaitMs, pBatchResult, pBatchCount, pStatus, ppItemResults); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDedupDataPortManager_Value = @import("../zig.zig").Guid.initString("44677452-b90a-445e-8192-cdcfe81511fb"); pub const IID_IDedupDataPortManager = &IID_IDedupDataPortManager_Value; pub const IDedupDataPortManager = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetConfiguration: fn( self: *const IDedupDataPortManager, pMinChunkSize: ?*u32, pMaxChunkSize: ?*u32, pChunkingAlgorithm: ?*DedupChunkingAlgorithm, pHashingAlgorithm: ?*DedupHashingAlgorithm, pCompressionAlgorithm: ?*DedupCompressionAlgorithm, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVolumeStatus: fn( self: *const IDedupDataPortManager, Options: u32, Path: ?BSTR, pStatus: ?*DedupDataPortVolumeStatus, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVolumeDataPort: fn( self: *const IDedupDataPortManager, Options: u32, Path: ?BSTR, ppDataPort: ?*?*IDedupDataPort, ) 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 IDedupDataPortManager_GetConfiguration(self: *const T, pMinChunkSize: ?*u32, pMaxChunkSize: ?*u32, pChunkingAlgorithm: ?*DedupChunkingAlgorithm, pHashingAlgorithm: ?*DedupHashingAlgorithm, pCompressionAlgorithm: ?*DedupCompressionAlgorithm) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupDataPortManager.VTable, self.vtable).GetConfiguration(@ptrCast(*const IDedupDataPortManager, self), pMinChunkSize, pMaxChunkSize, pChunkingAlgorithm, pHashingAlgorithm, pCompressionAlgorithm); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDedupDataPortManager_GetVolumeStatus(self: *const T, Options: u32, Path: ?BSTR, pStatus: ?*DedupDataPortVolumeStatus) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupDataPortManager.VTable, self.vtable).GetVolumeStatus(@ptrCast(*const IDedupDataPortManager, self), Options, Path, pStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDedupDataPortManager_GetVolumeDataPort(self: *const T, Options: u32, Path: ?BSTR, ppDataPort: ?*?*IDedupDataPort) callconv(.Inline) HRESULT { return @ptrCast(*const IDedupDataPortManager.VTable, self.vtable).GetVolumeDataPort(@ptrCast(*const IDedupDataPortManager, self), Options, Path, ppDataPort); } };} 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 (6) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BSTR = @import("../foundation.zig").BSTR; const HRESULT = @import("../foundation.zig").HRESULT; const IStream = @import("../system/com.zig").IStream; const IUnknown = @import("../system/com.zig").IUnknown; 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/storage/data_deduplication.zig
const kernel = @import("root").kernel; const Console = kernel.Console; const HexColor = Console.HexColor; const util = @import("util.zig"); const out8 = util.out8; const in8 = util.in8; const platform = @import("platform.zig"); const code_point_437 = @import("code_point_437.zig"); const Color = enum(u4) { Black = 0, Blue = 1, Green = 2, Cyan = 3, Red = 4, Magenta = 5, Brown = 6, LightGray = 7, DarkGray = 8, LightBlue = 9, LightGreen = 10, LightCyan = 11, LightRed = 12, LightMagenta = 13, Yellow = 14, White = 15, var color_value: u16 = undefined; fn get_cga_color(ansi_color: HexColor) Color { return switch (ansi_color) { HexColor.White => .White, HexColor.LightGray => .LightGray, HexColor.DarkGray => .DarkGray, HexColor.Black => .Black, HexColor.Red => .Red, HexColor.Green => .Green, HexColor.Yellow => .Brown, HexColor.Blue => .Blue, HexColor.Magenta => .Magenta, HexColor.Cyan => .Cyan, HexColor.LightRed => .LightRed, HexColor.LightGreen => .LightGreen, HexColor.LightYellow => .Yellow, HexColor.LightBlue => .LightBlue, HexColor.LightMagenta => .LightMagenta, HexColor.LightCyan => .LightCyan, }; } pub fn set(fg: HexColor, bg: HexColor) void { color_value = (@enumToInt(get_cga_color(fg)) | (@intCast(u16, @enumToInt(get_cga_color(bg))) << 4)) << 8; } pub fn char_value(c: u8) callconv(.Inline) u16 { return @intCast(u16, c) | color_value; } }; const command_port: u16 = 0x03D4; const data_port: u16 = 0x03D5; const high_byte_command: u8 = 14; const low_byte_command: u8 = 15; const set_cursor_shape_command: u8 = 0x0a; const default_fg_color = HexColor.White; const default_bg_color = HexColor.Black; var fg_color = default_fg_color; var bg_color = default_bg_color; var buffer: [*]u16 = undefined; pub var console = Console{ .place_impl = place_impl, .scroll_impl = scroll_impl, .set_hex_color_impl = set_hex_color_impl, .get_hex_color_impl = get_hex_color_impl, .reset_attributes_impl = reset_attributes_impl, .move_cursor_impl = move_cursor_impl, .show_cursor_impl = show_cursor_impl, .clear_screen_impl = clear_screen_impl, }; pub fn init() void { buffer = @intToPtr([*]u16, platform.kernel_to_virtual(0xB8000)); console.init(80, 25); } fn place_impl(c: *Console, utf32_value: u32, row: u32, col: u32) void { const cp437_value = if (from_unicode(utf32_value)) |cp437| cp437 else '?'; const index: u32 = (row *% c.width) +% col; buffer[index] = Color.char_value(cp437_value); } pub fn set_hex_color_impl(c: *Console, color: HexColor, layer: Console.Layer) void { _ = c; if (layer == .Foreground) { fg_color = color; } else { bg_color = color; } Color.set(fg_color, bg_color); } pub fn get_hex_color_impl(c: *Console, layer: Console.Layer) HexColor { _ = c; return if (layer == .Foreground) fg_color else bg_color; } pub fn reset_attributes_impl(c: *Console) void { c.set_hex_colors(default_fg_color, default_bg_color); } pub fn clear_screen_impl(c: *Console) void { var row: u32 = 0; while (row < c.height) : (row +%= 1) { var col: u32 = 0; while (col < c.width) : (col +%= 1) { c.place(' ', row, col); } } } pub fn move_cursor_impl(c: *Console, row: u32, col: u32) void { const index: u32 = (row *% c.width) +% col; out8(command_port, high_byte_command); out8(data_port, @intCast(u8, (index >> 8) & 0xFF)); out8(command_port, low_byte_command); out8(data_port, @intCast(u8, index & 0xFF)); } pub fn show_cursor_impl(c: *Console, show: bool) void { _ = c; out8(command_port, set_cursor_shape_command); out8(data_port, if (show) 0 else 0x20); // Bit 5 Disables Cursor } pub fn scroll_impl(c: *Console) void { var y: u32 = 1; while (y < c.height) : (y +%= 1) { var x: u32 = 0; while (x < c.width) : (x +%= 1) { const src: u32 = (y *% c.width) +% x; const dest: u32 = ((y - 1) *% c.width) +% x; buffer[dest] = buffer[src]; } } var x: u32 = 0; while (x < c.width) : (x +%= 1) { c.place(' ', c.height - 1, x); } } pub fn print_all_characters() void { console.reset_terminal(); var i: u16 = 0; while (i < 256) { console.print_char(@truncate(u8, i)); if (i % 32 == 31) { console.newline(); } i += 1; } } /// Convert UTF-32 to Code Page 437 pub fn from_unicode(c: u32) ?u8 { // Code Page 437 Doesn't Have Any Points Past 2^16 if (c > 0xFFFF) return null; const c16 = @intCast(u16, c); // Check a few contiguous ranges. The main one is Printable ASCII. if (code_point_437.contiguous_ranges(c16)) |c8| return c8; // Else check the hash table const hash = c16 % code_point_437.bucket_count; if (hash > code_point_437.max_hash_used) return null; const offset = hash * code_point_437.max_bucket_length; const bucket = code_point_437.hash_table[offset..offset + code_point_437.max_bucket_length]; for (bucket[0..]) |entry| { const valid = @intCast(u8, entry >> 24); if (valid == 0) return null; const key = @truncate(u16, entry); const value = @truncate(u8, entry >> 16); if (key == c16) return value; } return null; }
kernel/platform/cga_console.zig
const std = @import("std"); const c = @cImport({ @cInclude("stdlib.h"); }); const powtens = [_]f64{ 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22, }; fn is_digit(b: u8) bool { return (b >= '0' and b <= '9'); } fn is_ident_char(b: u8) bool { return (b >= 'a' and b <= 'z') or (b >= 'A' and b <= 'Z') or (b >= '0' and b <= '9') or b == '_'; } // https://github.com/nim-lang/Nim/blob/c94647aecad6ed7fd12152800437a6cda11e06e6/lib/system/strmantle.nim#L137 // Nim implementation of float parsing. The fast path is faster than // fmt.parseFloat by about 3 times on my PC. The slow path uses c_strtod function from libc pub fn parse_float(s: []const u8) !f64 { var num: f64 = 0.0; var i: usize = 0; var start: usize = 0; var sign: f64 = 1.0; var kdigits: i64 = 0; var fdigits: i64 = 0; var exponent: i64 = 0; var integer: u64 = 0; var frac_exponent: i64 = 0; var exp_sign: i64 = 1; var first_digit: i64 = -1; var has_sign: bool = false; if (i < s.len and (s[i] == '+' or s[i] == '-')) { has_sign = true; if (s[i] == '-') { sign = -1.0; } i += 1; } if (i + 2 < s.len and (s[i] == 'N' or s[i] == 'n')) { if (s[i + 1] == 'A' or s[i + 1] == 'a') { if (s[i + 2] == 'N' or s[i + 2] == 'n') { if (i + 3 >= s.len or !is_ident_char(s[i + 3])) { return std.math.nan(f64); } } } return error.InvalidFloat; } if (i + 2 < s.len and (s[i] == 'I' or s[i] == 'i')) { if (s[i + 1] == 'N' or s[i + 1] == 'n') { if (s[i + 2] == 'F' or s[i + 2] == 'f') { if (i + 3 >= s.len or !is_ident_char(s[i + 3])) { return std.math.inf(f64) * sign; } } } return error.InvalidFloat; } if (i < s.len and is_digit(s[i])) { first_digit = s[i] - '0'; } // Integer part while (i < s.len and is_digit(s[i])) { kdigits += 1; integer = integer * 10 + @intCast(u64, s[i] - '0'); i += 1; while (i < s.len and s[i] == '_') { i += 1; } } if (i < s.len and s[i] == '.') { i += 1; if (kdigits <= 0) { while (i < s.len and s[i] == '0') { frac_exponent += 1; i += 1; while (i < s.len and s[i] == '_') { i += 1; } } } if (first_digit == -1 and i < s.len and is_digit(s[i])) { first_digit = (s[i] - '0'); } while (i < s.len and is_digit(s[i])) { fdigits += 1; frac_exponent += 1; integer = integer * 10 + (s[i] - '0'); i += 1; while (i < s.len and s[i] == '_') { i += 1; } } } if ((kdigits + fdigits) <= 0 and (i == start or (i == start + 1 and has_sign))) { return error.InvalidFloat; } if ((i + 1) < s.len and (s[i] == 'e' or s[i] == 'E')) { i += 1; if (s[i] == '+' or s[i] == '-') { if (s[i] == '-') { exp_sign = -1; } i += 1; } if (!is_digit(s[i])) { return error.InvalidFloat; } while (i < s.len and is_digit(s[i])) { exponent = exponent * 10 + @intCast(i64, s[i] - '0'); i += 1; } } var real_exponent = exp_sign * exponent - frac_exponent; const exp_negative = real_exponent < 0; var abs_exponent = @intCast(usize, try std.math.absInt(real_exponent)); if (abs_exponent > 999) { if (exp_negative) { num = 0.0 * sign; } else { num = std.math.inf_f64 * sign; } return num; } const digits = kdigits + fdigits; if (digits <= 15 or (digits <= 16 and first_digit <= 8)) { if (abs_exponent <= 22) { if (exp_negative) { num = sign * @intToFloat(f64, integer) / powtens[abs_exponent]; } else { num = sign * @intToFloat(f64, integer) * powtens[abs_exponent]; } return num; } const slop = @intCast(usize, 15 - kdigits - fdigits); if (abs_exponent <= 22 + slop and !exp_negative) { num = sign * @intToFloat(f64, integer) * powtens[slop] * powtens[abs_exponent - slop]; return num; } } // Slow path if the fast one didn't work var t: [500]u8 = [_]u8{0} ** 500; var ti: usize = 0; const maxlen = t.len - "e+000".len; i = 0; if (i < s.len and s[i] == '.') { i += 1; } while (i < s.len and (is_digit(s[i]) or s[i] == '+' or s[i] == '-')) { if (ti < maxlen) { t[ti] = s[i]; ti += 1; } i += 1; while (i < s.len and (s[i] == '.' or s[i] == '_')) : (i += 1) {} } t[ti] = 'E'; ti += 1; if (exp_negative) { t[ti] = '-'; } else { t[ti] = '+'; } ti += 4; t[ti - 1] = @intCast(u8, ('0' + @mod(abs_exponent, 10))); abs_exponent = @divTrunc(abs_exponent, 10); t[ti - 2] = @intCast(u8, ('0' + @mod(abs_exponent, 10))); abs_exponent = @divTrunc(abs_exponent, 10); t[ti - 3] = @intCast(u8, ('0' + @mod(abs_exponent, 10))); abs_exponent = @divTrunc(abs_exponent, 10); var temp: []u8 = undefined; num = c.strtod(&t, @ptrCast([*c][*c]u8, &temp.ptr)); return num; }
src/parse-float.zig
const std = @import("std"); const mem = std.mem; const expect = std.testing.expect; // normal comment /// this is a documentation comment /// doc comment line 2 fn emptyFunctionWithComments() void {} test "empty function with comments" { emptyFunctionWithComments(); } test "truncate" { try expect(testTruncate(0x10fd) == 0xfd); comptime try expect(testTruncate(0x10fd) == 0xfd); } fn testTruncate(x: u32) u8 { return @truncate(u8, x); } const g1: i32 = 1233 + 1; var g2: i32 = 0; test "global variables" { try expect(g2 == 0); g2 = g1; try expect(g2 == 1234); } test "comptime keyword on expressions" { const x: i32 = comptime x: { break :x 1 + 2 + 3; }; try expect(x == comptime 6); } test "type equality" { try expect(*const u8 != *u8); } test "pointer dereferencing" { var x = @as(i32, 3); const y = &x; y.* += 1; try expect(x == 4); try expect(y.* == 4); } test "const expression eval handling of variables" { var x = true; while (x) { x = false; } } test "character literals" { try expect('\'' == single_quote); } const single_quote = '\''; test "non const ptr to aliased type" { const int = i32; try expect(?*int == ?*i32); } test "cold function" { thisIsAColdFn(); comptime thisIsAColdFn(); } fn thisIsAColdFn() void { @setCold(true); } test "unicode escape in character literal" { var a: u24 = '\u{01f4a9}'; try expect(a == 128169); } test "unicode character in character literal" { try expect('💩' == 128169); } fn first4KeysOfHomeRow() []const u8 { return "aoeu"; } test "return string from function" { try expect(mem.eql(u8, first4KeysOfHomeRow(), "aoeu")); } test "hex escape" { try expect(mem.eql(u8, "\x68\x65\x6c\x6c\x6f", "hello")); } test "multiline string" { const s1 = \\one \\two) \\three ; const s2 = "one\ntwo)\nthree"; try expect(mem.eql(u8, s1, s2)); } test "multiline string comments at start" { const s1 = //\\one \\two) \\three ; const s2 = "two)\nthree"; try expect(mem.eql(u8, s1, s2)); } test "multiline string comments at end" { const s1 = \\one \\two) //\\three ; const s2 = "one\ntwo)"; try expect(mem.eql(u8, s1, s2)); } test "multiline string comments in middle" { const s1 = \\one //\\two) \\three ; const s2 = "one\nthree"; try expect(mem.eql(u8, s1, s2)); } test "multiline string comments at multiple places" { const s1 = \\one //\\two \\three //\\four \\five ; const s2 = "one\nthree\nfive"; try expect(mem.eql(u8, s1, s2)); } test "call result of if else expression" { try expect(mem.eql(u8, f2(true), "a")); try expect(mem.eql(u8, f2(false), "b")); } fn f2(x: bool) []const u8 { return (if (x) fA else fB)(); } fn fA() []const u8 { return "a"; } fn fB() []const u8 { return "b"; }
test/behavior/basic.zig
// Because SPIR-V requires re-compilation anyway, and so hot swapping will not work // anyway, we simply generate all the code in flushModule. This keeps // things considerably simpler. const SpirV = @This(); const std = @import("std"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; const log = std.log.scoped(.link); const Module = @import("../Module.zig"); const Compilation = @import("../Compilation.zig"); const link = @import("../link.zig"); const codegen = @import("../codegen/spirv.zig"); const Word = codegen.Word; const ResultId = codegen.ResultId; const trace = @import("../tracy.zig").trace; const build_options = @import("build_options"); const spec = @import("../codegen/spirv/spec.zig"); const Air = @import("../Air.zig"); const Liveness = @import("../Liveness.zig"); // TODO: Should this struct be used at all rather than just a hashmap of aux data for every decl? pub const FnData = struct { // We're going to fill these in flushModule, and we're going to fill them unconditionally, // so just set it to undefined. id: ResultId = undefined, }; base: link.File, /// This linker backend does not try to incrementally link output SPIR-V code. /// Instead, it tracks all declarations in this table, and iterates over it /// in the flush function. decl_table: std.AutoArrayHashMapUnmanaged(*Module.Decl, DeclGenContext) = .{}, const DeclGenContext = struct { air: Air, liveness: Liveness, }; pub fn createEmpty(gpa: *Allocator, options: link.Options) !*SpirV { const spirv = try gpa.create(SpirV); spirv.* = .{ .base = .{ .tag = .spirv, .options = options, .file = null, .allocator = gpa, }, }; // TODO: Figure out where to put all of these switch (options.target.cpu.arch) { .spirv32, .spirv64 => {}, else => return error.TODOArchNotSupported, } switch (options.target.os.tag) { .opencl, .glsl450, .vulkan => {}, else => return error.TODOOsNotSupported, } if (options.target.abi != .none) { return error.TODOAbiNotSupported; } return spirv; } pub fn openPath(allocator: *Allocator, sub_path: []const u8, options: link.Options) !*SpirV { assert(options.object_format == .spirv); if (options.use_llvm) return error.LLVM_BackendIsTODO_ForSpirV; // TODO: LLVM Doesn't support SpirV at all. if (options.use_lld) return error.LLD_LinkingIsTODO_ForSpirV; // TODO: LLD Doesn't support SpirV at all. // TODO: read the file and keep vaild parts instead of truncating const file = try options.emit.?.directory.handle.createFile(sub_path, .{ .truncate = true, .read = true }); errdefer file.close(); const spirv = try createEmpty(allocator, options); errdefer spirv.base.destroy(); spirv.base.file = file; return spirv; } pub fn deinit(self: *SpirV) void { self.decl_table.deinit(self.base.allocator); } pub fn updateFunc(self: *SpirV, module: *Module, func: *Module.Fn, air: Air, liveness: Liveness) !void { if (build_options.skip_non_native) { @panic("Attempted to compile for architecture that was disabled by build configuration"); } _ = module; // Keep track of all decls so we can iterate over them on flush(). _ = try self.decl_table.getOrPut(self.base.allocator, func.owner_decl); _ = air; _ = liveness; @panic("TODO SPIR-V needs to keep track of Air and Liveness so it can use them later"); } pub fn updateDecl(self: *SpirV, module: *Module, decl: *Module.Decl) !void { if (build_options.skip_non_native) { @panic("Attempted to compile for architecture that was disabled by build configuration"); } _ = module; // Keep track of all decls so we can iterate over them on flush(). _ = try self.decl_table.getOrPut(self.base.allocator, decl); } pub fn updateDeclExports( self: *SpirV, module: *Module, decl: *const Module.Decl, exports: []const *Module.Export, ) !void { _ = self; _ = module; _ = decl; _ = exports; } pub fn freeDecl(self: *SpirV, decl: *Module.Decl) void { assert(self.decl_table.swapRemove(decl)); } pub fn flush(self: *SpirV, comp: *Compilation) !void { if (build_options.have_llvm and self.base.options.use_lld) { return error.LLD_LinkingIsTODO_ForSpirV; // TODO: LLD Doesn't support SpirV at all. } else { return self.flushModule(comp); } } pub fn flushModule(self: *SpirV, comp: *Compilation) !void { if (build_options.skip_non_native) { @panic("Attempted to compile for architecture that was disabled by build configuration"); } const tracy = trace(@src()); defer tracy.end(); const module = self.base.options.module.?; const target = comp.getTarget(); var spv = codegen.SPIRVModule.init(self.base.allocator, module); defer spv.deinit(); // Allocate an ID for every declaration before generating code, // so that we can access them before processing them. // TODO: We're allocating an ID unconditionally now, are there // declarations which don't generate a result? // TODO: fn_link is used here, but thats probably not the right field. It will work anyway though. { for (self.decl_table.keys()) |decl| { if (!decl.has_tv) continue; decl.fn_link.spirv.id = spv.allocResultId(); } } // Now, actually generate the code for all declarations. { var decl_gen = codegen.DeclGen.init(&spv); defer decl_gen.deinit(); var it = self.decl_table.iterator(); while (it.next()) |entry| { const decl = entry.key_ptr.*; if (!decl.has_tv) continue; const air = entry.value_ptr.air; const liveness = entry.value_ptr.liveness; if (try decl_gen.gen(decl, air, liveness)) |msg| { try module.failed_decls.put(module.gpa, decl, msg); return; // TODO: Attempt to generate more decls? } } } try writeCapabilities(&spv.binary.capabilities_and_extensions, target); try writeMemoryModel(&spv.binary.capabilities_and_extensions, target); const header = [_]Word{ spec.magic_number, (spec.version.major << 16) | (spec.version.minor << 8), 0, // TODO: Register Zig compiler magic number. spv.resultIdBound(), 0, // Schema (currently reserved for future use in the SPIR-V spec). }; // Note: The order of adding sections to the final binary // follows the SPIR-V logical module format! const buffers = &[_][]const Word{ &header, spv.binary.capabilities_and_extensions.items, spv.binary.debug_strings.items, spv.binary.types_globals_constants.items, spv.binary.fn_decls.items, }; var iovc_buffers: [buffers.len]std.os.iovec_const = undefined; for (iovc_buffers) |*iovc, i| { const bytes = std.mem.sliceAsBytes(buffers[i]); iovc.* = .{ .iov_base = bytes.ptr, .iov_len = bytes.len }; } var file_size: u64 = 0; for (iovc_buffers) |iov| { file_size += iov.iov_len; } const file = self.base.file.?; try file.seekTo(0); try file.setEndPos(file_size); try file.pwritevAll(&iovc_buffers, 0); } fn writeCapabilities(binary: *std.ArrayList(Word), target: std.Target) !void { // TODO: Integrate with a hypothetical feature system const cap: spec.Capability = switch (target.os.tag) { .opencl => .Kernel, .glsl450 => .Shader, .vulkan => .VulkanMemoryModel, else => unreachable, // TODO }; try codegen.writeInstruction(binary, .OpCapability, &[_]Word{@enumToInt(cap)}); } fn writeMemoryModel(binary: *std.ArrayList(Word), target: std.Target) !void { const addressing_model = switch (target.os.tag) { .opencl => switch (target.cpu.arch) { .spirv32 => spec.AddressingModel.Physical32, .spirv64 => spec.AddressingModel.Physical64, else => unreachable, // TODO }, .glsl450, .vulkan => spec.AddressingModel.Logical, else => unreachable, // TODO }; const memory_model: spec.MemoryModel = switch (target.os.tag) { .opencl => .OpenCL, .glsl450 => .GLSL450, .vulkan => .Vulkan, else => unreachable, }; try codegen.writeInstruction(binary, .OpMemoryModel, &[_]Word{ @enumToInt(addressing_model), @enumToInt(memory_model), }); }
src/link/SpirV.zig
const std = @import("std"); const inputFile = @embedFile("./input/day02.txt"); const forwardLen: usize = "forward ".len; const upLen: usize = "up ".len; const downLen: usize = "down ".len; fn calcPosition(input: []const u8) !i32 { var start: usize = 0; var x: i32 = 0; var y: i32 = 0; while (std.mem.indexOfScalarPos(u8, input, start, '\n')) |end| : (start = end + 1) { const c = input[start]; switch (c) { 'f' => x += try std.fmt.parseInt(i32, input[start + forwardLen .. end], 10), 'u' => y -= try std.fmt.parseInt(i32, input[start + upLen .. end], 10), 'd' => y += try std.fmt.parseInt(i32, input[start + downLen .. end], 10), else => unreachable, } } return x * y; } fn calcPositionAim(input: []const u8) !i32 { var start: usize = 0; var x: i32 = 0; var y: i32 = 0; var aim: i32 = 0; while (std.mem.indexOfScalarPos(u8, input, start, '\n')) |end| : (start = end + 1) { const c = input[start]; switch (c) { 'f' => { const forward = try std.fmt.parseInt(i32, input[start + forwardLen .. end], 10); x += forward; y += forward * aim; }, 'u' => aim -= try std.fmt.parseInt(i32, input[start + upLen .. end], 10), 'd' => aim += try std.fmt.parseInt(i32, input[start + downLen .. end], 10), else => unreachable, } } return x * y; } pub fn main() !void { const stdout = std.io.getStdOut().writer(); try stdout.print("Height * depth = {d}\nWith aim: {d}", .{ try calcPosition(inputFile), try calcPositionAim(inputFile) }); } test "calcPosition" { const input = \\forward 5 \\down 5 \\forward 8 \\up 3 \\down 8 \\forward 2 \\ ; try std.testing.expectEqual(@as(i32, 150), try calcPosition(input)); } test "calcPositionAim" { const input = \\forward 5 \\down 5 \\forward 8 \\up 3 \\down 8 \\forward 2 \\ ; try std.testing.expectEqual(@as(i32, 900), try calcPositionAim(input)); }
src/day02.zig
const std = @import("std"); const c = @import("c.zig"); const objc = @import("objc.zig"); const object = objc.object; const Class = objc.Class; const id = objc.id; const SEL = objc.SEL; const sel_getUid = objc.sel_getUid; /// Sends a message to an id or Class and returns the return value of the called method pub fn msgSend(comptime ReturnType: type, target: anytype, selector: SEL, args: anytype) ReturnType { const target_type = @TypeOf(target); if ((target_type == id or target_type == Class) == false) @compileError("msgSend target should be of type id or Class"); const args_meta = @typeInfo(@TypeOf(args)).Struct.fields; const FnType = blk: { { // NOTE(hazeycode): The following commented out code crashes the compiler :( last tested with Zig 0.9.0 // https://github.com/ziglang/zig/issues/9526 // comptime var fn_args: [2 + args_meta.len]std.builtin.TypeInfo.FnArg = undefined; // fn_args[0] = .{ // .is_generic = false, // .is_noalias = false, // .arg_type = @TypeOf(target), // }; // fn_args[1] = .{ // .is_generic = false, // .is_noalias = false, // .arg_type = SEL, // }; // inline for (args_meta) |a, i| { // fn_args[2 + i] = .{ // .is_generic = false, // .is_noalias = false, // .arg_type = a.field_type, // }; // } // break :blk @Type(.{ .Fn = .{ // .calling_convention = .C, // .alignment = 0, // .is_generic = false, // .is_var_args = false, // .return_type = ReturnType, // .args = &fn_args, // } }); } { // TODO(hazeycode): replace this hack with the more generalised code above once it doens't crash the compiler break :blk switch (args_meta.len) { 0 => fn (@TypeOf(target), SEL) callconv(.C) ReturnType, 1 => fn (@TypeOf(target), SEL, args_meta[0].field_type) callconv(.C) ReturnType, 2 => fn (@TypeOf(target), SEL, args_meta[0].field_type, args_meta[1].field_type) callconv(.C) ReturnType, 3 => fn (@TypeOf(target), SEL, args_meta[0].field_type, args_meta[1].field_type, args_meta[2].field_type) callconv(.C) ReturnType, 4 => fn (@TypeOf(target), SEL, args_meta[0].field_type, args_meta[1].field_type, args_meta[2].field_type, args_meta[3].field_type) callconv(.C) ReturnType, else => @compileError("Unsupported number of args: add more variants in zig-objcrt/src/message.zig"), }; } }; // NOTE: func is a var because making it const causes a compile error which I believe is a compiler bug var func = @ptrCast(FnType, c.objc_msgSend); return @call(.{}, func, .{ target, selector } ++ args); }
modules/platform/vendored/zig-objcrt/src/message.zig
const std = @import("std"); const stdx = @import("stdx"); const string = stdx.string; const ds = stdx.ds; const t = stdx.testing; const graphics = @import("graphics.zig"); const Transform = graphics.transform.Transform; const Color = graphics.Color; const draw_cmd = @import("draw_cmd.zig"); const DrawCommandList = draw_cmd.DrawCommandList; const DrawCommandPtr = draw_cmd.DrawCommandPtr; const log = stdx.log.scoped(.svg); // Parse SVG file format and SVG paths into draw commands. pub const PathCommand = enum { MoveTo, MoveToRel, LineTo, LineToRel, VertLineTo, VertLineToRel, CurveTo, CurveToRel, SmoothCurveTo, SmoothCurveToRel, ClosePath, }; pub fn PathCommandData(comptime Tag: PathCommand) type { return switch (Tag) { .MoveTo => PathMoveTo, .MoveToRel => PathMoveToRel, .LineTo => PathLineTo, .LineToRel => PathLineToRel, .VertLineTo => PathVertLineTo, .VertLineToRel => PathVertLineToRel, .CurveTo => PathCurveTo, .CurveToRel => PathCurveToRel, .SmoothCurveTo => PathSmoothCurveTo, .SmoothCurveToRel => PathSmoothCurveToRel, .ClosePath => void, }; } pub const PathCommandPtr = struct { tag: PathCommand, id: u32, fn init(tag: PathCommand, id: u32) @This() { return .{ .tag = tag, .id = id, }; } fn getData(self: *@This(), comptime Tag: PathCommand, buf: []const u8) PathCommandData(Tag) { return std.mem.bytesToValue(PathCommandData(Tag), buf[self.id..][0..@sizeOf(PathCommandData(Tag))]); } }; pub const PathCurveTo = struct { ca_x: f32, ca_y: f32, cb_x: f32, cb_y: f32, x: f32, y: f32, }; pub const PathSmoothCurveTo = struct { c2_x: f32, c2_y: f32, x: f32, y: f32, }; pub const PathSmoothCurveToRel = struct { c2_x: f32, c2_y: f32, x: f32, y: f32, }; pub const PathCurveToRel = struct { ca_x: f32, ca_y: f32, cb_x: f32, cb_y: f32, x: f32, y: f32, }; pub const PathVertLineTo = struct { y: f32, }; pub const PathVertLineToRel = struct { y: f32, }; pub const PathLineTo = struct { x: f32, y: f32, }; pub const PathLineToRel = struct { x: f32, y: f32, }; pub const PathMoveTo = struct { x: f32, y: f32, }; pub const PathMoveToRel = struct { x: f32, y: f32, }; pub const SvgPath = struct { alloc: ?std.mem.Allocator, data: []const f32, cmds: []const PathCommand, pub fn deinit(self: @This()) void { if (self.alloc) |alloc| { alloc.free(self.data); alloc.free(self.cmds); } } pub fn getData(self: @This(), comptime Tag: PathCommand, data_idx: usize) PathCommandData(Tag) { const Size = @sizeOf(PathCommandData(Tag)) / 4; return @ptrCast(*const PathCommandData(Tag), self.data[data_idx .. data_idx + Size]).*; } }; pub const PathParser = struct { const Self = @This(); data: std.ArrayList(f32), cmds: std.ArrayList(u8), temp_buf: std.ArrayList(u8), src: []const u8, next_pos: u32, // Use cur buffers during parsing so it can parse with it's own buffer or with a give buffer. cur_data: std.ArrayList(f32), cur_cmds: std.ArrayList(u8), pub fn init(alloc: std.mem.Allocator) Self { return .{ .data = std.ArrayList(f32).init(alloc), .temp_buf = std.ArrayList(u8).init(alloc), .cmds = std.ArrayList(u8).init(alloc), .src = undefined, .next_pos = undefined, .cur_data = undefined, .cur_cmds = undefined, }; } pub fn deinit(self: Self) void { self.data.deinit(); self.cmds.deinit(); self.temp_buf.deinit(); } // Parses into existing buffers. fn parseAppend(self: *Self, cmds: *std.ArrayList(u8), data: *std.ArrayList(f32), str: []const u8) !SvgPath { self.cur_cmds = cmds.*; self.cur_data = data.*; defer { cmds.* = self.cur_cmds; data.* = self.cur_data; } return self.parseInternal(str); } fn parseAlloc(self: *Self, alloc: std.mem.Allocator, str: []const u8) !SvgPath { const path = try self.parse(str); const new_cmds = try alloc.alloc(PathCommand, path.cmds.len); std.mem.copy(PathCommand, new_cmds, path.cmds); const new_data = try alloc.alloc(f32, path.data.len); std.mem.copy(f32, new_data, path.data); return SvgPath{ .alloc = alloc, .data = new_data, .cmds = new_cmds, }; } pub fn parse(self: *Self, str: []const u8) !SvgPath { self.temp_buf.clearRetainingCapacity(); self.cur_cmds = self.cmds; self.cur_data = self.data; defer { self.cmds = self.cur_cmds; self.data = self.cur_data; } self.cur_cmds.clearRetainingCapacity(); self.cur_data.clearRetainingCapacity(); return self.parseInternal(str); } fn seekToNext(self: *Self) ?u8 { self.consumeDelim(); if (self.nextAtEnd()) { return null; } return self.peekNext(); } fn parseInternal(self: *Self, str: []const u8) !SvgPath { self.src = str; self.next_pos = 0; const start_data_idx = self.cur_data.items.len; const start_cmd_idx = self.cur_cmds.items.len; errdefer { // Restore buffers. self.cur_data.resize(start_data_idx) catch unreachable; self.cur_cmds.resize(start_cmd_idx) catch unreachable; } while (true) { self.consumeDelim(); if (self.nextAtEnd()) { break; } var ch = self.peekNext(); if (!std.ascii.isAlpha(ch)) { log.debug("unsupported command char: {c} {} at {}", .{ ch, ch, self.next_pos }); log.debug("{s}", .{self.src}); return error.ParseError; } self.consumeNext(); switch (ch) { 'm' => { var cmd = try self.parseSvgMoveto(true); self.cur_cmds.append(@enumToInt(cmd)) catch unreachable; ch = self.seekToNext() orelse break; while (!std.ascii.isAlpha(ch)) { // Subsequent points are treated as LineTo cmd = try self.parseSvgLineto(true); self.cur_cmds.append(@enumToInt(cmd)) catch unreachable; ch = self.seekToNext() orelse break; } }, 'M' => { const cmd = try self.parseSvgMoveto(false); self.cur_cmds.append(@enumToInt(cmd)) catch unreachable; }, 'v' => { const cmd = try self.parseSvgVerticalLineto(true); self.cur_cmds.append(@enumToInt(cmd)) catch unreachable; }, 'l' => { var cmd = try self.parseSvgLineto(true); self.cur_cmds.append(@enumToInt(cmd)) catch unreachable; ch = self.seekToNext() orelse break; while (!std.ascii.isAlpha(ch)) { // Polyline, keep parsing same command. cmd = try self.parseSvgLineto(true); self.cur_cmds.append(@enumToInt(cmd)) catch unreachable; ch = self.seekToNext() orelse break; } }, 'L' => { const cmd = try self.parseSvgLineto(false); self.cur_cmds.append(@enumToInt(cmd)) catch unreachable; }, 'c' => { var cmd = try self.parseSvgCurveto(true); self.cur_cmds.append(@enumToInt(cmd)) catch unreachable; ch = self.seekToNext() orelse break; while (!std.ascii.isAlpha(ch)) { // Polybezier, keep parsing same command. cmd = try self.parseSvgCurveto(true); self.cur_cmds.append(@enumToInt(cmd)) catch unreachable; ch = self.seekToNext() orelse break; } }, 'C' => { const cmd = try self.parseSvgCurveto(false); self.cur_cmds.append(@enumToInt(cmd)) catch unreachable; }, 's' => { var cmd = try self.parseSvgSmoothCurveto(true); self.cur_cmds.append(@enumToInt(cmd)) catch unreachable; ch = self.seekToNext() orelse break; while (!std.ascii.isAlpha(ch)) { // Polybezier, keep parsing same command. cmd = try self.parseSvgSmoothCurveto(true); self.cur_cmds.append(@enumToInt(cmd)) catch unreachable; ch = self.seekToNext() orelse break; } }, 'S' => { const cmd = try self.parseSvgSmoothCurveto(false); self.cur_cmds.append(@enumToInt(cmd)) catch unreachable; }, 'z' => { self.cur_cmds.append(@enumToInt(PathCommand.ClosePath)) catch unreachable; }, 'Z' => { self.cur_cmds.append(@enumToInt(PathCommand.ClosePath)) catch unreachable; }, else => { log.debug("unsupported command char: {c} {}", .{ ch, ch }); return error.ParseError; }, } } return SvgPath{ .alloc = null, .data = self.cur_data.items[start_data_idx..], .cmds = std.mem.bytesAsSlice(PathCommand, self.cur_cmds.items[start_cmd_idx..]), }; } fn consumeDelim(self: *Self) void { while (!self.nextAtEnd()) { const ch = self.peekNext(); _ = std.mem.indexOf(u8, SvgPathDelimiters, &.{ch}) orelse return; self.next_pos += 1; } } fn nextAtEnd(self: *Self) bool { return self.next_pos == self.src.len; } fn consumeNext(self: *Self) void { self.next_pos += 1; } fn peekNext(self: *Self) u8 { return self.src[self.next_pos]; } fn parseSvgVerticalLineto(self: *Self, relative: bool) !PathCommand { const y = try self.parseSvgFloat(); if (relative) { return self.appendCommand(.VertLineToRel, &PathVertLineToRel{ .y = y, }); } else { return self.appendCommand(.VertLineTo, &PathVertLineTo{ .y = y, }); } } fn parseSvgLineto(self: *Self, relative: bool) !PathCommand { const x = try self.parseSvgFloat(); const y = try self.parseSvgFloat(); if (relative) { return self.appendCommand(.LineToRel, &PathLineToRel{ .x = x, .y = y, }); } else { return self.appendCommand(.LineTo, &PathLineTo{ .x = x, .y = y, }); } } fn appendCommand(self: *Self, comptime Tag: PathCommand, cmd: *PathCommandData(Tag)) PathCommand { const Size = @sizeOf(std.meta.Child(@TypeOf(cmd))) / 4; self.cur_data.appendSlice(@ptrCast(*[Size]f32, cmd)) catch unreachable; return Tag; } fn parseSvgMoveto(self: *Self, relative: bool) !PathCommand { // log.debug("parse moveto", .{}); const x = try self.parseSvgFloat(); const y = try self.parseSvgFloat(); if (relative) { return self.appendCommand(.MoveToRel, &PathMoveToRel{ .x = x, .y = y, }); } else { return self.appendCommand(.MoveTo, &PathMoveTo{ .x = x, .y = y, }); } } fn parseSvgSmoothCurveto(self: *Self, relative: bool) !PathCommand { const c2_x = try self.parseSvgFloat(); const c2_y = try self.parseSvgFloat(); const x = try self.parseSvgFloat(); const y = try self.parseSvgFloat(); if (relative) { return self.appendCommand(.SmoothCurveToRel, &PathSmoothCurveToRel{ .c2_x = c2_x, .c2_y = c2_y, .x = x, .y = y, }); } else { return self.appendCommand(.SmoothCurveTo, &PathSmoothCurveTo{ .c2_x = c2_x, .c2_y = c2_y, .x = x, .y = y, }); } } fn parseSvgCurveto(self: *Self, relative: bool) !PathCommand { const ca_x = try self.parseSvgFloat(); const ca_y = try self.parseSvgFloat(); const cb_x = try self.parseSvgFloat(); const cb_y = try self.parseSvgFloat(); const x = try self.parseSvgFloat(); const y = try self.parseSvgFloat(); if (relative) { return self.appendCommand(.CurveToRel, &PathCurveToRel{ .ca_x = ca_x, .ca_y = ca_y, .cb_x = cb_x, .cb_y = cb_y, .x = x, .y = y, }); } else { return self.appendCommand(.CurveTo, &PathCurveTo{ .ca_x = ca_x, .ca_y = ca_y, .cb_x = cb_x, .cb_y = cb_y, .x = x, .y = y, }); } } fn parseSvgFloat(self: *Self) !f32 { // log.debug("parse float", .{}); self.consumeDelim(); self.temp_buf.clearRetainingCapacity(); var allow_decimal = true; var is_valid = false; // Check first character. if (self.nextAtEnd()) { return error.ParseError; } var ch = self.peekNext(); if (std.ascii.isDigit(ch)) { is_valid = true; self.temp_buf.append(ch) catch unreachable; } else if (ch == '-') { self.temp_buf.append(ch) catch unreachable; } else if (ch == '.') { allow_decimal = false; } else { return error.ParseError; } self.consumeNext(); while (true) { if (self.nextAtEnd()) { break; } ch = self.peekNext(); if (std.ascii.isDigit(ch)) { is_valid = true; self.temp_buf.append(ch) catch unreachable; self.consumeNext(); continue; } if (allow_decimal and ch == '.') { allow_decimal = false; self.temp_buf.append(ch) catch unreachable; self.consumeNext(); continue; } // Not a float char. Check to see if we already have a valid number. if (is_valid) { break; } else { return error.ParseError; } } return std.fmt.parseFloat(f32, self.temp_buf.items) catch unreachable; } }; const SvgPathDelimiters = " ,\r\n\t"; pub fn parseSvgPath(alloc: std.mem.Allocator, str: []const u8) !SvgPath { var parser = PathParser.init(alloc); defer parser.deinit(); return parser.parseAlloc(alloc, str); } test "parseSvgPath absolute moveto" { const res = try parseSvgPath(t.alloc, "M394,106"); defer res.deinit(); try t.eq(res.cmds[0], .MoveTo); const data = res.getData(.MoveTo, 0); try t.eq(data.x, 394); try t.eq(data.y, 106); } test "parseSvgPath relative curveto" { const res = try parseSvgPath(t.alloc, "c-10.2,7.3-24,12-37.7,12"); defer res.deinit(); try t.eq(res.cmds[0], .CurveToRel); const data = res.getData(.CurveToRel, 0); try t.eq(data.ca_x, -10.2); try t.eq(data.ca_y, 7.3); try t.eq(data.cb_x, -24); try t.eq(data.cb_y, 12); try t.eq(data.x, -37.7); try t.eq(data.y, 12); } test "parseSvgPath curveto polybezier" { const res = try parseSvgPath(t.alloc, "m293,111s-12-8-13.5-6c0,0,10.5,6.5,13,15,0,0-1.5-9,0.5-9z"); defer res.deinit(); try t.eq(res.cmds.len, 5); try t.eq(res.cmds[2], .CurveToRel); var cmd = res.getData(.CurveToRel, 6); try t.eq(cmd.ca_x, 0); try t.eq(cmd.ca_y, 0); try t.eq(cmd.cb_x, 10.5); try t.eq(cmd.cb_y, 6.5); try t.eq(cmd.x, 13); try t.eq(cmd.y, 15); try t.eq(res.cmds[3], .CurveToRel); cmd = res.getData(.CurveToRel, 12); try t.eq(cmd.ca_x, 0); try t.eq(cmd.ca_y, 0); try t.eq(cmd.cb_x, -1.5); try t.eq(cmd.cb_y, -9); try t.eq(cmd.x, 0.5); try t.eq(cmd.y, -9); } test "PathParser.parse" { // Just check length. const path = \\M394,106c-10.2,7.3-24,12-37.7,12c-29,0-51.1-20.8-51.1-48.3c0-27.3,22.5-48.1,52-48.1 \\c14.3,0,29.2,5.5,38.9,14l-13,15c-7.1-6.3-16.8-10-25.9-10c-17,0-30.2,12.9-30.2,29.5c0,16.8,13.3,29.6,30.3,29.6 \\c5.7,0,12.8-2.3,19-5.5L394,106z ; const res = try parseSvgPath(t.alloc, path); defer res.deinit(); try t.eq(res.cmds.len, 12); } test "PathParser.parse CR/LF" { const path = "M394,106\r\nM100,100"; const res = try parseSvgPath(t.alloc, path); defer res.deinit(); } test "SvgParser.parse CR/LF" { var parser = SvgParser.init(t.alloc); defer parser.deinit(); const svg = "<svg><polygon points=\"10,10\r\n10,10\"/></svg>"; _ = try parser.parse(svg); } const SvgElement = enum { Group, Polygon, Path, Rect, }; const Attribute = struct { key: []const u8, value: ?[]const u8, }; const SvgDrawState = struct { // Empty indicates fill=none (don't do fill op) fill: ?Color, stroke: ?Color, transform: ?Transform, }; // Fast parser that just extracts draw commands from svg file. No ast returned. pub const SvgParser = struct { const Self = @This(); src: []const u8, next_ch_idx: u32, extra_data: std.ArrayList(f32), cmd_data: ds.DynamicArrayList(u32, f32), sub_cmds: std.ArrayList(u8), cmds: std.ArrayList(DrawCommandPtr), elem_map: ds.OwnedKeyStringHashMap(SvgElement), str_buf: std.ArrayList(u8), state_stack: std.ArrayList(SvgDrawState), path_parser: PathParser, // Keep track of the current colors set to determine adding FillColor/StrokeColor ops. cur_fill: ?Color, cur_stroke: ?Color, // Current transform to apply to coords. // TODO: implement transforms. We'd need to apply transform to every vertex generated. Probable solution is to // append transform commands to DrawCommandList in a way similar to setFillColor cur_transform: ?Transform, pub fn init(alloc: std.mem.Allocator) Self { var elem_map = ds.OwnedKeyStringHashMap(SvgElement).init(alloc); elem_map.put("g", .Group) catch unreachable; elem_map.put("polygon", .Polygon) catch unreachable; elem_map.put("path", .Path) catch unreachable; elem_map.put("rect", .Rect) catch unreachable; return .{ .src = undefined, .next_ch_idx = undefined, .extra_data = std.ArrayList(f32).init(alloc), .cmd_data = ds.DynamicArrayList(u32, f32).init(alloc), .cmds = std.ArrayList(DrawCommandPtr).init(alloc), .sub_cmds = std.ArrayList(u8).init(alloc), .elem_map = elem_map, .str_buf = std.ArrayList(u8).init(alloc), .state_stack = std.ArrayList(SvgDrawState).init(alloc), .cur_fill = undefined, .cur_stroke = undefined, .cur_transform = undefined, .path_parser = PathParser.init(alloc), }; } pub fn deinit(self: *Self) void { self.extra_data.deinit(); self.cmd_data.deinit(); self.sub_cmds.deinit(); self.cmds.deinit(); self.elem_map.deinit(); self.str_buf.deinit(); self.state_stack.deinit(); self.path_parser.deinit(); } pub fn parseAlloc(self: *Self, alloc: std.mem.Allocator, src: []const u8) !DrawCommandList { const res = try self.parse(src); const new_cmd_data = alloc.alloc(f32, res.cmd_data.len) catch unreachable; std.mem.copy(f32, new_cmd_data, res.cmd_data); const new_extra_data = alloc.alloc(f32, res.extra_data.len) catch unreachable; std.mem.copy(f32, new_extra_data, res.extra_data); const new_cmds = alloc.alloc(DrawCommandPtr, res.cmds.len) catch unreachable; std.mem.copy(DrawCommandPtr, new_cmds, res.cmds); const new_sub_cmds = alloc.alloc(u8, res.sub_cmds.len) catch unreachable; std.mem.copy(u8, new_sub_cmds, res.sub_cmds); return DrawCommandList{ .alloc = alloc, .extra_data = new_extra_data, .cmd_data = new_cmd_data, .cmds = new_cmds, .sub_cmds = new_sub_cmds, }; } pub fn parse(self: *Self, src: []const u8) !DrawCommandList { self.src = src; self.next_ch_idx = 0; self.extra_data.clearRetainingCapacity(); self.cmd_data.clearRetainingCapacity(); self.sub_cmds.clearRetainingCapacity(); self.cmds.clearRetainingCapacity(); self.state_stack.clearRetainingCapacity(); // Root state. self.state_stack.append(.{ .fill = Color.Black, .stroke = null, .transform = null, }) catch unreachable; self.cur_fill = null; self.cur_stroke = null; self.cur_transform = null; while (!self.nextAtEnd()) { _ = try self.parseElement(); } return DrawCommandList{ .alloc = null, .extra_data = self.extra_data.items, .cmd_data = self.cmd_data.buf.items, .cmds = self.cmds.items, .sub_cmds = self.sub_cmds.items, }; } fn parsePath(self: *Self) !void { // log.debug("parse path", .{}); while (try self.parseAttribute()) |attr| { if (stdx.string.eq(attr.key, "d")) { if (attr.value) |value| { const sub_cmd_start = self.sub_cmds.items.len; const data_start = self.extra_data.items.len; const res = try self.path_parser.parseAppend(&self.sub_cmds, &self.extra_data, value); // log.debug("path: {}cmds {s}", .{res.cmds.len, value}); const state = self.getCurrentState(); // Fill path. if (state.fill != null) { if (!std.meta.eql(state.fill, self.cur_fill)) { const ptr = self.cmd_data.append(draw_cmd.FillColorCommand{ .rgba = state.fill.?.toU32(), }) catch unreachable; self.cmds.append(.{ .tag = .FillColor, .id = ptr.id }) catch unreachable; } self.cur_fill = state.fill.?; const ptr = self.cmd_data.append(draw_cmd.FillPathCommand{ .num_cmds = @intCast(u32, res.cmds.len), .start_path_cmd_id = @intCast(u32, sub_cmd_start), .start_data_id = @intCast(u32, data_start), }) catch unreachable; self.cmds.append(.{ .tag = .FillPath, .id = ptr.id }) catch unreachable; } } } } try self.consume('/'); try self.consume('>'); } fn getCurrentState(self: *Self) SvgDrawState { return self.state_stack.items[self.state_stack.items.len - 1]; } fn parseRect(self: *Self) !void { // log.debug("parse rect", .{}); var req_fields: u4 = 0; var x: f32 = undefined; var y: f32 = undefined; var width: f32 = undefined; var height: f32 = undefined; while (try self.parseAttribute()) |attr| { // log.debug("{s}: {s}", .{attr.key, attr.value.?}); if (std.mem.eql(u8, attr.key, "x")) { if (attr.value) |value| { x = try std.fmt.parseFloat(f32, value); req_fields |= 1; } } else if (std.mem.eql(u8, attr.key, "y")) { if (attr.value) |value| { y = try std.fmt.parseFloat(f32, value); req_fields |= 1 << 1; } } else if (std.mem.eql(u8, attr.key, "width")) { if (attr.value) |value| { width = try std.fmt.parseFloat(f32, value); req_fields |= 1 << 2; } } else if (std.mem.eql(u8, attr.key, "height")) { if (attr.value) |value| { height = try std.fmt.parseFloat(f32, value); req_fields |= 1 << 3; } } } if (req_fields == (1 << 4) - 1) { const state = self.getCurrentState(); // Fill rect. if (state.fill != null) { if (!std.meta.eql(state.fill, self.cur_fill)) { const ptr = self.cmd_data.append(draw_cmd.FillColorCommand{ .rgba = state.fill.?.toU32(), }) catch unreachable; self.cmds.append(.{ .tag = .FillColor, .id = ptr.id }) catch unreachable; } self.cur_fill = state.fill.?; const ptr = self.cmd_data.append(draw_cmd.FillRectCommand{ .x = x, .y = y, .width = width, .height = height, }) catch unreachable; self.cmds.append(.{ .tag = .FillRect, .id = ptr.id }) catch unreachable; } } try self.consume('/'); try self.consume('>'); } fn parsePolygon(self: *Self) !void { // log.debug("parse polygon", .{}); while (try self.parseAttribute()) |attr| { // log.debug("{s}: {s}", .{attr.key, attr.value}); if (std.mem.eql(u8, attr.key, "points")) { if (attr.value) |value| { var iter = std.mem.tokenize(u8, value, "\r\n\t "); var num_verts: u32 = 0; const start_vert_id = @intCast(u32, self.extra_data.items.len); while (iter.next()) |pair| { const sep_idx = stdx.string.indexOf(pair, ',') orelse return error.ParseError; const x = try std.fmt.parseFloat(f32, pair[0..sep_idx]); const y = try std.fmt.parseFloat(f32, pair[sep_idx + 1 ..]); self.extra_data.appendSlice(&.{ x, y }) catch unreachable; num_verts += 1; } const state = self.getCurrentState(); // Fill polygon. if (state.fill != null) { if (!std.meta.eql(state.fill, self.cur_fill)) { const ptr = self.cmd_data.append(draw_cmd.FillColorCommand{ .rgba = state.fill.?.toU32(), }) catch unreachable; self.cmds.append(.{ .tag = .FillColor, .id = ptr.id }) catch unreachable; } self.cur_fill = state.fill.?; const ptr = self.cmd_data.append(draw_cmd.FillPolygonCommand{ .num_vertices = num_verts, .start_vertex_id = start_vert_id, }) catch unreachable; self.cmds.append(.{ .tag = .FillPolygon, .id = ptr.id }) catch unreachable; } } } } try self.consume('/'); try self.consume('>'); } fn parseFunctionLastFloatArg(self: *Self, str: []const u8, next_pos: *u32) !f32 { _ = self; const pos = next_pos.*; if (string.indexOfPos(str, pos, ')')) |end| { const res = try std.fmt.parseFloat(f32, str[pos..end]); next_pos.* = @intCast(u32, end) + 1; return res; } else { return error.ParseError; } } fn parseFunctionFloatArg(self: *Self, str: []const u8, next_pos: *u32) !f32 { _ = self; const pos = next_pos.*; if (string.indexOfPos(str, pos, ',')) |end| { const res = try std.fmt.parseFloat(f32, str[pos..end]); next_pos.* = @intCast(u32, end) + 1; return res; } else { return error.ParseError; } } // Parses from an attribute value. fn parseFunctionName(self: *Self, str: []const u8, next_pos: *u32) !?[]const u8 { _ = self; var pos = next_pos.*; if (pos == str.len) { return null; } // consume whitespace. var ch = str[pos]; while (std.ascii.isSpace(ch)) { pos += 1; if (pos == str.len) { return null; } ch = str[pos]; } const start_pos = pos; if (!std.ascii.isAlpha(ch)) { return error.ParseError; } pos += 1; while (true) { if (pos == str.len) { return error.ParseError; } ch = str[pos]; if (ch == '(') { next_pos.* = pos + 1; return str[start_pos..pos]; } pos += 1; } } // Parses until end element '>' is consumed. fn parseGroup(self: *Self) !void { // log.debug("parse group", .{}); // Need a flag to separate declaring "none" and not having a value at all. var declared_fill = false; var fill: ?Color = null; var transform: ?Transform = null; while (try self.parseAttribute()) |attr| { self.str_buf.resize(attr.key.len) catch unreachable; const lower = stdx.string.toLower(attr.key, self.str_buf.items); if (string.eq(lower, "fill")) { if (attr.value) |value| { if (stdx.string.eq(value, "none")) { fill = null; } else { const c = try Color.parse(value); fill = c; } declared_fill = true; } } else if (string.eq(lower, "transform")) { if (attr.value) |value| { var next_pos: u32 = 0; if (try self.parseFunctionName(value, &next_pos)) |name| { if (string.eq(name, "matrix")) { const m0 = try self.parseFunctionFloatArg(value, &next_pos); const m1 = try self.parseFunctionFloatArg(value, &next_pos); const m2 = try self.parseFunctionFloatArg(value, &next_pos); const m3 = try self.parseFunctionFloatArg(value, &next_pos); const m4 = try self.parseFunctionFloatArg(value, &next_pos); const m5 = try self.parseFunctionLastFloatArg(value, &next_pos); transform = Transform.initRowMajor([16]f32{ m0, m2, 0, m4, m1, m3, 0, m5, 0, 0, 1, 0, 0, 0, 0, 1, }); // log.debug("yay matrix {} {} {} {} {} {}", .{m0, m1, m2, m3, m4, m5}); // unreachable; } } } } } try self.consume('>'); var state = self.getCurrentState(); self.cur_transform = if (transform != null) transform.? else state.transform; self.state_stack.append(.{ .fill = if (declared_fill) fill else state.fill, .stroke = state.stroke, .transform = self.cur_transform, }) catch unreachable; try self.parseChildrenAndCloseTag(); _ = self.state_stack.pop(); // Need to restore cur_transform. cur_fill/cur_stroke track the current graphics state. state = self.getCurrentState(); self.cur_transform = state.transform; } fn parseAttribute(self: *Self) !?Attribute { const key = try self.parseAttributeKey(); if (key == null) return null; // log.debug("attr key: {s}", .{key.?}); try self.consume('='); try self.consume('"'); if (self.nextAtEnd()) return error.ParseError; const start_idx = self.next_ch_idx; try self.consumeUntilIncl('"'); const value = self.src[start_idx .. self.next_ch_idx - 1]; return Attribute{ .key = key.?, .value = value }; } fn consumeUntilIncl(self: *Self, ch: u8) !void { while (self.peekNext() != ch) { self.next_ch_idx += 1; if (self.nextAtEnd()) { return error.ParseError; } } self.next_ch_idx += 1; } fn consume(self: *Self, ch: u8) !void { if (self.nextAtEnd()) { return error.ParseError; } if (self.peekNext() == ch) { self.next_ch_idx += 1; } else { log.debug("Failed to consume: {c} at {}", .{ ch, self.next_ch_idx }); return error.ParseError; } } fn consumeUntilWhitespace(self: *Self) void { while (!std.ascii.isSpace(self.peekNext())) { self.next_ch_idx += 1; if (self.nextAtEnd()) { break; } } } fn consumeWhitespaces(self: *Self) void { while (std.ascii.isSpace(self.peekNext())) { self.next_ch_idx += 1; if (self.nextAtEnd()) { break; } } } fn peekNext(self: *Self) u8 { return self.src[self.next_ch_idx]; } fn hasLookahead(self: *Self, n: u32, ch: u8) bool { if (self.next_ch_idx + n < self.src.len) { return self.src[self.next_ch_idx + n] == ch; } else { return false; } } // Returns whether an element was parsed. fn parseElement(self: *Self) anyerror!bool { // log.debug("parse element", .{}); const ch = self.peekNext(); if (std.ascii.isSpace(ch)) { self.consumeWhitespaces(); } if (self.nextAtEnd()) { return false; } if (self.peekNext() == '<') { // End of a parent element. if (self.hasLookahead(1, '/')) { return false; } } else return error.ParseError; try self.consume('<'); if (self.peekNext() == '?') { // Skip xml declaration. _ = try self.consumeToTagEnd(); return true; } const name = try self.parseTagName(); // log.debug("elem name: {s}", .{name}); self.str_buf.resize(name.len) catch unreachable; if (self.elem_map.get(stdx.string.toLower(name, self.str_buf.items))) |elem| { switch (elem) { .Group => try self.parseGroup(), .Polygon => try self.parsePolygon(), .Path => try self.parsePath(), .Rect => try self.parseRect(), } return true; } else { if (self.nextAtEnd()) { return error.ParseError; } const single_elem = try self.consumeToTagEnd(); if (single_elem) { return true; } try self.parseChildrenAndCloseTag(); return true; } } fn parseChildrenAndCloseTag(self: *Self) !void { // log.debug("parse children", .{}); while (try self.parseElement()) {} // Parse close tag. if (self.nextAtEnd()) { return error.ParseError; } try self.consume('<'); try self.consume('/'); _ = try self.parseTagName(); try self.consume('>'); } // Returns whether tag is single element. fn consumeToTagEnd(self: *Self) !bool { while (true) { var ch = self.peekNext(); if (ch == '>') { self.next_ch_idx += 1; return false; } else if (ch == '/') { self.next_ch_idx += 1; if (self.nextAtEnd()) { return error.ParseError; } ch = self.peekNext(); if (ch == '>') { self.next_ch_idx += 1; return true; } } self.next_ch_idx += 1; if (self.nextAtEnd()) { return error.ParseError; } } } fn nextAtEnd(self: *Self) bool { return self.next_ch_idx == self.src.len; } fn parseAttributeKey(self: *Self) anyerror!?[]const u8 { if (self.nextAtEnd()) { return error.ParseError; } var ch = self.peekNext(); if (std.ascii.isAlpha(ch)) { const start = self.next_ch_idx; while (true) { if (ch == '=') { break; } if (std.ascii.isSpace(ch)) { return error.ParseError; } self.next_ch_idx += 1; if (self.nextAtEnd()) { return error.ParseError; } ch = self.peekNext(); } return self.src[start..self.next_ch_idx]; } else if (std.ascii.isSpace(ch)) { self.consumeWhitespaces(); return try self.parseAttributeKey(); } else { return null; } } fn parseTagName(self: *Self) ![]const u8 { if (self.nextAtEnd()) { return error.ParseError; } var ch = self.peekNext(); if (std.ascii.isSpace(ch)) { self.consumeWhitespaces(); if (self.nextAtEnd()) { return error.ParseError; } ch = self.peekNext(); } if (std.ascii.isAlpha(ch)) { const start = self.next_ch_idx; while (true) { if (std.ascii.isSpace(ch) or ch == '>') { break; } self.next_ch_idx += 1; if (self.nextAtEnd()) { break; } ch = self.peekNext(); } return self.src[start..self.next_ch_idx]; } else { log.debug("Failed to consume: {c} at {}", .{ ch, self.next_ch_idx }); return error.ParseError; } } };
graphics/src/svg.zig
usingnamespace @import("../engine/engine.zig"); const std = @import("std"); const testing = std.testing; const mem = std.mem; pub fn ReentrantContext(comptime Payload: type, comptime Value: type) type { return *Parser(Payload, Value); } /// Wraps the `input.parser`, allowing it to be reentrant (such as in the case of a left recursive /// grammar.) /// /// This has relatively small overhead (so you may use it to wrap any reentrant parser), but is /// only strictly required for reentrant parsers where invoking the parser multiple times at the /// same exact position in the input string is required to emit a different result. For example: /// /// ```ebnf /// Expr = Expr?, "abc" ; /// Grammar = Expr ; /// ``` /// /// Without a Reentrant wrapper, parsing the above Grammar would match only a singular /// `(null, abc)` match, because `Expr` is not invoked recursively. However, with a reentrant /// wrapper it would match `(((null,abc),abc),abc)` instead. /// /// The `input.parser` must remain alive for as long as the `Reentrant` parser will be used. pub fn Reentrant(comptime Payload: type, comptime Value: type) type { return struct { parser: Parser(Payload, Value) = Parser(Payload, Value).init(parse, nodeName, deinit), input: ReentrantContext(Payload, Value), const Self = @This(); pub fn init(input: ReentrantContext(Payload, Value)) Self { return Self{ .input = input }; } pub fn deinit(parser: *Parser(Payload, Value), allocator: *mem.Allocator) void { const self = @fieldParentPtr(Self, "parser", parser); self.input.deinit(allocator); } pub fn nodeName(parser: *const Parser(Payload, Value), node_name_cache: *std.AutoHashMap(usize, ParserNodeName)) Error!u64 { const self = @fieldParentPtr(Self, "parser", parser); var v = std.hash_map.hashString("Reentrant"); v +%= try self.input.nodeName(node_name_cache); return v; } pub fn parse(parser: *const Parser(Payload, Value), in_ctx: *const Context(Payload, Value)) callconv(.Async) !void { const self = @fieldParentPtr(Self, "parser", parser); var ctx = in_ctx.with(self.input); defer ctx.results.close(); // See gll_parser.zig:Memoizer.get for details on what this is doing and why. var retrying = false; var retrying_max_depth: ?usize = null; while (true) { const child_node_name = try ctx.input.nodeName(&in_ctx.memoizer.node_name_cache); const child_ctx = try in_ctx.initChildRetry(Value, child_node_name, ctx.offset, retrying_max_depth); defer child_ctx.deinitChild(); if (!child_ctx.existing_results) try ctx.input.parse(&child_ctx); var buf = try ctx.allocator.create(ResultStream(Result(Value))); defer ctx.allocator.destroy(buf); buf.* = try ResultStream(Result(Value)).init(ctx.allocator, ctx.key); defer buf.deinit(); var sub = child_ctx.subscribe(); while (sub.next()) |next| { try buf.add(next.toUnowned()); } buf.close(); if ((sub.cyclic_closed or retrying) and !child_ctx.isRetrying(child_node_name, ctx.offset)) { if (retrying and sub.cyclic_closed) { if (retrying_max_depth.? > 0) retrying_max_depth.? -= 1; retrying = false; continue; } retrying = true; if (retrying_max_depth == null) { retrying_max_depth = 0; } retrying_max_depth.? += 1; continue; } else { var sub2 = buf.subscribe(ctx.key, ctx.path, Result(Value).initError(ctx.offset, "matches only the empty language")); while (sub2.next()) |next| { try ctx.results.add(next); } break; } } } }; }
src/combn/combinator/reentrant.zig
const std = @import("std"); const web = @import("zhp"); const Request = web.Request; const Response = web.Response; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; pub const io_mode = .evented; pub const log_level = .debug; /// This handler demonstrates how to send a template resrponse using /// zig's built-in formatting. const TemplateHandler = struct { const template = @embedFile("templates/cover.html"); pub fn get(self: *TemplateHandler, req: *Request, resp: *Response) !void { _ = req; _ = self; @setEvalBranchQuota(100000); try resp.stream.print(template, .{"ZHP"}); } }; /// This handler demonstrates how to set headers and /// write to the response stream. The response stream is buffered. /// in memory until the handler completes. const HelloHandler = struct { pub fn get(self: *HelloHandler, req: *Request, resp: *Response) !void { _ = self; _ = req; try resp.headers.append("Content-Type", "text/plain"); try resp.stream.writeAll("Hello, World!"); } }; /// This handler demonstrates how to send a streaming response. /// since ZHP buffers the handler output use `send_stream = true` to tell /// it to invoke the stream method to complete the response. const StreamHandler = struct { const template = @embedFile("templates/stream.html"); allocator: ?*std.mem.Allocator = null, pub fn get(self: *StreamHandler, req: *Request, resp: *Response) !void { if (std.mem.eql(u8, req.path, "/stream/live/")) { try resp.headers.append("Content-Type", "audio/mpeg"); try resp.headers.append("Cache-Control", "no-cache"); // This tells the framework to invoke stream fn after sending the // headers resp.send_stream = true; self.allocator = resp.allocator; } else { try resp.stream.writeAll(template); } } pub fn stream(self: *StreamHandler, io: *web.IOStream) !usize { std.log.info("Starting audio stream", .{}); const n = self.forward(io) catch |err| { std.log.info("Error streaming: {s}", .{err}); return 0; }; return n; } fn forward(self: *StreamHandler, io: *web.IOStream) !usize { const writer = io.writer(); std.debug.assert(self.allocator != null); const a = self.allocator.?; // http://streams.sevenfm.nl/live std.log.info("Connecting...", .{}); const conn = try std.net.tcpConnectToHost(a, "streams.sevenfm.nl", 80); defer conn.close(); std.log.info("Connected!", .{}); try conn.writer().writeAll("GET /live HTTP/1.1\r\n" ++ "Host: streams.sevenfm.nl\r\n" ++ "Accept: */*\r\n" ++ "Connection: keep-alive\r\n" ++ "\r\n"); var buf: [4096]u8 = undefined; var total_sent: usize = 0; // On the first response skip their server's headers // but include the icecast stream headers from their response const end = try conn.read(buf[0..]); const offset = if (std.mem.indexOf(u8, buf[0..end], "icy-br:")) |o| o else 0; try writer.writeAll(buf[offset..end]); total_sent += end - offset; // Now just forward the stream data while (true) { const n = try conn.read(buf[0..]); if (n == 0) { std.log.info("Stream disconnected", .{}); break; } total_sent += n; try writer.writeAll(buf[0..n]); try io.flush(); // Send it out the pipe } return total_sent; } }; /// This handler shows how to read headers and cookies from the request. /// It also shows another way to write to the response stream. /// Finally it shows one way to use "static" storage that persists between /// requests. const JsonHandler = struct { // Static storage var counter = std.atomic.Atomic(usize).init(0); pub fn get(self: *JsonHandler, req: *Request, resp: *Response) !void { _ = self; _ = req; try resp.headers.append("Content-Type", "application/json"); var jw = std.json.writeStream(resp.stream, 4); try jw.beginObject(); for (req.headers.headers.items) |h| { try jw.objectField(h.key); try jw.emitString(h.value); } // Cookies aren't parsed by default // If you know they're parsed (eg by middleware) you can just // use request.cookies directly if (try req.readCookies()) |cookies| { try jw.objectField("Cookie"); try jw.beginObject(); for (cookies.cookies.items) |c| { try jw.objectField(c.key); try jw.emitString(c.value); } try jw.endObject(); } try jw.objectField("Request-Count"); try jw.emitNumber(counter.fetchAdd(1, .Monotonic)); try jw.endObject(); } }; /// This handler demonstrates how to use url arguments. The /// `request.args` is the result of ctregex's parsing of the url. const ApiHandler = struct { pub fn get(self: *ApiHandler, req: *Request, resp: *Response) !void { _ = self; try resp.headers.append("Content-Type", "application/json"); var jw = std.json.writeStream(resp.stream, 4); try jw.beginObject(); const args = req.args.?; try jw.objectField(args[0].?); try jw.emitString(args[1].?); try jw.endObject(); } }; /// When an error is returned the framework will return the error handler response const ErrorTestHandler = struct { pub fn get(self: *ErrorTestHandler, req: *Request, resp: *Response) !void { _ = self; _ = req; try resp.stream.writeAll("Do some work"); return error.Ooops; } }; /// Redirect shortcut const RedirectHandler = struct { // Shows how to redirect pub fn get(self: *RedirectHandler, req: *Request, resp: *Response) !void { _ = self; _ = req; // Redirect to home try resp.redirect("/"); } }; /// Work in progress... shows one way to render and post a form. const FormHandler = struct { const template = @embedFile("templates/form.html"); const key = "{% form %}"; const start = std.mem.indexOf(u8, template, key).?; const end = start + key.len; pub fn get(self: *FormHandler, req: *Request, resp: *Response) !void { _ = self; _ = req; // Split the template on the key const form = \\<form action="/form/" method="post" enctype="multipart/form-data"> \\<input type="text" name="name" value="Your name"><br /> \\<input type="checkbox" name="agree" /><label>Do you like Zig?</label><br /> \\<input type="file" name="image" /><label>Upload</label><br /> \\<button type="submit">Submit</button> \\</form> ; try resp.stream.writeAll(template[0..start]); try resp.stream.writeAll(form); try resp.stream.writeAll(template[end..]); } pub fn post(self: *FormHandler, req: *Request, resp: *Response) !void { _ = self; var content_type = req.headers.getDefault("Content-Type", ""); if (std.mem.startsWith(u8, content_type, "multipart/form-data")) { var form = web.forms.Form.init(resp.allocator); form.parse(req) catch |err| switch (err) { error.NotImplemented => { resp.status = web.responses.REQUEST_ENTITY_TOO_LARGE; try resp.stream.writeAll("TODO: Handle large uploads"); return; }, else => return err, }; try resp.stream.writeAll(template[0..start]); try resp.stream.print( \\<h1>Hello: {s}</h1> , .{if (form.fields.get("name")) |name| name else ""}); if (form.fields.get("agree")) |_| { try resp.stream.writeAll("Me too!"); } else { try resp.stream.writeAll("Aww sorry!"); } try resp.stream.writeAll(template[end..]); } else { resp.status = web.responses.BAD_REQUEST; } } }; const ChatHandler = struct { const template = @embedFile("templates/chat.html"); pub fn get(self: *ChatHandler, req: *Request, resp: *Response) !void { _ = self; _ = req; try resp.stream.writeAll(template); } }; /// Demonstrates the useage of the websocket protocol const ChatWebsocketHandler = struct { var client_id = std.atomic.Atomic(usize).init(0); var chat_handlers = std.ArrayList(*ChatWebsocketHandler).init(&gpa.allocator); websocket: web.Websocket, stream: ?web.websocket.Writer(1024, .Text) = null, username: []const u8 = "", pub fn selectProtocol(req: *Request, resp: *Response) !void { _ = req; try resp.headers.append("Sec-WebSocket-Protocol", "json"); } pub fn connected(self: *ChatWebsocketHandler) !void { std.log.debug("Websocket connected!", .{}); // Initialze the stream self.stream = self.websocket.writer(1024, .Text); const stream = &self.stream.?; var jw = std.json.writeStream(stream.writer(), 4); try jw.beginObject(); try jw.objectField("type"); try jw.emitString("id"); try jw.objectField("id"); try jw.emitNumber(client_id.fetchAdd(1, .Monotonic)); try jw.objectField("date"); try jw.emitNumber(std.time.milliTimestamp()); try jw.endObject(); try stream.flush(); try chat_handlers.append(self); } pub fn onMessage(self: *ChatWebsocketHandler, message: []const u8, binary: bool) !void { _ = binary; std.log.debug("Websocket message: {s}", .{message}); const allocator = self.websocket.response.allocator; var parser = std.json.Parser.init(allocator, false); defer parser.deinit(); var obj = try parser.parse(message); defer obj.deinit(); const msg = obj.root.Object; const t = msg.get("type").?.String; if (std.mem.eql(u8, t, "message")) { try self.sendMessage(self.username, msg.get("text").?.String); } else if (std.mem.eql(u8, t, "username")) { self.username = try std.mem.dupe(allocator, u8, msg.get("name").?.String); try self.sendUserList(); } } pub fn sendUserList(self: *ChatWebsocketHandler) !void { _ = self; const t = std.time.milliTimestamp(); for (chat_handlers.items) |handler| { const stream = &handler.stream.?; var jw = std.json.writeStream(stream.writer(), 4); try jw.beginObject(); try jw.objectField("type"); try jw.emitString("userlist"); try jw.objectField("users"); try jw.beginArray(); for (chat_handlers.items) |obj| { try jw.arrayElem(); try jw.emitString(obj.username); } try jw.endArray(); try jw.objectField("date"); try jw.emitNumber(t); try jw.endObject(); try stream.flush(); } } pub fn sendMessage(self: *ChatWebsocketHandler, name: []const u8, message: []const u8) !void { _ = self; const t = std.time.milliTimestamp(); for (chat_handlers.items) |handler| { const stream = &handler.stream.?; var jw = std.json.writeStream(stream.writer(), 4); try jw.beginObject(); try jw.objectField("type"); try jw.emitString("message"); try jw.objectField("text"); try jw.emitString(message); try jw.objectField("name"); try jw.emitString(name); try jw.objectField("date"); try jw.emitNumber(t); try jw.endObject(); try stream.flush(); } } pub fn disconnected(self: *ChatWebsocketHandler) !void { if (self.websocket.err) |err| { std.log.debug("Websocket error: {s}", .{err}); } else { std.log.debug("Websocket closed!", .{}); } for (chat_handlers.items) |handler, i| { if (handler == self) { _ = chat_handlers.swapRemove(i); break; } } } }; // The routes must be defined in the "root" pub const routes = [_]web.Route{ web.Route.create("cover", "/", TemplateHandler), web.Route.create("hello", "/hello", HelloHandler), web.Route.create("api", "/api/([a-z]+)/(\\d+)/", ApiHandler), web.Route.create("json", "/json/", JsonHandler), web.Route.create("stream", "/stream/", StreamHandler), web.Route.create("stream-media", "/stream/live/", StreamHandler), web.Route.create("redirect", "/redirect/", RedirectHandler), web.Route.create("error", "/500/", ErrorTestHandler), web.Route.create("form", "/form/", FormHandler), web.Route.create("chat", "/chat/", ChatHandler), web.Route.websocket("websocket", "/chat/ws/", ChatWebsocketHandler), web.Route.static("static", "/static/", "example/static/"), }; pub const middleware = [_]web.Middleware{ web.Middleware.create(web.middleware.LoggingMiddleware), //web.Middleware.create(web.middleware.SessionMiddleware), }; pub fn main() !void { defer std.debug.assert(!gpa.deinit()); const allocator = &gpa.allocator; var app = web.Application.init(allocator, .{ .debug = true }); defer app.deinit(); try app.listen("127.0.0.1", 9000); try app.start(); }
example/main.zig
const std = @import("std"); const mem = std.mem; const DefaultIgnorableCodePoint = @This(); allocator: *mem.Allocator, array: []bool, lo: u21 = 173, hi: u21 = 921599, pub fn init(allocator: *mem.Allocator) !DefaultIgnorableCodePoint { var instance = DefaultIgnorableCodePoint{ .allocator = allocator, .array = try allocator.alloc(bool, 921427), }; mem.set(bool, instance.array, false); var index: u21 = 0; instance.array[0] = true; instance.array[674] = true; instance.array[1391] = true; index = 4274; while (index <= 4275) : (index += 1) { instance.array[index] = true; } index = 5895; while (index <= 5896) : (index += 1) { instance.array[index] = true; } index = 5982; while (index <= 5984) : (index += 1) { instance.array[index] = true; } instance.array[5985] = true; index = 8030; while (index <= 8034) : (index += 1) { instance.array[index] = true; } index = 8061; while (index <= 8065) : (index += 1) { instance.array[index] = true; } index = 8115; while (index <= 8119) : (index += 1) { instance.array[index] = true; } instance.array[8120] = true; index = 8121; while (index <= 8130) : (index += 1) { instance.array[index] = true; } instance.array[12471] = true; index = 64851; while (index <= 64866) : (index += 1) { instance.array[index] = true; } instance.array[65106] = true; instance.array[65267] = true; index = 65347; while (index <= 65355) : (index += 1) { instance.array[index] = true; } index = 113651; while (index <= 113654) : (index += 1) { instance.array[index] = true; } index = 118982; while (index <= 118989) : (index += 1) { instance.array[index] = true; } instance.array[917331] = true; instance.array[917332] = true; index = 917333; while (index <= 917362) : (index += 1) { instance.array[index] = true; } index = 917363; while (index <= 917458) : (index += 1) { instance.array[index] = true; } index = 917459; while (index <= 917586) : (index += 1) { instance.array[index] = true; } index = 917587; while (index <= 917826) : (index += 1) { instance.array[index] = true; } index = 917827; while (index <= 921426) : (index += 1) { instance.array[index] = true; } // Placeholder: 0. Struct name, 1. Code point kind return instance; } pub fn deinit(self: *DefaultIgnorableCodePoint) void { self.allocator.free(self.array); } // isDefaultIgnorableCodePoint checks if cp is of the kind Default_Ignorable_Code_Point. pub fn isDefaultIgnorableCodePoint(self: DefaultIgnorableCodePoint, cp: u21) bool { if (cp < self.lo or cp > self.hi) return false; const index = cp - self.lo; return if (index >= self.array.len) false else self.array[index]; }
src/components/autogen/DerivedCoreProperties/DefaultIgnorableCodePoint.zig
const std = @import("std"); const utils = @import("../utils.zig"); pub const CompressionMethod = enum(u16) { none = 0, shrunk, reduced1, reduced2, reduced3, reduced4, imploded, deflated = 8, enhanced_deflated, dcl_imploded, bzip2 = 12, lzma = 14, ibm_terse = 18, ibm_lz77_z, zstd_deprecated, zstd = 93, mp3, xz, jepg, wavpack, ppmd_1_1, aex_encryption, pub fn read(self: *CompressionMethod, reader: anytype) !void { const data = try reader.readIntLittle(u16); self.* = @intToEnum(CompressionMethod, data); } pub fn write(self: CompressionMethod, writer: anytype) !void { const data = @enumToInt(self); try writer.writeIntLittle(u16, data); } }; pub const Version = struct { pub const Vendor = enum(u8) { dos = 0, amiga, openvms, unix, vm, atari, os2_hpfs, macintosh, z_system, cp_m, ntfs, mvs, vse, acorn, vfat, alt_mvs, beos, tandem, os400, osx, _, }; vendor: Vendor, major: u8, minor: u8, pub fn read(self: *Version, reader: anytype) !void { const data = try reader.readIntLittle(u16); self.major = @truncate(u8, data) / 10; self.minor = @truncate(u8, data) % 10; self.vendor = @intToEnum(Vendor, @truncate(u8, data >> 8)); } pub fn write(self: Version, writer: anytype) !void { const version = @as(u16, self.major * 10 + self.minor); const vendor = @as(u16, @enumToInt(self.vendor)) << 8; try writer.writeIntLittle(u16, version | vendor); } }; pub const GeneralPurposeBitFlag = packed struct { encrypted: bool, compression1: u1, compression2: u1, data_descriptor: bool, enhanced_deflation: u1, compressed_patched: bool, strong_encryption: bool, __7_reserved: u1, __8_reserved: u1, __9_reserved: u1, __10_reserved: u1, is_utf8: bool, __12_reserved: u1, mask_headers: bool, __14_reserved: u1, __15_reserved: u1, pub fn read(self: *GeneralPurposeBitFlag, reader: anytype) !void { const data = try reader.readIntLittle(u16); self.* = @bitCast(GeneralPurposeBitFlag, data); } pub fn write(self: GeneralPurposeBitFlag, writer: anytype) !void { const data = @bitCast(u16, self); try writer.writeIntLittle(u16, data); } }; pub const InternalAttributes = packed struct { apparent_text: bool, __1_reserved: u1, control_before_logical: bool, __3_7_reserved: u5, __8_15_reserved: u8, pub fn read(self: *InternalAttributes, reader: anytype) !void { const data = try reader.readIntLittle(u16); self.* = @bitCast(GeneralPurposeBitFlag, data); } pub fn write(self: InternalAttributes, writer: anytype) !void { const data = @bitCast(u16, self); try writer.writeIntLittle(u16, data); } }; pub const DosTimestamp = struct { second: u6, minute: u6, hour: u5, day: u5, month: u4, year: u12, pub fn read(self: *DosTimestamp, reader: anytype) !void { const time = try reader.readIntLittle(u16); self.second = @as(u6, @truncate(u5, time)) << 1; self.minute = @truncate(u6, time >> 5); self.hour = @truncate(u5, time >> 11); const date = try reader.readIntLittle(u16); self.day = @truncate(u5, date); self.month = @truncate(u4, date >> 5); self.year = @as(u12, @truncate(u7, date >> 9)) + 1980; } pub fn write(self: DosTimestamp, writer: anytype) !void { const second = @as(u16, @truncate(u5, self.second >> 1)); const minute = @as(u16, @truncate(u5, self.minute) << 5); const hour = @as(u16, @truncate(u5, self.hour) << 11); try writer.writeIntLittle(u16, second | minute | hour); const day = self.day; const month = self.month << 5; const year = (self.year - 1980) << 11; try writer.writeIntLittle(u16, day | month | year); } }; pub const LocalFileHeader = struct { pub const Signature = 0x04034b50; pub const size = 26; version_needed: Version, flags: GeneralPurposeBitFlag, compression: CompressionMethod, mtime: DosTimestamp, checksum: u32, compressed_size: u64, uncompressed_size: u64, filename_len: u16, extrafield_len: u16, central_header: *const CentralDirectoryHeader, data_descriptor: ?DataDescriptor, offset: usize, const ReadError = error{ MalformedLocalFileHeader, MultidiskUnsupported }; pub fn read(self: *LocalFileHeader, central_header: *const CentralDirectoryHeader, seeker: anytype, reader: anytype) !void { const Seek = Seeker(@TypeOf(seeker)); try self.version_needed.read(reader); try self.flags.read(reader); try self.compression.read(reader); try self.mtime.read(reader); self.checksum = try reader.readIntLittle(u32); self.compressed_size = try reader.readIntLittle(u32); self.uncompressed_size = try reader.readIntLittle(u32); self.filename_len = try reader.readIntLittle(u16); self.extrafield_len = try reader.readIntLittle(u16); self.offset = central_header.offset + 30 + self.filename_len + self.extrafield_len; self.central_header = central_header; if (self.filename_len != central_header.filename_len) return error.MalformedLocalFileHeader; try Seek.seekBy(seeker, reader.context, @intCast(i64, self.filename_len)); var is_zip64 = false; var extra_read: u32 = 0; const needs_uncompressed_size = self.uncompressed_size == 0xFFFFFFFF; const needs_compressed_size = self.compressed_size == 0xFFFFFFFF; const required_zip64_size = (@as(u5, @boolToInt(needs_uncompressed_size)) + @as(u5, @boolToInt(needs_compressed_size))) * 8; while (extra_read < self.extrafield_len) { const field_id = try reader.readIntLittle(u16); const field_size = try reader.readIntLittle(u16); extra_read += 4; if (field_id == 0x0001) { if (field_size < required_zip64_size) return error.MalformedExtraField; if (needs_uncompressed_size) self.uncompressed_size = try reader.readIntLittle(u64); if (needs_compressed_size) self.compressed_size = try reader.readIntLittle(u64); extra_read += required_zip64_size; try Seek.seekBy(seeker, reader.context, field_size - required_zip64_size); break; } else { try Seek.seekBy(seeker, reader.context, field_size); extra_read += field_size; } } const left = self.extrafield_len - extra_read; if (self.flags.data_descriptor) { try Seek.seekBy(seeker, reader.context, @intCast(i64, left + self.compressed_size)); self.data_descriptor = @as(DataDescriptor, undefined); try self.data_descriptor.?.read(reader, is_zip64); } } }; pub const DataDescriptor = struct { pub const Signature = 0x04034b50; pub const size = 12; checksum: u64, compressed_size: u64, uncompressed_size: u64, pub fn read(self: *DataDescriptor, reader: anytype, zip64: bool) !void { const signature = try reader.readIntLittle(u32); if (signature == DataDescriptor.Signature) { if (zip64) { self.checksum = try reader.readIntLittle(u64); self.compressed_size = try reader.readIntLittle(u64); self.uncompressed_size = try reader.readIntLittle(u64); } else { self.checksum = try reader.readIntLittle(u32); self.compressed_size = try reader.readIntLittle(u32); self.uncompressed_size = try reader.readIntLittle(u32); } } else { if (zip64) { const next_u32 = try reader.readIntLittle(u32); self.checksum = @as(u64, next_u32) << 32 | signature; self.compressed_size = try reader.readIntLittle(u64); self.uncompressed_size = try reader.readIntLittle(u64); } else { self.checksum = signature; self.compressed_size = try reader.readIntLittle(u32); self.uncompressed_size = try reader.readIntLittle(u32); } } } }; pub const CentralDirectoryHeader = struct { pub const Signature = 0x02014b50; pub const size = 42; version_made: Version, version_needed: Version, flags: GeneralPurposeBitFlag, compression: CompressionMethod, mtime: DosTimestamp, checksum: u32, compressed_size: u64, uncompressed_size: u64, disk_start: u16, internal_attributes: InternalAttributes, external_attributes: u32, offset: u64, filename_len: u16, extrafield_len: u16, file_comment_len: u16, filename: []const u8, local_header: LocalFileHeader, pub fn readInitial(self: *CentralDirectoryHeader, reader: anytype) !void { try self.version_made.read(reader); try self.version_needed.read(reader); try self.flags.read(reader); try self.compression.read(reader); try self.mtime.read(reader); self.checksum = try reader.readIntLittle(u32); self.compressed_size = try reader.readIntLittle(u32); self.uncompressed_size = try reader.readIntLittle(u32); self.filename_len = try reader.readIntLittle(u16); self.extrafield_len = try reader.readIntLittle(u16); self.file_comment_len = try reader.readIntLittle(u16); self.disk_start = try reader.readIntLittle(u16); try self.internal_attributes.read(reader); self.external_attributes = try reader.readIntLittle(u32); self.offset = try reader.readIntLittle(u32); } const ReadSecondaryError = error{MalformedExtraField}; pub fn readSecondary(self: *CentralDirectoryHeader, seeker: anytype, reader: anytype) !void { const Seek = Seeker(@TypeOf(seeker)); const needs_uncompressed_size = self.uncompressed_size == 0xFFFFFFFF; const needs_compressed_size = self.compressed_size == 0xFFFFFFFF; const needs_header_offset = self.offset == 0xFFFFFFFF; const required_zip64_size = (@as(u5, @boolToInt(needs_uncompressed_size)) + @as(u5, @boolToInt(needs_compressed_size)) + @as(u5, @boolToInt(needs_header_offset))) * 8; const needs_zip64 = needs_uncompressed_size or needs_compressed_size or needs_header_offset; if (needs_zip64) { var read: usize = 0; while (read < self.extrafield_len) { const field_id = try reader.readIntLittle(u16); const field_size = try reader.readIntLittle(u16); read += 4; if (field_id == 0x0001) { if (field_size < required_zip64_size) return error.MalformedExtraField; if (needs_uncompressed_size) self.uncompressed_size = try reader.readIntLittle(u64); if (needs_compressed_size) self.compressed_size = try reader.readIntLittle(u64); if (needs_header_offset) self.offset = try reader.readIntLittle(u64); read += required_zip64_size; break; } else { try Seek.seekBy(seeker, reader.context, field_size); read += field_size; } } const left = self.extrafield_len - read; try Seek.seekBy(seeker, reader.context, @intCast(i64, self.file_comment_len + left)); } else { try Seek.seekBy(seeker, reader.context, @intCast(i64, self.extrafield_len + self.file_comment_len)); } } }; pub const EndCentralDirectory64Record = struct { pub const Signature = 0x06064b50; pub const size = 52; record_size: u64, version_made: Version, version_needed: Version, disk_number: u32, disk_start_directory: u32, disk_directory_entries: u64, directory_entry_count: u64, directory_size: u64, directory_offset: u64, pub fn parse(self: *EndCentralDirectory64Record, reader: anytype) (@TypeOf(reader).Error || error{EndOfStream})!void { self.record_size = try reader.readIntLittle(u64); try self.version_made.read(reader); try self.version_needed.read(reader); self.disk_number = try reader.readIntLittle(u32); self.disk_start_directory = try reader.readIntLittle(u32); self.disk_directory_entries = try reader.readIntLittle(u64); self.directory_entry_count = try reader.readIntLittle(u64); self.directory_size = try reader.readIntLittle(u64); self.directory_offset = try reader.readIntLittle(u64); } }; pub const EndCentralDirectory64Locator = struct { pub const Signature = 0x07064b50; pub const size = 16; directory_disk_number: u32, directory_offset: u64, number_of_disks: u32, pub fn parse(self: *EndCentralDirectory64Locator, reader: anytype) (@TypeOf(reader).Error || error{EndOfStream})!void { self.directory_disk_number = try reader.readIntLittle(u32); self.directory_offset = try reader.readIntLittle(u64); self.number_of_disks = try reader.readIntLittle(u32); } }; pub const EndCentralDirectoryRecord = struct { pub const Signature = 0x06054b50; pub const size = 18; disk_number: u16, disk_start_directory: u16, disk_directory_entries: u16, directory_entry_count: u16, directory_size: u32, directory_offset: u32, comment_length: u16, pub fn parse(self: *EndCentralDirectoryRecord, reader: anytype) (@TypeOf(reader).Error || error{EndOfStream})!void { self.disk_number = try reader.readIntLittle(u16); self.disk_start_directory = try reader.readIntLittle(u16); self.disk_directory_entries = try reader.readIntLittle(u16); self.directory_entry_count = try reader.readIntLittle(u16); self.directory_size = try reader.readIntLittle(u32); self.directory_offset = try reader.readIntLittle(u32); self.comment_length = try reader.readIntLittle(u16); } }; /// Finds and read's the ZIP central directory and local headers. pub fn LoadError(comptime Reader: type) type { return ReadInfoError(Reader) || ReadDirectoryError(Reader); } pub fn load(allocator: *std.mem.Allocator, reader: anytype) LoadError(@TypeOf(reader))!Directory { const info = try readInfo(reader); return try readDirectory(allocator, reader, info); } pub const Info = struct { is_zip64: bool, ecd: EndCentralDirectoryRecord, ecd64: EndCentralDirectory64Record, start_offset: u64, directory_offset: u64, num_entries: u32, }; pub fn ReadInfoError(comptime Reader: type) type { return Reader.Error || Seeker(Reader).Context.SeekError || error{ EndOfStream, FileTooSmall, InvalidZip, InvalidZip64Locator, MultidiskUnsupported, TooManyFiles }; } pub fn readInfo(reader: anytype) ReadInfoError(@TypeOf(reader))!Info { const file_length = try reader.context.getEndPos(); const minimum_ecdr_offset: u64 = EndCentralDirectoryRecord.size + 4; const maximum_ecdr_offset: u64 = EndCentralDirectoryRecord.size + 4 + 0xffff; if (file_length < minimum_ecdr_offset) return error.FileTooSmall; // Find the ECDR signature with a broad pass. var pos = file_length - minimum_ecdr_offset; var last_pos = if (maximum_ecdr_offset > file_length) file_length else file_length - maximum_ecdr_offset; var buffer: [4096]u8 = undefined; find: while (pos > 0) { try reader.context.seekTo(pos); const read = try reader.readAll(&buffer); if (read == 0) return error.InvalidZip; var i: usize = 0; while (i < read - 4) : (i += 1) { if (std.mem.readIntLittle(u32, buffer[i..][0..4]) == EndCentralDirectoryRecord.Signature) { pos = pos + i; try reader.context.seekTo(pos + 4); break :find; } } if (pos < 4096 or pos < last_pos) return error.InvalidZip; pos -= 4096; } var self: Info = undefined; try self.ecd.parse(reader); if (pos > EndCentralDirectory64Locator.size + EndCentralDirectory64Record.size + 8) { const locator_pos = pos - EndCentralDirectory64Locator.size - 4; try reader.context.seekTo(locator_pos); var locator: EndCentralDirectory64Locator = undefined; const locator_sig = try reader.readIntLittle(u32); if (locator_sig == EndCentralDirectory64Locator.Signature) { try locator.parse(reader); if (locator.directory_offset > file_length - EndCentralDirectory64Record.size - 4) return error.InvalidZip64Locator; try reader.context.seekTo(locator.directory_offset); const ecd64_sig = try reader.readIntLittle(u32); if (ecd64_sig == EndCentralDirectory64Record.Signature) { try self.ecd64.parse(reader); self.is_zip64 = true; } } } self.num_entries = self.ecd.directory_entry_count; self.directory_offset = self.ecd.directory_offset; var directory_size: u64 = self.ecd.directory_size; if (self.ecd.disk_number != self.ecd.disk_start_directory) return error.MultidiskUnsupported; if (self.ecd.disk_directory_entries != self.ecd.directory_entry_count) return error.MultidiskUnsupported; // Sanity checks if (self.is_zip64) { if (self.ecd64.disk_number != self.ecd64.disk_start_directory) return error.MultidiskUnsupported; if (self.ecd64.disk_directory_entries != self.ecd64.directory_entry_count) return error.MultidiskUnsupported; if (self.ecd64.directory_entry_count > std.math.maxInt(u32)) return error.TooManyFiles; self.num_entries = @truncate(u32, self.ecd64.directory_entry_count); self.directory_offset = self.ecd64.directory_offset; directory_size = self.ecd64.directory_size; } // Gets the start of the actual ZIP. // This is required because ZIPs can have preambles for self-execution, for example // so they could actually start anywhere in the file. self.start_offset = pos - self.ecd.directory_size - self.directory_offset; return self; } fn centralHeaderLessThan(_: void, lhs: CentralDirectoryHeader, rhs: CentralDirectoryHeader) bool { return lhs.offset < rhs.offset; } pub fn ReadDirectoryError(comptime Reader: type) type { return std.mem.Allocator.Error || Reader.Error || Seeker(Reader).Context.SeekError || CentralDirectoryHeader.ReadSecondaryError || error{ EndOfStream, MalformedCentralDirectoryHeader, MultidiskUnsupported, MalformedLocalFileHeader }; } pub fn readDirectory(allocator: *std.mem.Allocator, reader: anytype, info: Info) ReadDirectoryError(@TypeOf(reader))!Directory { const Seek = Seeker(@TypeOf(reader)); var headers = try std.ArrayListUnmanaged(CentralDirectoryHeader).initCapacity(allocator, info.num_entries); errdefer headers.deinit(allocator); var index: u32 = 0; try reader.context.seekTo(info.start_offset + info.directory_offset); var buffered = Seek.BufferedReader{ .unbuffered_reader = reader }; const buffered_reader = buffered.reader(); var filename_len_total: usize = 0; while (index < info.num_entries) : (index += 1) { const sig = try buffered_reader.readIntLittle(u32); if (sig != CentralDirectoryHeader.Signature) return error.MalformedCentralDirectoryHeader; var hdr = headers.addOneAssumeCapacity(); try hdr.readInitial(buffered_reader); if (hdr.disk_start != info.ecd.disk_number) return error.MultidiskUnsupported; try Seek.seekBy(reader, buffered_reader.context, @intCast(i64, hdr.filename_len + hdr.extrafield_len + hdr.file_comment_len)); filename_len_total += hdr.filename_len; } var filename_buffer = try std.ArrayListUnmanaged(u8).initCapacity(allocator, filename_len_total); errdefer filename_buffer.deinit(allocator); try Seek.seekTo(reader, buffered_reader.context, info.start_offset + info.directory_offset); for (headers.items) |*hdr| { try Seek.seekBy(reader, buffered_reader.context, 46); hdr.filename = try readFilename(&filename_buffer, buffered_reader, hdr.filename_len); try hdr.readSecondary(reader, buffered_reader); } std.sort.sort(CentralDirectoryHeader, headers.items, {}, centralHeaderLessThan); for (headers.items) |*hdr| { try Seek.seekTo(reader, buffered_reader.context, info.start_offset + hdr.offset); const signature = try buffered_reader.readIntLittle(u32); if (signature != LocalFileHeader.Signature) return error.MalformedLocalFileHeader; try hdr.local_header.read(hdr, reader, buffered_reader); } return Directory { .start_offset = info.start_offset, .headers = headers.toOwnedSlice(allocator), .filename_buffer = filename_buffer.toOwnedSlice(allocator), }; } pub const Directory = struct { start_offset: u64, headers: []CentralDirectoryHeader, filename_buffer: []u8, pub fn deinit(self: Directory, allocator: *std.mem.Allocator) void { allocator.free(self.headers); allocator.free(self.filename_buffer); } pub fn getFileIndex(self: Directory, filename: []const u8) !usize { for (self.directory.items) |*hdr, i| { if (std.mem.eql(u8, hdr.filename, filename)) { return i; } } return error.FileNotFound; } pub fn readFileAlloc(self: Directory, reader: anytype, allocator: *std.mem.Allocator, index: usize) ![]const u8 { const Seek = Seeker(@TypeOf(reader)); const header = self.headers.items[index]; reader.context.seekTo(self.start_offset + header.local_header.offset); var buffer = try allocator.alloc(u8, header.uncompressed_size); errdefer allocator.free(buffer); var read_buffered = Seek.BufferedReader{ .unbuffered_reader = reader }; var limited = utils.LimitedReader(Seek.BufferedReader.Reader).init(read_buffered.reader(), header.compressed_size); const limited_reader = limited.reader(); var write_stream = std.io.fixedBufferStream(buffer); const writer = write_stream.writer(); var fifo = std.fifo.LinearFifo(u8, .{ .Static = 8192 }).init(); switch (header.compression) { .none => { try fifo.pump(limited_reader, writer); }, .deflated => { var window: [0x8000]u8 = undefined; var stream = std.compress.deflate.inflateStream(limited_reader, &window); try fifo.pump(stream.reader(), writer); }, else => return error.CompressionUnsupported, } return buffer; } pub const ExtractOptions = struct { skip_components: u16 = 0, }; pub fn extract(self: Directory, reader: anytype, dir: std.fs.Dir, options: ExtractOptions) !usize { const Seek = Seeker(@TypeOf(reader)); var buffered = Seek.BufferedReader{ .unbuffered_reader = reader }; const file_reader = buffered.reader(); var written: usize = 0; extract: for (self.headers) |hdr| { const new_filename = blk: { var component: usize = 0; var last_pos: usize = 0; while (component < options.skip_components) : (component += 1) { last_pos = std.mem.indexOfPos(u8, hdr.filename, last_pos, "/") orelse continue :extract; } if (last_pos + 1 == hdr.filename_len) continue :extract; break :blk if (hdr.filename[last_pos] == '/') hdr.filename[last_pos + 1 ..] else hdr.filename[last_pos..]; }; if (std.fs.path.dirnamePosix(new_filename)) |dirname| { try dir.makePath(dirname); } if (new_filename[new_filename.len - 1] == '/') continue; const fd = try dir.createFile(new_filename, .{}); defer fd.close(); try Seek.seekTo(reader, file_reader.context, self.start_offset + hdr.local_header.offset); var limited = utils.LimitedReader(Seek.BufferedReader.Reader).init(file_reader, hdr.compressed_size); const limited_reader = limited.reader(); var fifo = std.fifo.LinearFifo(u8, .{ .Static = 8192 }).init(); written += hdr.uncompressed_size; switch (hdr.compression) { .none => { try fifo.pump(limited_reader, fd.writer()); }, .deflated => { var window: [0x8000]u8 = undefined; var stream = std.compress.deflate.inflateStream(limited_reader, &window); try fifo.pump(stream.reader(), fd.writer()); }, else => return error.CompressionUnsupported, } } return written; } /// Returns a file tree of this ZIP archive. /// Useful for plucking specific files out of a ZIP or listing it's contents. pub fn getFileTree(self: Directory, allocator: *std.mem.Allocator) !FileTree { var tree = FileTree{}; try tree.entries.ensureTotalCapacity(allocator, @intCast(u32, self.headers.len)); errdefer tree.entries.deinit(allocator); for (self.headers) |*hdr| { try tree.appendFile(allocator, hdr); } return tree; } }; fn readFilename(filename_buffer: *std.ArrayListUnmanaged(u8), reader: anytype, len: usize) ![]const u8 { const prev_len = filename_buffer.items.len; filename_buffer.items.len += len; var buf = filename_buffer.items[prev_len..][0..len]; const read = try reader.readAll(buf); if (read != len) return error.EndOfStream; return buf; } fn Seeker(comptime Reader: type) type { return struct { pub const Context = std.meta.fieldInfo(Reader, .context).field_type; comptime { const is_seekable = @hasDecl(Context, "seekBy") and @hasDecl(Context, "seekTo") and @hasDecl(Context, "getEndPos"); if (!is_seekable) @compileError("Reader must wrap a seekable context"); } pub const BufferedReader = std.io.BufferedReader(8192, Reader); pub fn seekBy(reader: Reader, buffered: *BufferedReader, offset: i64) !void { if (offset == 0) return; if (offset > 0) { const u_offset = @intCast(u64, offset); if (u_offset <= buffered.fifo.count) { buffered.fifo.discard(u_offset); } else if (u_offset <= buffered.fifo.count + buffered.fifo.buf.len) { const left = u_offset - buffered.fifo.count; buffered.fifo.discard(buffered.fifo.count); try buffered.reader().skipBytes(left, .{ .buf_size = 8192 }); } else { const left = u_offset - buffered.fifo.count; buffered.fifo.discard(buffered.fifo.count); try reader.context.seekBy(@intCast(i64, left)); } } else { const left = offset - @intCast(i64, buffered.fifo.count); buffered.fifo.discard(buffered.fifo.count); try reader.context.seekBy(left); } } pub fn getPos(reader: Reader, buffered: *BufferedReader) !u64 { const pos = try reader.context.getPos(); return pos - buffered.fifo.count; } pub fn seekTo(reader: Reader, buffered: *BufferedReader, pos: u64) !void { const offset = @intCast(i64, pos) - @intCast(i64, try getPos(reader, buffered)); try seekBy(reader, buffered, offset); } }; } // High-level constructs pub const FileTree = struct { entries: std.StringHashMapUnmanaged(*const CentralDirectoryHeader) = .{}, structure: std.StringHashMapUnmanaged(std.ArrayListUnmanaged(*const CentralDirectoryHeader)) = .{}, pub fn appendFile(self: *FileTree, allocator: *std.mem.Allocator, hdr: *const CentralDirectoryHeader) !void { // Determines the end of filename. If the filename is a directory, skip the last character as it is an extraenous `/`, else do nothing. var filename_end_index = hdr.filename.len - if (hdr.filename[hdr.filename.len - 1] == '/') @as(usize, 1) else @as(usize, 0); var start = if (std.mem.lastIndexOf(u8, hdr.filename[0..filename_end_index], "/")) |ind| hdr.filename[0..ind] else "/"; var gpr = try self.structure.getOrPut(allocator, start); if (!gpr.found_existing) gpr.value_ptr.* = std.ArrayListUnmanaged(*const CentralDirectoryHeader){}; try gpr.value_ptr.append(allocator, hdr); try self.entries.put(allocator, hdr.filename, hdr); } pub fn deinit(self: *FileTree, allocator: *std.mem.Allocator) void { self.entries.deinit(allocator); var it = self.structure.valueIterator(); while (it.next()) |entry| { entry.deinit(allocator); } self.structure.deinit(allocator); } pub fn readDir(self: FileTree, path: []const u8) ?*std.ArrayListUnmanaged(*const CentralDirectoryHeader) { return if (self.structure.getEntry(path)) |ent| ent.value_ptr else null; } pub fn getEntry(self: FileTree, path: []const u8) ?*const CentralDirectoryHeader { return self.entries.get(path); } }; comptime { std.testing.refAllDecls(@This()); }
src/formats/zip.zig
pub const GNSS_DRIVER_VERSION_1 = @as(u32, 1); pub const GNSS_DRIVER_VERSION_2 = @as(u32, 2); pub const GNSS_DRIVER_VERSION_3 = @as(u32, 3); pub const GNSS_DRIVER_VERSION_4 = @as(u32, 4); pub const GNSS_DRIVER_VERSION_5 = @as(u32, 5); pub const GNSS_DRIVER_VERSION_6 = @as(u32, 6); pub const IOCTL_GNSS_SEND_PLATFORM_CAPABILITY = @as(u32, 2228228); pub const IOCTL_GNSS_GET_DEVICE_CAPABILITY = @as(u32, 2228232); pub const IOCTL_GNSS_SEND_DRIVERCOMMAND = @as(u32, 2228236); pub const IOCTL_GNSS_START_FIXSESSION = @as(u32, 2228288); pub const IOCTL_GNSS_MODIFY_FIXSESSION = @as(u32, 2228292); pub const IOCTL_GNSS_STOP_FIXSESSION = @as(u32, 2228296); pub const IOCTL_GNSS_GET_FIXDATA = @as(u32, 2228300); pub const IOCTL_GNSS_INJECT_AGNSS = @as(u32, 2228352); pub const IOCTL_GNSS_LISTEN_AGNSS = @as(u32, 2228416); pub const IOCTL_GNSS_LISTEN_ERROR = @as(u32, 2228420); pub const IOCTL_GNSS_LISTEN_NI = @as(u32, 2228480); pub const IOCTL_GNSS_SET_SUPL_HSLP = @as(u32, 2228484); pub const IOCTL_GNSS_CONFIG_SUPL_CERT = @as(u32, 2228488); pub const IOCTL_GNSS_RESPOND_NI = @as(u32, 2228492); pub const IOCTL_GNSS_EXECUTE_CWTEST = @as(u32, 2228496); pub const IOCTL_GNSS_EXECUTE_SELFTEST = @as(u32, 2228500); pub const IOCTL_GNSS_GET_CHIPSETINFO = @as(u32, 2228504); pub const IOCTL_GNSS_LISTEN_NMEA = @as(u32, 2228508); pub const IOCTL_GNSS_SET_V2UPL_CONFIG = @as(u32, 2228512); pub const IOCTL_GNSS_CREATE_GEOFENCE = @as(u32, 2228544); pub const IOCTL_GNSS_DELETE_GEOFENCE = @as(u32, 2228548); pub const IOCTL_GNSS_LISTEN_GEOFENCE_ALERT = @as(u32, 2228552); pub const IOCTL_GNSS_LISTEN_GEOFENCES_TRACKINGSTATUS = @as(u32, 2228556); pub const IOCTL_GNSS_LISTEN_DRIVER_REQUEST = @as(u32, 2228608); pub const IOCTL_GNSS_START_BREADCRUMBING = @as(u32, 2228672); pub const IOCTL_GNSS_STOP_BREADCRUMBING = @as(u32, 2228676); pub const IOCTL_GNSS_LISTEN_BREADCRUMBING_ALERT = @as(u32, 2228680); pub const IOCTL_GNSS_POP_BREADCRUMBS = @as(u32, 2228684); pub const GNSS_AGNSSFORMAT_XTRA1 = @as(u32, 1); pub const GNSS_AGNSSFORMAT_XTRA2 = @as(u32, 2); pub const GNSS_AGNSSFORMAT_LTO = @as(u32, 4); pub const GNSS_AGNSSFORMAT_XTRA3 = @as(u32, 8); pub const GNSS_AGNSSFORMAT_XTRA3_1 = @as(u32, 16); pub const GNSS_AGNSSFORMAT_XTRA3_2 = @as(u32, 32); pub const GNSS_AGNSSFORMAT_XTRA_INT = @as(u32, 64); pub const MAX_SERVER_URL_NAME = @as(u32, 260); pub const MIN_GEOFENCES_REQUIRED = @as(u32, 100); pub const BREADCRUMBING_UNSUPPORTED = @as(u32, 0); pub const BREADCRUMBING_VERSION_1 = @as(u32, 1); pub const MIN_BREADCRUMBS_SUPPORTED = @as(u32, 120); pub const GNSS_SATELLITE_ANY = @as(u32, 0); pub const GNSS_SATELLITE_GPS = @as(u32, 1); pub const GNSS_SATELLITE_GLONASS = @as(u32, 2); pub const GNSS_SATELLITE_BEIDOU = @as(u32, 4); pub const GNSS_SATELLITE_GALILEO = @as(u32, 8); pub const GNSS_OPERMODE_ANY = @as(u32, 0); pub const GNSS_OPERMODE_MSA = @as(u32, 1); pub const GNSS_OPERMODE_MSB = @as(u32, 2); pub const GNSS_OPERMODE_MSS = @as(u32, 4); pub const GNSS_OPERMODE_CELLID = @as(u32, 8); pub const GNSS_OPERMODE_AFLT = @as(u32, 16); pub const GNSS_OPERMODE_OTDOA = @as(u32, 32); pub const GNSS_NMEALOGGING_NONE = @as(u32, 0); pub const GNSS_NMEALOGGING_ALL = @as(u32, 255); pub const GNSS_FIXDETAIL_BASIC = @as(u32, 1); pub const GNSS_FIXDETAIL_ACCURACY = @as(u32, 2); pub const GNSS_FIXDETAIL_SATELLITE = @as(u32, 4); pub const GNSS_MAXSATELLITE = @as(u32, 64); pub const GNSS_GEOFENCESUPPORT_SUPPORTED = @as(u32, 1); pub const GNSS_GEOFENCESUPPORT_CIRCLE = @as(u32, 2); pub const LOCATION_API_VERSION = @as(u32, 1); pub const GUID_DEVINTERFACE_GNSS = Guid.initString("3336e5e4-018a-4669-84c5-bd05f3bd368b"); //-------------------------------------------------------------------------------- // Section: Types (87) //-------------------------------------------------------------------------------- const CLSID_Location_Value = Guid.initString("e5b8e079-ee6d-4e33-a438-c87f2e959254"); pub const CLSID_Location = &CLSID_Location_Value; const CLSID_DefaultLocation_Value = Guid.initString("8b7fbfe0-5cd7-494a-af8c-283a65707506"); pub const CLSID_DefaultLocation = &CLSID_DefaultLocation_Value; const CLSID_LatLongReport_Value = Guid.initString("ed81c073-1f84-4ca8-a161-183c776bc651"); pub const CLSID_LatLongReport = &CLSID_LatLongReport_Value; const CLSID_CivicAddressReport_Value = Guid.initString("d39e7bdd-7d05-46b8-8721-80cf035f57d7"); pub const CLSID_CivicAddressReport = &CLSID_CivicAddressReport_Value; const CLSID_LatLongReportFactory_Value = Guid.initString("9dcc3cc8-8609-4863-bad4-03601f4c65e8"); pub const CLSID_LatLongReportFactory = &CLSID_LatLongReportFactory_Value; const CLSID_CivicAddressReportFactory_Value = Guid.initString("2a11f42c-3e81-4ad4-9cbe-45579d89671a"); pub const CLSID_CivicAddressReportFactory = &CLSID_CivicAddressReportFactory_Value; const CLSID_DispLatLongReport_Value = Guid.initString("7a7c3277-8f84-4636-95b2-ebb5507ff77e"); pub const CLSID_DispLatLongReport = &CLSID_DispLatLongReport_Value; const CLSID_DispCivicAddressReport_Value = Guid.initString("4c596aec-8544-4082-ba9f-eb0a7d8e65c6"); pub const CLSID_DispCivicAddressReport = &CLSID_DispCivicAddressReport_Value; pub const LOCATION_REPORT_STATUS = enum(i32) { NOT_SUPPORTED = 0, ERROR = 1, ACCESS_DENIED = 2, INITIALIZING = 3, RUNNING = 4, }; pub const REPORT_NOT_SUPPORTED = LOCATION_REPORT_STATUS.NOT_SUPPORTED; pub const REPORT_ERROR = LOCATION_REPORT_STATUS.ERROR; pub const REPORT_ACCESS_DENIED = LOCATION_REPORT_STATUS.ACCESS_DENIED; pub const REPORT_INITIALIZING = LOCATION_REPORT_STATUS.INITIALIZING; pub const REPORT_RUNNING = LOCATION_REPORT_STATUS.RUNNING; // TODO: this type is limited to platform 'windows6.1' const IID_ILocationReport_Value = Guid.initString("c8b7f7ee-75d0-4db9-b62d-7a0f369ca456"); pub const IID_ILocationReport = &IID_ILocationReport_Value; pub const ILocationReport = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetSensorID: fn( self: *const ILocationReport, pSensorID: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTimestamp: fn( self: *const ILocationReport, pCreationTime: ?*SYSTEMTIME, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetValue: fn( self: *const ILocationReport, pKey: ?*const PROPERTYKEY, pValue: ?*PROPVARIANT, ) 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 ILocationReport_GetSensorID(self: *const T, pSensorID: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationReport.VTable, self.vtable).GetSensorID(@ptrCast(*const ILocationReport, self), pSensorID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocationReport_GetTimestamp(self: *const T, pCreationTime: ?*SYSTEMTIME) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationReport.VTable, self.vtable).GetTimestamp(@ptrCast(*const ILocationReport, self), pCreationTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocationReport_GetValue(self: *const T, pKey: ?*const PROPERTYKEY, pValue: ?*PROPVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationReport.VTable, self.vtable).GetValue(@ptrCast(*const ILocationReport, self), pKey, pValue); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_ILatLongReport_Value = Guid.initString("7fed806d-0ef8-4f07-80ac-36a0beae3134"); pub const IID_ILatLongReport = &IID_ILatLongReport_Value; pub const ILatLongReport = extern struct { pub const VTable = extern struct { base: ILocationReport.VTable, GetLatitude: fn( self: *const ILatLongReport, pLatitude: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLongitude: fn( self: *const ILatLongReport, pLongitude: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetErrorRadius: fn( self: *const ILatLongReport, pErrorRadius: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAltitude: fn( self: *const ILatLongReport, pAltitude: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAltitudeError: fn( self: *const ILatLongReport, pAltitudeError: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ILocationReport.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILatLongReport_GetLatitude(self: *const T, pLatitude: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const ILatLongReport.VTable, self.vtable).GetLatitude(@ptrCast(*const ILatLongReport, self), pLatitude); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILatLongReport_GetLongitude(self: *const T, pLongitude: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const ILatLongReport.VTable, self.vtable).GetLongitude(@ptrCast(*const ILatLongReport, self), pLongitude); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILatLongReport_GetErrorRadius(self: *const T, pErrorRadius: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const ILatLongReport.VTable, self.vtable).GetErrorRadius(@ptrCast(*const ILatLongReport, self), pErrorRadius); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILatLongReport_GetAltitude(self: *const T, pAltitude: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const ILatLongReport.VTable, self.vtable).GetAltitude(@ptrCast(*const ILatLongReport, self), pAltitude); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILatLongReport_GetAltitudeError(self: *const T, pAltitudeError: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const ILatLongReport.VTable, self.vtable).GetAltitudeError(@ptrCast(*const ILatLongReport, self), pAltitudeError); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_ICivicAddressReport_Value = Guid.initString("c0b19f70-4adf-445d-87f2-cad8fd711792"); pub const IID_ICivicAddressReport = &IID_ICivicAddressReport_Value; pub const ICivicAddressReport = extern struct { pub const VTable = extern struct { base: ILocationReport.VTable, GetAddressLine1: fn( self: *const ICivicAddressReport, pbstrAddress1: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAddressLine2: fn( self: *const ICivicAddressReport, pbstrAddress2: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCity: fn( self: *const ICivicAddressReport, pbstrCity: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStateProvince: fn( self: *const ICivicAddressReport, pbstrStateProvince: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPostalCode: fn( self: *const ICivicAddressReport, pbstrPostalCode: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCountryRegion: fn( self: *const ICivicAddressReport, pbstrCountryRegion: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDetailLevel: fn( self: *const ICivicAddressReport, pDetailLevel: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ILocationReport.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICivicAddressReport_GetAddressLine1(self: *const T, pbstrAddress1: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICivicAddressReport.VTable, self.vtable).GetAddressLine1(@ptrCast(*const ICivicAddressReport, self), pbstrAddress1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICivicAddressReport_GetAddressLine2(self: *const T, pbstrAddress2: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICivicAddressReport.VTable, self.vtable).GetAddressLine2(@ptrCast(*const ICivicAddressReport, self), pbstrAddress2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICivicAddressReport_GetCity(self: *const T, pbstrCity: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICivicAddressReport.VTable, self.vtable).GetCity(@ptrCast(*const ICivicAddressReport, self), pbstrCity); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICivicAddressReport_GetStateProvince(self: *const T, pbstrStateProvince: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICivicAddressReport.VTable, self.vtable).GetStateProvince(@ptrCast(*const ICivicAddressReport, self), pbstrStateProvince); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICivicAddressReport_GetPostalCode(self: *const T, pbstrPostalCode: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICivicAddressReport.VTable, self.vtable).GetPostalCode(@ptrCast(*const ICivicAddressReport, self), pbstrPostalCode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICivicAddressReport_GetCountryRegion(self: *const T, pbstrCountryRegion: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICivicAddressReport.VTable, self.vtable).GetCountryRegion(@ptrCast(*const ICivicAddressReport, self), pbstrCountryRegion); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICivicAddressReport_GetDetailLevel(self: *const T, pDetailLevel: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ICivicAddressReport.VTable, self.vtable).GetDetailLevel(@ptrCast(*const ICivicAddressReport, self), pDetailLevel); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_ILocation_Value = Guid.initString("ab2ece69-56d9-4f28-b525-de1b0ee44237"); pub const IID_ILocation = &IID_ILocation_Value; pub const ILocation = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, RegisterForReport: fn( self: *const ILocation, pEvents: ?*ILocationEvents, reportType: ?*const Guid, dwRequestedReportInterval: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnregisterForReport: fn( self: *const ILocation, reportType: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetReport: fn( self: *const ILocation, reportType: ?*const Guid, ppLocationReport: ?*?*ILocationReport, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetReportStatus: fn( self: *const ILocation, reportType: ?*const Guid, pStatus: ?*LOCATION_REPORT_STATUS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetReportInterval: fn( self: *const ILocation, reportType: ?*const Guid, pMilliseconds: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetReportInterval: fn( self: *const ILocation, reportType: ?*const Guid, millisecondsRequested: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDesiredAccuracy: fn( self: *const ILocation, reportType: ?*const Guid, pDesiredAccuracy: ?*LOCATION_DESIRED_ACCURACY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDesiredAccuracy: fn( self: *const ILocation, reportType: ?*const Guid, desiredAccuracy: LOCATION_DESIRED_ACCURACY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RequestPermissions: fn( self: *const ILocation, hParent: ?HWND, pReportTypes: [*]Guid, count: u32, fModal: BOOL, ) 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 ILocation_RegisterForReport(self: *const T, pEvents: ?*ILocationEvents, reportType: ?*const Guid, dwRequestedReportInterval: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ILocation.VTable, self.vtable).RegisterForReport(@ptrCast(*const ILocation, self), pEvents, reportType, dwRequestedReportInterval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocation_UnregisterForReport(self: *const T, reportType: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ILocation.VTable, self.vtable).UnregisterForReport(@ptrCast(*const ILocation, self), reportType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocation_GetReport(self: *const T, reportType: ?*const Guid, ppLocationReport: ?*?*ILocationReport) callconv(.Inline) HRESULT { return @ptrCast(*const ILocation.VTable, self.vtable).GetReport(@ptrCast(*const ILocation, self), reportType, ppLocationReport); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocation_GetReportStatus(self: *const T, reportType: ?*const Guid, pStatus: ?*LOCATION_REPORT_STATUS) callconv(.Inline) HRESULT { return @ptrCast(*const ILocation.VTable, self.vtable).GetReportStatus(@ptrCast(*const ILocation, self), reportType, pStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocation_GetReportInterval(self: *const T, reportType: ?*const Guid, pMilliseconds: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ILocation.VTable, self.vtable).GetReportInterval(@ptrCast(*const ILocation, self), reportType, pMilliseconds); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocation_SetReportInterval(self: *const T, reportType: ?*const Guid, millisecondsRequested: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ILocation.VTable, self.vtable).SetReportInterval(@ptrCast(*const ILocation, self), reportType, millisecondsRequested); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocation_GetDesiredAccuracy(self: *const T, reportType: ?*const Guid, pDesiredAccuracy: ?*LOCATION_DESIRED_ACCURACY) callconv(.Inline) HRESULT { return @ptrCast(*const ILocation.VTable, self.vtable).GetDesiredAccuracy(@ptrCast(*const ILocation, self), reportType, pDesiredAccuracy); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocation_SetDesiredAccuracy(self: *const T, reportType: ?*const Guid, desiredAccuracy: LOCATION_DESIRED_ACCURACY) callconv(.Inline) HRESULT { return @ptrCast(*const ILocation.VTable, self.vtable).SetDesiredAccuracy(@ptrCast(*const ILocation, self), reportType, desiredAccuracy); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocation_RequestPermissions(self: *const T, hParent: ?HWND, pReportTypes: [*]Guid, count: u32, fModal: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ILocation.VTable, self.vtable).RequestPermissions(@ptrCast(*const ILocation, self), hParent, pReportTypes, count, fModal); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.0' const IID_ILocationPower_Value = Guid.initString("193e7729-ab6b-4b12-8617-7596e1bb191c"); pub const IID_ILocationPower = &IID_ILocationPower_Value; pub const ILocationPower = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Connect: fn( self: *const ILocationPower, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Disconnect: fn( self: *const ILocationPower, ) 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 ILocationPower_Connect(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationPower.VTable, self.vtable).Connect(@ptrCast(*const ILocationPower, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocationPower_Disconnect(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationPower.VTable, self.vtable).Disconnect(@ptrCast(*const ILocationPower, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IDefaultLocation_Value = Guid.initString("a65af77e-969a-4a2e-8aca-33bb7cbb1235"); pub const IID_IDefaultLocation = &IID_IDefaultLocation_Value; pub const IDefaultLocation = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetReport: fn( self: *const IDefaultLocation, reportType: ?*const Guid, pLocationReport: ?*ILocationReport, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetReport: fn( self: *const IDefaultLocation, reportType: ?*const Guid, ppLocationReport: ?*?*ILocationReport, ) 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 IDefaultLocation_SetReport(self: *const T, reportType: ?*const Guid, pLocationReport: ?*ILocationReport) callconv(.Inline) HRESULT { return @ptrCast(*const IDefaultLocation.VTable, self.vtable).SetReport(@ptrCast(*const IDefaultLocation, self), reportType, pLocationReport); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDefaultLocation_GetReport(self: *const T, reportType: ?*const Guid, ppLocationReport: ?*?*ILocationReport) callconv(.Inline) HRESULT { return @ptrCast(*const IDefaultLocation.VTable, self.vtable).GetReport(@ptrCast(*const IDefaultLocation, self), reportType, ppLocationReport); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_ILocationEvents_Value = Guid.initString("cae02bbf-798b-4508-a207-35a7906dc73d"); pub const IID_ILocationEvents = &IID_ILocationEvents_Value; pub const ILocationEvents = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnLocationChanged: fn( self: *const ILocationEvents, reportType: ?*const Guid, pLocationReport: ?*ILocationReport, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnStatusChanged: fn( self: *const ILocationEvents, reportType: ?*const Guid, newStatus: LOCATION_REPORT_STATUS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocationEvents_OnLocationChanged(self: *const T, reportType: ?*const Guid, pLocationReport: ?*ILocationReport) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationEvents.VTable, self.vtable).OnLocationChanged(@ptrCast(*const ILocationEvents, self), reportType, pLocationReport); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocationEvents_OnStatusChanged(self: *const T, reportType: ?*const Guid, newStatus: LOCATION_REPORT_STATUS) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationEvents.VTable, self.vtable).OnStatusChanged(@ptrCast(*const ILocationEvents, self), reportType, newStatus); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDispLatLongReport_Value = Guid.initString("8ae32723-389b-4a11-9957-5bdd48fc9617"); pub const IID_IDispLatLongReport = &IID_IDispLatLongReport_Value; pub const IDispLatLongReport = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Latitude: fn( self: *const IDispLatLongReport, pVal: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Longitude: fn( self: *const IDispLatLongReport, pVal: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ErrorRadius: fn( self: *const IDispLatLongReport, pVal: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Altitude: fn( self: *const IDispLatLongReport, pVal: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AltitudeError: fn( self: *const IDispLatLongReport, pVal: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Timestamp: fn( self: *const IDispLatLongReport, pVal: ?*f64, ) 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 IDispLatLongReport_get_Latitude(self: *const T, pVal: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IDispLatLongReport.VTable, self.vtable).get_Latitude(@ptrCast(*const IDispLatLongReport, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispLatLongReport_get_Longitude(self: *const T, pVal: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IDispLatLongReport.VTable, self.vtable).get_Longitude(@ptrCast(*const IDispLatLongReport, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispLatLongReport_get_ErrorRadius(self: *const T, pVal: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IDispLatLongReport.VTable, self.vtable).get_ErrorRadius(@ptrCast(*const IDispLatLongReport, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispLatLongReport_get_Altitude(self: *const T, pVal: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IDispLatLongReport.VTable, self.vtable).get_Altitude(@ptrCast(*const IDispLatLongReport, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispLatLongReport_get_AltitudeError(self: *const T, pVal: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IDispLatLongReport.VTable, self.vtable).get_AltitudeError(@ptrCast(*const IDispLatLongReport, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispLatLongReport_get_Timestamp(self: *const T, pVal: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IDispLatLongReport.VTable, self.vtable).get_Timestamp(@ptrCast(*const IDispLatLongReport, self), pVal); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDispCivicAddressReport_Value = Guid.initString("16ff1a34-9e30-42c3-b44d-e22513b5767a"); pub const IID_IDispCivicAddressReport = &IID_IDispCivicAddressReport_Value; pub const IDispCivicAddressReport = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AddressLine1: fn( self: *const IDispCivicAddressReport, pAddress1: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AddressLine2: fn( self: *const IDispCivicAddressReport, pAddress2: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_City: fn( self: *const IDispCivicAddressReport, pCity: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_StateProvince: fn( self: *const IDispCivicAddressReport, pStateProvince: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PostalCode: fn( self: *const IDispCivicAddressReport, pPostalCode: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_CountryRegion: fn( self: *const IDispCivicAddressReport, pCountryRegion: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DetailLevel: fn( self: *const IDispCivicAddressReport, pDetailLevel: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Timestamp: fn( self: *const IDispCivicAddressReport, pVal: ?*f64, ) 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 IDispCivicAddressReport_get_AddressLine1(self: *const T, pAddress1: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDispCivicAddressReport.VTable, self.vtable).get_AddressLine1(@ptrCast(*const IDispCivicAddressReport, self), pAddress1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispCivicAddressReport_get_AddressLine2(self: *const T, pAddress2: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDispCivicAddressReport.VTable, self.vtable).get_AddressLine2(@ptrCast(*const IDispCivicAddressReport, self), pAddress2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispCivicAddressReport_get_City(self: *const T, pCity: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDispCivicAddressReport.VTable, self.vtable).get_City(@ptrCast(*const IDispCivicAddressReport, self), pCity); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispCivicAddressReport_get_StateProvince(self: *const T, pStateProvince: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDispCivicAddressReport.VTable, self.vtable).get_StateProvince(@ptrCast(*const IDispCivicAddressReport, self), pStateProvince); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispCivicAddressReport_get_PostalCode(self: *const T, pPostalCode: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDispCivicAddressReport.VTable, self.vtable).get_PostalCode(@ptrCast(*const IDispCivicAddressReport, self), pPostalCode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispCivicAddressReport_get_CountryRegion(self: *const T, pCountryRegion: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDispCivicAddressReport.VTable, self.vtable).get_CountryRegion(@ptrCast(*const IDispCivicAddressReport, self), pCountryRegion); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispCivicAddressReport_get_DetailLevel(self: *const T, pDetailLevel: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDispCivicAddressReport.VTable, self.vtable).get_DetailLevel(@ptrCast(*const IDispCivicAddressReport, self), pDetailLevel); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispCivicAddressReport_get_Timestamp(self: *const T, pVal: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IDispCivicAddressReport.VTable, self.vtable).get_Timestamp(@ptrCast(*const IDispCivicAddressReport, self), pVal); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ILocationReportFactory_Value = Guid.initString("2daec322-90b2-47e4-bb08-0da841935a6b"); pub const IID_ILocationReportFactory = &IID_ILocationReportFactory_Value; pub const ILocationReportFactory = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, ListenForReports: fn( self: *const ILocationReportFactory, requestedReportInterval: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, StopListeningForReports: fn( self: *const ILocationReportFactory, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Status: fn( self: *const ILocationReportFactory, pVal: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ReportInterval: fn( self: *const ILocationReportFactory, pMilliseconds: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ReportInterval: fn( self: *const ILocationReportFactory, millisecondsRequested: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DesiredAccuracy: fn( self: *const ILocationReportFactory, pDesiredAccuracy: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DesiredAccuracy: fn( self: *const ILocationReportFactory, desiredAccuracy: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RequestPermissions: fn( self: *const ILocationReportFactory, hWnd: ?*u32, ) 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 ILocationReportFactory_ListenForReports(self: *const T, requestedReportInterval: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationReportFactory.VTable, self.vtable).ListenForReports(@ptrCast(*const ILocationReportFactory, self), requestedReportInterval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocationReportFactory_StopListeningForReports(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationReportFactory.VTable, self.vtable).StopListeningForReports(@ptrCast(*const ILocationReportFactory, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocationReportFactory_get_Status(self: *const T, pVal: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationReportFactory.VTable, self.vtable).get_Status(@ptrCast(*const ILocationReportFactory, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocationReportFactory_get_ReportInterval(self: *const T, pMilliseconds: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationReportFactory.VTable, self.vtable).get_ReportInterval(@ptrCast(*const ILocationReportFactory, self), pMilliseconds); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocationReportFactory_put_ReportInterval(self: *const T, millisecondsRequested: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationReportFactory.VTable, self.vtable).put_ReportInterval(@ptrCast(*const ILocationReportFactory, self), millisecondsRequested); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocationReportFactory_get_DesiredAccuracy(self: *const T, pDesiredAccuracy: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationReportFactory.VTable, self.vtable).get_DesiredAccuracy(@ptrCast(*const ILocationReportFactory, self), pDesiredAccuracy); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocationReportFactory_put_DesiredAccuracy(self: *const T, desiredAccuracy: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationReportFactory.VTable, self.vtable).put_DesiredAccuracy(@ptrCast(*const ILocationReportFactory, self), desiredAccuracy); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocationReportFactory_RequestPermissions(self: *const T, hWnd: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationReportFactory.VTable, self.vtable).RequestPermissions(@ptrCast(*const ILocationReportFactory, self), hWnd); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ILatLongReportFactory_Value = Guid.initString("3f0804cb-b114-447d-83dd-390174ebb082"); pub const IID_ILatLongReportFactory = &IID_ILatLongReportFactory_Value; pub const ILatLongReportFactory = extern struct { pub const VTable = extern struct { base: ILocationReportFactory.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LatLongReport: fn( self: *const ILatLongReportFactory, pVal: ?*?*IDispLatLongReport, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ILocationReportFactory.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILatLongReportFactory_get_LatLongReport(self: *const T, pVal: ?*?*IDispLatLongReport) callconv(.Inline) HRESULT { return @ptrCast(*const ILatLongReportFactory.VTable, self.vtable).get_LatLongReport(@ptrCast(*const ILatLongReportFactory, self), pVal); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ICivicAddressReportFactory_Value = Guid.initString("bf773b93-c64f-4bee-beb2-67c0b8df66e0"); pub const IID_ICivicAddressReportFactory = &IID_ICivicAddressReportFactory_Value; pub const ICivicAddressReportFactory = extern struct { pub const VTable = extern struct { base: ILocationReportFactory.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_CivicAddressReport: fn( self: *const ICivicAddressReportFactory, pVal: ?*?*IDispCivicAddressReport, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ILocationReportFactory.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICivicAddressReportFactory_get_CivicAddressReport(self: *const T, pVal: ?*?*IDispCivicAddressReport) callconv(.Inline) HRESULT { return @ptrCast(*const ICivicAddressReportFactory.VTable, self.vtable).get_CivicAddressReport(@ptrCast(*const ICivicAddressReportFactory, self), pVal); } };} pub usingnamespace MethodMixin(@This()); }; const IID__ILatLongReportFactoryEvents_Value = Guid.initString("16ee6cb7-ab3c-424b-849f-269be551fcbc"); pub const IID__ILatLongReportFactoryEvents = &IID__ILatLongReportFactoryEvents_Value; pub const _ILatLongReportFactoryEvents = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; const IID__ICivicAddressReportFactoryEvents_Value = Guid.initString("c96039ff-72ec-4617-89bd-84d88bedc722"); pub const IID__ICivicAddressReportFactoryEvents = &IID__ICivicAddressReportFactoryEvents_Value; pub const _ICivicAddressReportFactoryEvents = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; pub const GNSS_SUPL_VERSION = extern struct { MajorVersion: u32, MinorVersion: u32, }; pub const GNSS_SUPL_VERSION_2 = extern struct { MajorVersion: u32, MinorVersion: u32, ServiceIndicator: u32, }; pub const GNSS_DEVICE_CAPABILITY = extern struct { Size: u32, Version: u32, SupportMultipleFixSessions: BOOL, SupportMultipleAppSessions: BOOL, RequireAGnssInjection: BOOL, AgnssFormatSupported: u32, AgnssFormatPreferred: u32, SupportDistanceTracking: BOOL, SupportContinuousTracking: BOOL, Reserved1: u32, Reserved2: BOOL, Reserved3: BOOL, Reserved4: BOOL, Reserved5: BOOL, GeofencingSupport: u32, Reserved6: BOOL, Reserved7: BOOL, SupportCpLocation: BOOL, SupportUplV2: BOOL, SupportSuplV1: BOOL, SupportSuplV2: BOOL, SupportedSuplVersion: GNSS_SUPL_VERSION, MaxGeofencesSupported: u32, SupportMultipleSuplRootCert: BOOL, GnssBreadCrumbPayloadVersion: u32, MaxGnssBreadCrumbFixes: u32, Unused: [496]u8, }; pub const GNSS_PLATFORM_CAPABILITY = extern struct { Size: u32, Version: u32, SupportAgnssInjection: BOOL, AgnssFormatSupported: u32, Unused: [516]u8, }; pub const GNSS_DRIVERCOMMAND_TYPE = enum(i32) { SetLocationServiceEnabled = 1, SetLocationNIRequestAllowed = 2, ForceSatelliteSystem = 3, ForceOperationMode = 4, ResetEngine = 9, ClearAgnssData = 10, SetSuplVersion = 12, SetNMEALogging = 13, SetUplServerAccessInterval = 14, SetNiTimeoutInterval = 15, ResetGeofencesTracking = 16, SetSuplVersion2 = 17, CustomCommand = 256, }; pub const GNSS_SetLocationServiceEnabled = GNSS_DRIVERCOMMAND_TYPE.SetLocationServiceEnabled; pub const GNSS_SetLocationNIRequestAllowed = GNSS_DRIVERCOMMAND_TYPE.SetLocationNIRequestAllowed; pub const GNSS_ForceSatelliteSystem = GNSS_DRIVERCOMMAND_TYPE.ForceSatelliteSystem; pub const GNSS_ForceOperationMode = GNSS_DRIVERCOMMAND_TYPE.ForceOperationMode; pub const GNSS_ResetEngine = GNSS_DRIVERCOMMAND_TYPE.ResetEngine; pub const GNSS_ClearAgnssData = GNSS_DRIVERCOMMAND_TYPE.ClearAgnssData; pub const GNSS_SetSuplVersion = GNSS_DRIVERCOMMAND_TYPE.SetSuplVersion; pub const GNSS_SetNMEALogging = GNSS_DRIVERCOMMAND_TYPE.SetNMEALogging; pub const GNSS_SetUplServerAccessInterval = GNSS_DRIVERCOMMAND_TYPE.SetUplServerAccessInterval; pub const GNSS_SetNiTimeoutInterval = GNSS_DRIVERCOMMAND_TYPE.SetNiTimeoutInterval; pub const GNSS_ResetGeofencesTracking = GNSS_DRIVERCOMMAND_TYPE.ResetGeofencesTracking; pub const GNSS_SetSuplVersion2 = GNSS_DRIVERCOMMAND_TYPE.SetSuplVersion2; pub const GNSS_CustomCommand = GNSS_DRIVERCOMMAND_TYPE.CustomCommand; pub const GNSS_DRIVERCOMMAND_PARAM = extern struct { Size: u32, Version: u32, CommandType: GNSS_DRIVERCOMMAND_TYPE, Reserved: u32, CommandDataSize: u32, Unused: [512]u8, CommandData: [1]u8, }; pub const GNSS_FIXSESSIONTYPE = enum(i32) { SingleShot = 1, DistanceTracking = 2, ContinuousTracking = 3, LKG = 4, }; pub const GNSS_FixSession_SingleShot = GNSS_FIXSESSIONTYPE.SingleShot; pub const GNSS_FixSession_DistanceTracking = GNSS_FIXSESSIONTYPE.DistanceTracking; pub const GNSS_FixSession_ContinuousTracking = GNSS_FIXSESSIONTYPE.ContinuousTracking; pub const GNSS_FixSession_LKG = GNSS_FIXSESSIONTYPE.LKG; pub const GNSS_SINGLESHOT_PARAM = extern struct { Size: u32, Version: u32, ResponseTime: u32, }; pub const GNSS_DISTANCETRACKING_PARAM = extern struct { Size: u32, Version: u32, MovementThreshold: u32, }; pub const GNSS_CONTINUOUSTRACKING_PARAM = extern struct { Size: u32, Version: u32, PreferredInterval: u32, }; pub const GNSS_LKGFIX_PARAM = extern struct { Size: u32, Version: u32, }; pub const GNSS_FIXSESSION_PARAM = extern struct { Size: u32, Version: u32, FixSessionID: u32, SessionType: GNSS_FIXSESSIONTYPE, HorizontalAccuracy: u32, HorizontalConfidence: u32, Reserved: [9]u32, FixLevelOfDetails: u32, Anonymous: extern union { SingleShotParam: GNSS_SINGLESHOT_PARAM, DistanceParam: GNSS_DISTANCETRACKING_PARAM, ContinuousParam: GNSS_CONTINUOUSTRACKING_PARAM, LkgFixParam: GNSS_LKGFIX_PARAM, UnusedParam: [268]u8, }, Unused: [256]u8, }; pub const GNSS_STOPFIXSESSION_PARAM = extern struct { Size: u32, Version: u32, FixSessionID: u32, Unused: [512]u8, }; pub const GNSS_FIXDATA_BASIC = extern struct { Size: u32, Version: u32, Latitude: f64, Longitude: f64, Altitude: f64, Speed: f64, Heading: f64, }; pub const GNSS_FIXDATA_BASIC_2 = extern struct { Size: u32, Version: u32, Latitude: f64, Longitude: f64, Altitude: f64, Speed: f64, Heading: f64, AltitudeEllipsoid: f64, }; pub const GNSS_FIXDATA_ACCURACY = extern struct { Size: u32, Version: u32, HorizontalAccuracy: u32, HorizontalErrorMajorAxis: u32, HorizontalErrorMinorAxis: u32, HorizontalErrorAngle: u32, HeadingAccuracy: u32, AltitudeAccuracy: u32, SpeedAccuracy: u32, HorizontalConfidence: u32, HeadingConfidence: u32, AltitudeConfidence: u32, SpeedConfidence: u32, PositionDilutionOfPrecision: f32, HorizontalDilutionOfPrecision: f32, VerticalDilutionOfPrecision: f32, }; pub const GNSS_FIXDATA_ACCURACY_2 = extern struct { Size: u32, Version: u32, HorizontalAccuracy: f64, HorizontalErrorMajorAxis: f64, HorizontalErrorMinorAxis: f64, HorizontalErrorAngle: f64, HeadingAccuracy: f64, AltitudeAccuracy: f64, SpeedAccuracy: f64, HorizontalConfidence: u32, HeadingConfidence: u32, AltitudeConfidence: u32, SpeedConfidence: u32, PositionDilutionOfPrecision: f64, HorizontalDilutionOfPrecision: f64, VerticalDilutionOfPrecision: f64, GeometricDilutionOfPrecision: f64, TimeDilutionOfPrecision: f64, }; pub const GNSS_SATELLITEINFO = extern struct { SatelliteId: u32, UsedInPositiong: BOOL, Elevation: f64, Azimuth: f64, SignalToNoiseRatio: f64, }; pub const GNSS_FIXDATA_SATELLITE = extern struct { Size: u32, Version: u32, SatelliteCount: u32, SatelliteArray: [64]GNSS_SATELLITEINFO, }; pub const GNSS_FIXDATA = extern struct { Size: u32, Version: u32, FixSessionID: u32, FixTimeStamp: FILETIME, IsFinalFix: BOOL, FixStatus: NTSTATUS, FixLevelOfDetails: u32, BasicData: GNSS_FIXDATA_BASIC, AccuracyData: GNSS_FIXDATA_ACCURACY, SatelliteData: GNSS_FIXDATA_SATELLITE, }; pub const GNSS_FIXDATA_2 = extern struct { Size: u32, Version: u32, FixSessionID: u32, FixTimeStamp: FILETIME, IsFinalFix: BOOL, FixStatus: NTSTATUS, FixLevelOfDetails: u32, BasicData: GNSS_FIXDATA_BASIC_2, AccuracyData: GNSS_FIXDATA_ACCURACY_2, SatelliteData: GNSS_FIXDATA_SATELLITE, }; pub const GNSS_BREADCRUMBING_PARAM = extern struct { Size: u32, Version: u32, MaximumHorizontalUncertainty: u32, MinDistanceBetweenFixes: u32, MaximumErrorTimeoutMs: u32, Unused: [512]u8, }; pub const GNSS_BREADCRUMBING_ALERT_DATA = extern struct { Size: u32, Version: u32, Unused: [512]u8, }; pub const GNSS_BREADCRUMB_V1 = extern struct { FixTimeStamp: FILETIME, Latitude: f64, Longitude: f64, HorizontalAccuracy: u32, Speed: u16, SpeedAccuracy: u16, Altitude: i16, AltitudeAccuracy: u16, Heading: i16, HeadingAccuracy: u8, FixSuccess: u8, }; pub const GNSS_BREADCRUMB_LIST = extern struct { Size: u32, Version: u32, NumCrumbs: u32, Anonymous: extern union { v1: [50]GNSS_BREADCRUMB_V1, }, }; pub const GNSS_GEOREGIONTYPE = enum(i32) { e = 1, }; pub const GNSS_GeoRegion_Circle = GNSS_GEOREGIONTYPE.e; pub const GNSS_GEOREGION_CIRCLE = extern struct { Latitude: f64, Longitude: f64, RadiusInMeters: f64, }; pub const GNSS_GEOREGION = extern struct { Size: u32, Version: u32, GeoRegionType: GNSS_GEOREGIONTYPE, Anonymous: extern union { Circle: GNSS_GEOREGION_CIRCLE, Unused: [512]u8, }, }; pub const GNSS_GEOFENCE_STATE = enum(i32) { Unknown = 0, Entered = 1, Exited = 2, }; pub const GNSS_GeofenceState_Unknown = GNSS_GEOFENCE_STATE.Unknown; pub const GNSS_GeofenceState_Entered = GNSS_GEOFENCE_STATE.Entered; pub const GNSS_GeofenceState_Exited = GNSS_GEOFENCE_STATE.Exited; pub const GNSS_GEOFENCE_CREATE_PARAM = extern struct { Size: u32, Version: u32, AlertTypes: u32, InitialState: GNSS_GEOFENCE_STATE, Boundary: GNSS_GEOREGION, Unused: [512]u8, }; pub const GNSS_GEOFENCE_CREATE_RESPONSE = extern struct { Size: u32, Version: u32, CreationStatus: NTSTATUS, GeofenceID: u32, Unused: [512]u8, }; pub const GNSS_GEOFENCE_DELETE_PARAM = extern struct { Size: u32, Version: u32, GeofenceID: u32, Unused: [512]u8, }; pub const GNSS_GEOFENCE_ALERT_DATA = extern struct { Size: u32, Version: u32, GeofenceID: u32, GeofenceState: GNSS_GEOFENCE_STATE, FixBasicData: GNSS_FIXDATA_BASIC, FixAccuracyData: GNSS_FIXDATA_ACCURACY, Unused: [512]u8, }; pub const GNSS_GEOFENCES_TRACKINGSTATUS_DATA = extern struct { Size: u32, Version: u32, Status: NTSTATUS, StatusTimeStamp: FILETIME, Unused: [512]u8, }; pub const GNSS_EVENT_TYPE = enum(i32) { FixAvailable = 1, RequireAgnss = 2, Error = 3, NiRequest = 12, NmeaData = 13, GeofenceAlertData = 14, GeofencesTrackingStatus = 15, DriverRequest = 16, BreadcrumbAlertEvent = 17, FixAvailable_2 = 18, Custom = 32768, }; pub const GNSS_Event_FixAvailable = GNSS_EVENT_TYPE.FixAvailable; pub const GNSS_Event_RequireAgnss = GNSS_EVENT_TYPE.RequireAgnss; pub const GNSS_Event_Error = GNSS_EVENT_TYPE.Error; pub const GNSS_Event_NiRequest = GNSS_EVENT_TYPE.NiRequest; pub const GNSS_Event_NmeaData = GNSS_EVENT_TYPE.NmeaData; pub const GNSS_Event_GeofenceAlertData = GNSS_EVENT_TYPE.GeofenceAlertData; pub const GNSS_Event_GeofencesTrackingStatus = GNSS_EVENT_TYPE.GeofencesTrackingStatus; pub const GNSS_Event_DriverRequest = GNSS_EVENT_TYPE.DriverRequest; pub const GNSS_Event_BreadcrumbAlertEvent = GNSS_EVENT_TYPE.BreadcrumbAlertEvent; pub const GNSS_Event_FixAvailable_2 = GNSS_EVENT_TYPE.FixAvailable_2; pub const GNSS_Event_Custom = GNSS_EVENT_TYPE.Custom; pub const GNSS_ERRORINFO = extern struct { Size: u32, Version: u32, ErrorCode: u32, IsRecoverable: BOOL, ErrorDescription: [256]u16, Unused: [512]u8, }; pub const GNSS_NMEA_DATA = extern struct { Size: u32, Version: u32, NmeaSentences: [256]CHAR, }; pub const GNSS_AGNSS_REQUEST_TYPE = enum(i32) { TimeInjection = 1, PositionInjection = 2, BlobInjection = 3, }; pub const GNSS_AGNSS_TimeInjection = GNSS_AGNSS_REQUEST_TYPE.TimeInjection; pub const GNSS_AGNSS_PositionInjection = GNSS_AGNSS_REQUEST_TYPE.PositionInjection; pub const GNSS_AGNSS_BlobInjection = GNSS_AGNSS_REQUEST_TYPE.BlobInjection; pub const GNSS_AGNSS_REQUEST_PARAM = extern struct { Size: u32, Version: u32, RequestType: GNSS_AGNSS_REQUEST_TYPE, BlobFormat: u32, }; pub const GNSS_NI_PLANE_TYPE = enum(i32) { SUPL = 1, CP = 2, V2UPL = 3, }; pub const GNSS_NI_SUPL = GNSS_NI_PLANE_TYPE.SUPL; pub const GNSS_NI_CP = GNSS_NI_PLANE_TYPE.CP; pub const GNSS_NI_V2UPL = GNSS_NI_PLANE_TYPE.V2UPL; pub const GNSS_NI_REQUEST_TYPE = enum(i32) { SingleShot = 1, AreaTrigger = 2, }; pub const GNSS_NI_Request_SingleShot = GNSS_NI_REQUEST_TYPE.SingleShot; pub const GNSS_NI_Request_AreaTrigger = GNSS_NI_REQUEST_TYPE.AreaTrigger; pub const GNSS_NI_NOTIFICATION_TYPE = enum(i32) { NoNotifyNoVerify = 1, NotifyOnly = 2, NotifyVerifyDefaultAllow = 3, NotifyVerifyDefaultNotAllow = 4, PrivacyOverride = 5, }; pub const GNSS_NI_NoNotifyNoVerify = GNSS_NI_NOTIFICATION_TYPE.NoNotifyNoVerify; pub const GNSS_NI_NotifyOnly = GNSS_NI_NOTIFICATION_TYPE.NotifyOnly; pub const GNSS_NI_NotifyVerifyDefaultAllow = GNSS_NI_NOTIFICATION_TYPE.NotifyVerifyDefaultAllow; pub const GNSS_NI_NotifyVerifyDefaultNotAllow = GNSS_NI_NOTIFICATION_TYPE.NotifyVerifyDefaultNotAllow; pub const GNSS_NI_PrivacyOverride = GNSS_NI_NOTIFICATION_TYPE.PrivacyOverride; pub const GNSS_SUPL_NI_INFO = extern struct { Size: u32, Version: u32, RequestorId: [260]u16, ClientName: [260]u16, SuplNiUrl: [260]CHAR, }; pub const GNSS_CP_NI_INFO = extern struct { Size: u32, Version: u32, RequestorId: [260]u16, NotificationText: [260]u16, }; pub const GNSS_V2UPL_NI_INFO = extern struct { Size: u32, Version: u32, RequestorId: [260]u16, }; pub const GNSS_NI_REQUEST_PARAM = extern struct { Size: u32, Version: u32, RequestId: u32, RequestType: GNSS_NI_REQUEST_TYPE, NotificationType: GNSS_NI_NOTIFICATION_TYPE, RequestPlaneType: GNSS_NI_PLANE_TYPE, Anonymous: extern union { SuplNiInfo: GNSS_SUPL_NI_INFO, CpNiInfo: GNSS_CP_NI_INFO, V2UplNiInfo: GNSS_V2UPL_NI_INFO, }, ResponseTimeInSec: u32, EmergencyLocation: BOOL, }; pub const GNSS_DRIVER_REQUEST = enum(i32) { A = 1, }; pub const SUPL_CONFIG_DATA = GNSS_DRIVER_REQUEST.A; pub const GNSS_DRIVER_REQUEST_DATA = extern struct { Size: u32, Version: u32, Request: GNSS_DRIVER_REQUEST, RequestFlag: u32, }; pub const GNSS_EVENT = extern struct { Size: u32, Version: u32, EventType: GNSS_EVENT_TYPE, EventDataSize: u32, Unused: [512]u8, Anonymous: extern union { FixData: GNSS_FIXDATA, AgnssRequest: GNSS_AGNSS_REQUEST_PARAM, NiRequest: GNSS_NI_REQUEST_PARAM, ErrorInformation: GNSS_ERRORINFO, NmeaData: GNSS_NMEA_DATA, GeofenceAlertData: GNSS_GEOFENCE_ALERT_DATA, BreadcrumbAlertData: GNSS_BREADCRUMBING_ALERT_DATA, GeofencesTrackingStatus: GNSS_GEOFENCES_TRACKINGSTATUS_DATA, DriverRequestData: GNSS_DRIVER_REQUEST_DATA, CustomData: [1]u8, }, }; pub const GNSS_EVENT_2 = extern struct { Size: u32, Version: u32, EventType: GNSS_EVENT_TYPE, EventDataSize: u32, Unused: [512]u8, Anonymous: extern union { FixData: GNSS_FIXDATA, FixData2: GNSS_FIXDATA_2, AgnssRequest: GNSS_AGNSS_REQUEST_PARAM, NiRequest: GNSS_NI_REQUEST_PARAM, ErrorInformation: GNSS_ERRORINFO, NmeaData: GNSS_NMEA_DATA, GeofenceAlertData: GNSS_GEOFENCE_ALERT_DATA, BreadcrumbAlertData: GNSS_BREADCRUMBING_ALERT_DATA, GeofencesTrackingStatus: GNSS_GEOFENCES_TRACKINGSTATUS_DATA, DriverRequestData: GNSS_DRIVER_REQUEST_DATA, CustomData: [1]u8, }, }; pub const GNSS_AGNSS_INJECTTIME = extern struct { Size: u32, Version: u32, UtcTime: FILETIME, TimeUncertainty: u32, }; pub const GNSS_AGNSS_INJECTPOSITION = extern struct { Size: u32, Version: u32, Age: u32, BasicData: GNSS_FIXDATA_BASIC, AccuracyData: GNSS_FIXDATA_ACCURACY, }; pub const GNSS_AGNSS_INJECTBLOB = extern struct { Size: u32, Version: u32, BlobOui: u32, BlobVersion: u32, AgnssFormat: u32, BlobSize: u32, BlobData: [1]u8, }; pub const GNSS_AGNSS_INJECT = extern struct { Size: u32, Version: u32, InjectionType: GNSS_AGNSS_REQUEST_TYPE, InjectionStatus: NTSTATUS, InjectionDataSize: u32, Unused: [512]u8, Anonymous: extern union { Time: GNSS_AGNSS_INJECTTIME, Position: GNSS_AGNSS_INJECTPOSITION, BlobData: GNSS_AGNSS_INJECTBLOB, }, }; pub const GNSS_SUPL_HSLP_CONFIG = extern struct { Size: u32, Version: u32, SuplHslp: [260]CHAR, SuplHslpFromImsi: [260]CHAR, Reserved: u32, Unused: [512]u8, }; pub const GNSS_SUPL_CERT_ACTION = enum(i32) { Inject = 1, Delete = 2, Purge = 3, }; pub const GNSS_Supl_Cert_Inject = GNSS_SUPL_CERT_ACTION.Inject; pub const GNSS_Supl_Cert_Delete = GNSS_SUPL_CERT_ACTION.Delete; pub const GNSS_Supl_Cert_Purge = GNSS_SUPL_CERT_ACTION.Purge; pub const GNSS_SUPL_CERT_CONFIG = extern struct { Size: u32, Version: u32, CertAction: GNSS_SUPL_CERT_ACTION, SuplCertName: [260]CHAR, CertSize: u32, Unused: [512]u8, CertData: [1]u8, }; pub const GNSS_V2UPL_CONFIG = extern struct { Size: u32, Version: u32, MPC: [260]CHAR, PDE: [260]CHAR, ApplicationTypeIndicator_MR: u8, Unused: [512]u8, }; pub const GNSS_NI_USER_RESPONSE = enum(i32) { Accept = 1, Deny = 2, Timeout = 3, }; pub const GNSS_Ni_UserResponseAccept = GNSS_NI_USER_RESPONSE.Accept; pub const GNSS_Ni_UserResponseDeny = GNSS_NI_USER_RESPONSE.Deny; pub const GNSS_Ni_UserResponseTimeout = GNSS_NI_USER_RESPONSE.Timeout; pub const GNSS_NI_RESPONSE = extern struct { Size: u32, Version: u32, RequestId: u32, UserResponse: GNSS_NI_USER_RESPONSE, }; pub const GNSS_CWTESTDATA = extern struct { Size: u32, Version: u32, TestResultStatus: NTSTATUS, SignalToNoiseRatio: f64, Frequency: f64, Unused: [512]u8, }; pub const GNSS_SELFTESTCONFIG = extern struct { Size: u32, Version: u32, TestType: u32, Unused: [512]u8, InBufLen: u32, InBuffer: [1]u8, }; pub const GNSS_SELFTESTRESULT = extern struct { Size: u32, Version: u32, TestResultStatus: NTSTATUS, Result: u32, PinFailedBitMask: u32, Unused: [512]u8, OutBufLen: u32, OutBuffer: [1]u8, }; pub const GNSS_CHIPSETINFO = extern struct { Size: u32, Version: u32, ManufacturerID: [25]u16, HardwareID: [25]u16, FirmwareVersion: [20]u16, Unused: [512]u8, }; //-------------------------------------------------------------------------------- // 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 (14) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const BSTR = @import("../foundation.zig").BSTR; const CHAR = @import("../foundation.zig").CHAR; const FILETIME = @import("../foundation.zig").FILETIME; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const IDispatch = @import("../system/com.zig").IDispatch; const IUnknown = @import("../system/com.zig").IUnknown; const LOCATION_DESIRED_ACCURACY = @import("../devices/sensors.zig").LOCATION_DESIRED_ACCURACY; const NTSTATUS = @import("../foundation.zig").NTSTATUS; const PROPERTYKEY = @import("../ui/shell/properties_system.zig").PROPERTYKEY; const PROPVARIANT = @import("../system/com/structured_storage.zig").PROPVARIANT; const SYSTEMTIME = @import("../foundation.zig").SYSTEMTIME; 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/devices/geolocation.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; //-------------------------------------------------------------------------------------------------- pub fn part1() anyerror!void { const file = std.fs.cwd().openFile("data/day08_input.txt", .{}) catch |err| label: { std.debug.print("unable to open file: {e}\n", .{err}); const stderr = std.io.getStdErr(); break :label stderr; }; defer file.close(); const file_size = try file.getEndPos(); std.log.info("File size {}", .{file_size}); var reader = std.io.bufferedReader(file.reader()); var istream = reader.reader(); var buf: [128]u8 = undefined; var counts = [_]u16{0} ** 10; var codes: [14][]const u8 = undefined; while (try istream.readUntilDelimiterOrEof(&buf, '\n')) |line| { var i: usize = 0; var it = std.mem.tokenize(u8, line, " |"); while (it.next()) |value| : (i += 1) { codes[i] = value; } // Evaluate line i = 10; while (i < 14) : (i += 1) { const len = codes[i].len; if (len == 2) { counts[1] += 1; } else if (len == 4) { counts[4] += 1; } else if (len == 3) { counts[7] += 1; } else if (len == 7) { counts[8] += 1; } } } const part1_sum = counts[1] + counts[4] + counts[7] + counts[8]; std.log.info("Part 1 sum: {d}", .{part1_sum}); } //-------------------------------------------------------------------------------------------------- const MutableIterator = struct { buffer: []u8, delimiter_bytes: []const u8, index: usize = 0, const Self = @This(); /// Returns a slice of the next token, or null if tokenization is complete. pub fn next(self: *Self) ?[]u8 { // move to beginning of token while (self.index < self.buffer.len and self.isSplitByte(self.buffer[self.index])) : (self.index += 1) {} const start = self.index; if (start == self.buffer.len) { return null; } // move to end of token while (self.index < self.buffer.len and !self.isSplitByte(self.buffer[self.index])) : (self.index += 1) {} const end = self.index; return self.buffer[start..end]; } fn isSplitByte(self: Self, byte: u8) bool { for (self.delimiter_bytes) |delimiter_byte| { if (byte == delimiter_byte) { return true; } } return false; } }; pub fn tokenize(buffer: []u8, delimiter_bytes: []const u8) MutableIterator { return .{ .index = 0, .buffer = buffer, .delimiter_bytes = delimiter_bytes, }; } //-------------------------------------------------------------------------------------------------- pub fn contains_all(input: []const u8, search_terms: []const u8) bool { if (input.len < search_terms.len) { return false; } for (search_terms) |term| { var found = false; for (input) |char| { if (char == term) { found = true; break; } } if (found == false) { return false; } } return true; } //-------------------------------------------------------------------------------------------------- pub fn create_decoder(input: *const [10][]const u8) [10][]const u8 { var map: [10][]const u8 = undefined; // First pass to get 1, 4, 7, 8 values var i: usize = 0; while (i < 10) : (i += 1) { const len = input[i].len; if (len == 2) { map[1] = input[i]; // 1 } else if (len == 4) { map[4] = input[i]; // 4 } else if (len == 3) { map[7] = input[i]; // 7 } else if (len == 7) { map[8] = input[i]; // 8 } } // Second pass: find 3 and 6 // 3 contains everything in 7. (2 and 5 do not) // 6 doesn't contain everything in 1. (0 and 9 do not) i = 0; while (i < 10) : (i += 1) { const len = input[i].len; if (len == 5) { // can be 2, 3 or 5 if (contains_all(input[i], map[7])) { map[3] = input[i]; } } else if (len == 6) { // can be 0, 9 or 6 if (contains_all(input[i], map[1]) == false) { map[6] = input[i]; } } } // Third pass: find 9 and 5 // 6 contains everything in 5. (not 2) // 9 contains everything in 3. (0 does not) i = 0; while (i < 10) : (i += 1) { const len = input[i].len; if (len == 5 and !std.mem.eql(u8, input[i], map[3])) { // can be 2 or 5 if (contains_all(map[6], input[i])) { // NB. reversed order here map[5] = input[i]; } else { map[2] = input[i]; } } else if (len == 6 and !std.mem.eql(u8, input[i], map[6])) { // can be 0 or 9 if (contains_all(input[i], map[3])) { map[9] = input[i]; } else { map[0] = input[i]; } } } return map; } //-------------------------------------------------------------------------------------------------- pub fn decode(input: *const [4][]const u8, decoder: *const [10][]const u8) u32 { var digits: [4]u32 = undefined; for (input) |digit_to_decode, d| { digits[d] = for (decoder) |code, pos| { if (std.mem.eql(u8, code, digit_to_decode)) { break @intCast(u32, pos); } } else 0; } // Sum digits var res: u32 = 0; res += (digits[0] * 1000); res += (digits[1] * 100); res += (digits[2] * 10); res += (digits[3] * 1); return res; } //-------------------------------------------------------------------------------------------------- pub fn part2() anyerror!void { const file = std.fs.cwd().openFile("data/day08_input.txt", .{}) catch |err| label: { std.debug.print("unable to open file: {e}\n", .{err}); const stderr = std.io.getStdErr(); break :label stderr; }; defer file.close(); const file_size = try file.getEndPos(); std.log.info("File size {}", .{file_size}); var reader = std.io.bufferedReader(file.reader()); var istream = reader.reader(); var buf: [128]u8 = undefined; var codes: [14][]u8 = undefined; var sum: u32 = 0; while (try istream.readUntilDelimiterOrEof(&buf, '\n')) |line| { var i: usize = 0; var it = tokenize(buf[0..line.len], " |"); while (it.next()) |value| : (i += 1) { std.sort.sort(u8, value, {}, comptime std.sort.asc(u8)); codes[i] = value; // std.log.info("{s}", .{value}); } const decoder = create_decoder(codes[0..10]); sum += decode(codes[10..14], &decoder); } std.log.info("Part 2 sum: {d}", .{sum}); } //-------------------------------------------------------------------------------------------------- pub fn main() anyerror!void { try part1(); try part2(); } //--------------------------------------------------------------------------------------------------
src/day08.zig
/// The function fiatSecp256k1AddcarryxU64 is an addition with carry. /// Postconditions: /// out1 = (arg1 + arg2 + arg3) mod 2^64 /// out2 = ⌊(arg1 + arg2 + arg3) / 2^64⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffffffffffff] /// arg3: [0x0 ~> 0xffffffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] /// out2: [0x0 ~> 0x1] fn fiatSecp256k1AddcarryxU64(out1: *u64, out2: *u1, arg1: u1, arg2: u64, arg3: u64) callconv(.Inline) void { const x1: u128 = ((@intCast(u128, arg1) + @intCast(u128, arg2)) + @intCast(u128, arg3)); const x2: u64 = @intCast(u64, (x1 & @intCast(u128, 0xffffffffffffffff))); const x3: u1 = @intCast(u1, (x1 >> 64)); out1.* = x2; out2.* = x3; } /// The function fiatSecp256k1SubborrowxU64 is a subtraction with borrow. /// Postconditions: /// out1 = (-arg1 + arg2 + -arg3) mod 2^64 /// out2 = -⌊(-arg1 + arg2 + -arg3) / 2^64⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffffffffffff] /// arg3: [0x0 ~> 0xffffffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] /// out2: [0x0 ~> 0x1] fn fiatSecp256k1SubborrowxU64(out1: *u64, out2: *u1, arg1: u1, arg2: u64, arg3: u64) callconv(.Inline) void { const x1: i128 = ((@intCast(i128, arg2) - @intCast(i128, arg1)) - @intCast(i128, arg3)); const x2: i1 = @intCast(i1, (x1 >> 64)); const x3: u64 = @intCast(u64, (x1 & @intCast(i128, 0xffffffffffffffff))); out1.* = x3; out2.* = @intCast(u1, (@intCast(i2, 0x0) - @intCast(i2, x2))); } /// The function fiatSecp256k1MulxU64 is a multiplication, returning the full double-width result. /// Postconditions: /// out1 = (arg1 * arg2) mod 2^64 /// out2 = ⌊arg1 * arg2 / 2^64⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0xffffffffffffffff] /// arg2: [0x0 ~> 0xffffffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] /// out2: [0x0 ~> 0xffffffffffffffff] fn fiatSecp256k1MulxU64(out1: *u64, out2: *u64, arg1: u64, arg2: u64) callconv(.Inline) void { const x1: u128 = (@intCast(u128, arg1) * @intCast(u128, arg2)); const x2: u64 = @intCast(u64, (x1 & @intCast(u128, 0xffffffffffffffff))); const x3: u64 = @intCast(u64, (x1 >> 64)); out1.* = x2; out2.* = x3; } /// The function fiatSecp256k1CmovznzU64 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 fiatSecp256k1CmovznzU64(out1: *u64, arg1: u1, arg2: u64, arg3: u64) callconv(.Inline) void { const x1: u1 = (~(~arg1)); const x2: u64 = @intCast(u64, (@intCast(i128, @intCast(i1, (@intCast(i2, 0x0) - @intCast(i2, x1)))) & @intCast(i128, 0xffffffffffffffff))); const x3: u64 = ((x2 & arg3) | ((~x2) & arg2)); out1.* = x3; } /// The function fiatSecp256k1Mul multiplies two field elements in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn fiatSecp256k1Mul(out1: *[4]u64, arg1: [4]u64, arg2: [4]u64) void { const x1: u64 = (arg1[1]); const x2: u64 = (arg1[2]); const x3: u64 = (arg1[3]); const x4: u64 = (arg1[0]); var x5: u64 = undefined; var x6: u64 = undefined; fiatSecp256k1MulxU64(&x5, &x6, x4, (arg2[3])); var x7: u64 = undefined; var x8: u64 = undefined; fiatSecp256k1MulxU64(&x7, &x8, x4, (arg2[2])); var x9: u64 = undefined; var x10: u64 = undefined; fiatSecp256k1MulxU64(&x9, &x10, x4, (arg2[1])); var x11: u64 = undefined; var x12: u64 = undefined; fiatSecp256k1MulxU64(&x11, &x12, x4, (arg2[0])); var x13: u64 = undefined; var x14: u1 = undefined; fiatSecp256k1AddcarryxU64(&x13, &x14, 0x0, x12, x9); var x15: u64 = undefined; var x16: u1 = undefined; fiatSecp256k1AddcarryxU64(&x15, &x16, x14, x10, x7); var x17: u64 = undefined; var x18: u1 = undefined; fiatSecp256k1AddcarryxU64(&x17, &x18, x16, x8, x5); const x19: u64 = (@intCast(u64, x18) + x6); var x20: u64 = undefined; var x21: u64 = undefined; fiatSecp256k1MulxU64(&x20, &x21, x11, 0xd838091dd2253531); var x22: u64 = undefined; var x23: u64 = undefined; fiatSecp256k1MulxU64(&x22, &x23, x20, 0xffffffffffffffff); var x24: u64 = undefined; var x25: u64 = undefined; fiatSecp256k1MulxU64(&x24, &x25, x20, 0xffffffffffffffff); var x26: u64 = undefined; var x27: u64 = undefined; fiatSecp256k1MulxU64(&x26, &x27, x20, 0xffffffffffffffff); var x28: u64 = undefined; var x29: u64 = undefined; fiatSecp256k1MulxU64(&x28, &x29, x20, 0xfffffffefffffc2f); var x30: u64 = undefined; var x31: u1 = undefined; fiatSecp256k1AddcarryxU64(&x30, &x31, 0x0, x29, x26); var x32: u64 = undefined; var x33: u1 = undefined; fiatSecp256k1AddcarryxU64(&x32, &x33, x31, x27, x24); var x34: u64 = undefined; var x35: u1 = undefined; fiatSecp256k1AddcarryxU64(&x34, &x35, x33, x25, x22); const x36: u64 = (@intCast(u64, x35) + x23); var x37: u64 = undefined; var x38: u1 = undefined; fiatSecp256k1AddcarryxU64(&x37, &x38, 0x0, x11, x28); var x39: u64 = undefined; var x40: u1 = undefined; fiatSecp256k1AddcarryxU64(&x39, &x40, x38, x13, x30); var x41: u64 = undefined; var x42: u1 = undefined; fiatSecp256k1AddcarryxU64(&x41, &x42, x40, x15, x32); var x43: u64 = undefined; var x44: u1 = undefined; fiatSecp256k1AddcarryxU64(&x43, &x44, x42, x17, x34); var x45: u64 = undefined; var x46: u1 = undefined; fiatSecp256k1AddcarryxU64(&x45, &x46, x44, x19, x36); var x47: u64 = undefined; var x48: u64 = undefined; fiatSecp256k1MulxU64(&x47, &x48, x1, (arg2[3])); var x49: u64 = undefined; var x50: u64 = undefined; fiatSecp256k1MulxU64(&x49, &x50, x1, (arg2[2])); var x51: u64 = undefined; var x52: u64 = undefined; fiatSecp256k1MulxU64(&x51, &x52, x1, (arg2[1])); var x53: u64 = undefined; var x54: u64 = undefined; fiatSecp256k1MulxU64(&x53, &x54, x1, (arg2[0])); var x55: u64 = undefined; var x56: u1 = undefined; fiatSecp256k1AddcarryxU64(&x55, &x56, 0x0, x54, x51); var x57: u64 = undefined; var x58: u1 = undefined; fiatSecp256k1AddcarryxU64(&x57, &x58, x56, x52, x49); var x59: u64 = undefined; var x60: u1 = undefined; fiatSecp256k1AddcarryxU64(&x59, &x60, x58, x50, x47); const x61: u64 = (@intCast(u64, x60) + x48); var x62: u64 = undefined; var x63: u1 = undefined; fiatSecp256k1AddcarryxU64(&x62, &x63, 0x0, x39, x53); var x64: u64 = undefined; var x65: u1 = undefined; fiatSecp256k1AddcarryxU64(&x64, &x65, x63, x41, x55); var x66: u64 = undefined; var x67: u1 = undefined; fiatSecp256k1AddcarryxU64(&x66, &x67, x65, x43, x57); var x68: u64 = undefined; var x69: u1 = undefined; fiatSecp256k1AddcarryxU64(&x68, &x69, x67, x45, x59); var x70: u64 = undefined; var x71: u1 = undefined; fiatSecp256k1AddcarryxU64(&x70, &x71, x69, @intCast(u64, x46), x61); var x72: u64 = undefined; var x73: u64 = undefined; fiatSecp256k1MulxU64(&x72, &x73, x62, 0xd838091dd2253531); var x74: u64 = undefined; var x75: u64 = undefined; fiatSecp256k1MulxU64(&x74, &x75, x72, 0xffffffffffffffff); var x76: u64 = undefined; var x77: u64 = undefined; fiatSecp256k1MulxU64(&x76, &x77, x72, 0xffffffffffffffff); var x78: u64 = undefined; var x79: u64 = undefined; fiatSecp256k1MulxU64(&x78, &x79, x72, 0xffffffffffffffff); var x80: u64 = undefined; var x81: u64 = undefined; fiatSecp256k1MulxU64(&x80, &x81, x72, 0xfffffffefffffc2f); var x82: u64 = undefined; var x83: u1 = undefined; fiatSecp256k1AddcarryxU64(&x82, &x83, 0x0, x81, x78); var x84: u64 = undefined; var x85: u1 = undefined; fiatSecp256k1AddcarryxU64(&x84, &x85, x83, x79, x76); var x86: u64 = undefined; var x87: u1 = undefined; fiatSecp256k1AddcarryxU64(&x86, &x87, x85, x77, x74); const x88: u64 = (@intCast(u64, x87) + x75); var x89: u64 = undefined; var x90: u1 = undefined; fiatSecp256k1AddcarryxU64(&x89, &x90, 0x0, x62, x80); var x91: u64 = undefined; var x92: u1 = undefined; fiatSecp256k1AddcarryxU64(&x91, &x92, x90, x64, x82); var x93: u64 = undefined; var x94: u1 = undefined; fiatSecp256k1AddcarryxU64(&x93, &x94, x92, x66, x84); var x95: u64 = undefined; var x96: u1 = undefined; fiatSecp256k1AddcarryxU64(&x95, &x96, x94, x68, x86); var x97: u64 = undefined; var x98: u1 = undefined; fiatSecp256k1AddcarryxU64(&x97, &x98, x96, x70, x88); const x99: u64 = (@intCast(u64, x98) + @intCast(u64, x71)); var x100: u64 = undefined; var x101: u64 = undefined; fiatSecp256k1MulxU64(&x100, &x101, x2, (arg2[3])); var x102: u64 = undefined; var x103: u64 = undefined; fiatSecp256k1MulxU64(&x102, &x103, x2, (arg2[2])); var x104: u64 = undefined; var x105: u64 = undefined; fiatSecp256k1MulxU64(&x104, &x105, x2, (arg2[1])); var x106: u64 = undefined; var x107: u64 = undefined; fiatSecp256k1MulxU64(&x106, &x107, x2, (arg2[0])); var x108: u64 = undefined; var x109: u1 = undefined; fiatSecp256k1AddcarryxU64(&x108, &x109, 0x0, x107, x104); var x110: u64 = undefined; var x111: u1 = undefined; fiatSecp256k1AddcarryxU64(&x110, &x111, x109, x105, x102); var x112: u64 = undefined; var x113: u1 = undefined; fiatSecp256k1AddcarryxU64(&x112, &x113, x111, x103, x100); const x114: u64 = (@intCast(u64, x113) + x101); var x115: u64 = undefined; var x116: u1 = undefined; fiatSecp256k1AddcarryxU64(&x115, &x116, 0x0, x91, x106); var x117: u64 = undefined; var x118: u1 = undefined; fiatSecp256k1AddcarryxU64(&x117, &x118, x116, x93, x108); var x119: u64 = undefined; var x120: u1 = undefined; fiatSecp256k1AddcarryxU64(&x119, &x120, x118, x95, x110); var x121: u64 = undefined; var x122: u1 = undefined; fiatSecp256k1AddcarryxU64(&x121, &x122, x120, x97, x112); var x123: u64 = undefined; var x124: u1 = undefined; fiatSecp256k1AddcarryxU64(&x123, &x124, x122, x99, x114); var x125: u64 = undefined; var x126: u64 = undefined; fiatSecp256k1MulxU64(&x125, &x126, x115, 0xd838091dd2253531); var x127: u64 = undefined; var x128: u64 = undefined; fiatSecp256k1MulxU64(&x127, &x128, x125, 0xffffffffffffffff); var x129: u64 = undefined; var x130: u64 = undefined; fiatSecp256k1MulxU64(&x129, &x130, x125, 0xffffffffffffffff); var x131: u64 = undefined; var x132: u64 = undefined; fiatSecp256k1MulxU64(&x131, &x132, x125, 0xffffffffffffffff); var x133: u64 = undefined; var x134: u64 = undefined; fiatSecp256k1MulxU64(&x133, &x134, x125, 0xfffffffefffffc2f); var x135: u64 = undefined; var x136: u1 = undefined; fiatSecp256k1AddcarryxU64(&x135, &x136, 0x0, x134, x131); var x137: u64 = undefined; var x138: u1 = undefined; fiatSecp256k1AddcarryxU64(&x137, &x138, x136, x132, x129); var x139: u64 = undefined; var x140: u1 = undefined; fiatSecp256k1AddcarryxU64(&x139, &x140, x138, x130, x127); const x141: u64 = (@intCast(u64, x140) + x128); var x142: u64 = undefined; var x143: u1 = undefined; fiatSecp256k1AddcarryxU64(&x142, &x143, 0x0, x115, x133); var x144: u64 = undefined; var x145: u1 = undefined; fiatSecp256k1AddcarryxU64(&x144, &x145, x143, x117, x135); var x146: u64 = undefined; var x147: u1 = undefined; fiatSecp256k1AddcarryxU64(&x146, &x147, x145, x119, x137); var x148: u64 = undefined; var x149: u1 = undefined; fiatSecp256k1AddcarryxU64(&x148, &x149, x147, x121, x139); var x150: u64 = undefined; var x151: u1 = undefined; fiatSecp256k1AddcarryxU64(&x150, &x151, x149, x123, x141); const x152: u64 = (@intCast(u64, x151) + @intCast(u64, x124)); var x153: u64 = undefined; var x154: u64 = undefined; fiatSecp256k1MulxU64(&x153, &x154, x3, (arg2[3])); var x155: u64 = undefined; var x156: u64 = undefined; fiatSecp256k1MulxU64(&x155, &x156, x3, (arg2[2])); var x157: u64 = undefined; var x158: u64 = undefined; fiatSecp256k1MulxU64(&x157, &x158, x3, (arg2[1])); var x159: u64 = undefined; var x160: u64 = undefined; fiatSecp256k1MulxU64(&x159, &x160, x3, (arg2[0])); var x161: u64 = undefined; var x162: u1 = undefined; fiatSecp256k1AddcarryxU64(&x161, &x162, 0x0, x160, x157); var x163: u64 = undefined; var x164: u1 = undefined; fiatSecp256k1AddcarryxU64(&x163, &x164, x162, x158, x155); var x165: u64 = undefined; var x166: u1 = undefined; fiatSecp256k1AddcarryxU64(&x165, &x166, x164, x156, x153); const x167: u64 = (@intCast(u64, x166) + x154); var x168: u64 = undefined; var x169: u1 = undefined; fiatSecp256k1AddcarryxU64(&x168, &x169, 0x0, x144, x159); var x170: u64 = undefined; var x171: u1 = undefined; fiatSecp256k1AddcarryxU64(&x170, &x171, x169, x146, x161); var x172: u64 = undefined; var x173: u1 = undefined; fiatSecp256k1AddcarryxU64(&x172, &x173, x171, x148, x163); var x174: u64 = undefined; var x175: u1 = undefined; fiatSecp256k1AddcarryxU64(&x174, &x175, x173, x150, x165); var x176: u64 = undefined; var x177: u1 = undefined; fiatSecp256k1AddcarryxU64(&x176, &x177, x175, x152, x167); var x178: u64 = undefined; var x179: u64 = undefined; fiatSecp256k1MulxU64(&x178, &x179, x168, 0xd838091dd2253531); var x180: u64 = undefined; var x181: u64 = undefined; fiatSecp256k1MulxU64(&x180, &x181, x178, 0xffffffffffffffff); var x182: u64 = undefined; var x183: u64 = undefined; fiatSecp256k1MulxU64(&x182, &x183, x178, 0xffffffffffffffff); var x184: u64 = undefined; var x185: u64 = undefined; fiatSecp256k1MulxU64(&x184, &x185, x178, 0xffffffffffffffff); var x186: u64 = undefined; var x187: u64 = undefined; fiatSecp256k1MulxU64(&x186, &x187, x178, 0xfffffffefffffc2f); var x188: u64 = undefined; var x189: u1 = undefined; fiatSecp256k1AddcarryxU64(&x188, &x189, 0x0, x187, x184); var x190: u64 = undefined; var x191: u1 = undefined; fiatSecp256k1AddcarryxU64(&x190, &x191, x189, x185, x182); var x192: u64 = undefined; var x193: u1 = undefined; fiatSecp256k1AddcarryxU64(&x192, &x193, x191, x183, x180); const x194: u64 = (@intCast(u64, x193) + x181); var x195: u64 = undefined; var x196: u1 = undefined; fiatSecp256k1AddcarryxU64(&x195, &x196, 0x0, x168, x186); var x197: u64 = undefined; var x198: u1 = undefined; fiatSecp256k1AddcarryxU64(&x197, &x198, x196, x170, x188); var x199: u64 = undefined; var x200: u1 = undefined; fiatSecp256k1AddcarryxU64(&x199, &x200, x198, x172, x190); var x201: u64 = undefined; var x202: u1 = undefined; fiatSecp256k1AddcarryxU64(&x201, &x202, x200, x174, x192); var x203: u64 = undefined; var x204: u1 = undefined; fiatSecp256k1AddcarryxU64(&x203, &x204, x202, x176, x194); const x205: u64 = (@intCast(u64, x204) + @intCast(u64, x177)); var x206: u64 = undefined; var x207: u1 = undefined; fiatSecp256k1SubborrowxU64(&x206, &x207, 0x0, x197, 0xfffffffefffffc2f); var x208: u64 = undefined; var x209: u1 = undefined; fiatSecp256k1SubborrowxU64(&x208, &x209, x207, x199, 0xffffffffffffffff); var x210: u64 = undefined; var x211: u1 = undefined; fiatSecp256k1SubborrowxU64(&x210, &x211, x209, x201, 0xffffffffffffffff); var x212: u64 = undefined; var x213: u1 = undefined; fiatSecp256k1SubborrowxU64(&x212, &x213, x211, x203, 0xffffffffffffffff); var x214: u64 = undefined; var x215: u1 = undefined; fiatSecp256k1SubborrowxU64(&x214, &x215, x213, x205, @intCast(u64, 0x0)); var x216: u64 = undefined; fiatSecp256k1CmovznzU64(&x216, x215, x206, x197); var x217: u64 = undefined; fiatSecp256k1CmovznzU64(&x217, x215, x208, x199); var x218: u64 = undefined; fiatSecp256k1CmovznzU64(&x218, x215, x210, x201); var x219: u64 = undefined; fiatSecp256k1CmovznzU64(&x219, x215, x212, x203); out1[0] = x216; out1[1] = x217; out1[2] = x218; out1[3] = x219; } /// The function fiatSecp256k1Square squares a field element in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg1)) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn fiatSecp256k1Square(out1: *[4]u64, arg1: [4]u64) void { const x1: u64 = (arg1[1]); const x2: u64 = (arg1[2]); const x3: u64 = (arg1[3]); const x4: u64 = (arg1[0]); var x5: u64 = undefined; var x6: u64 = undefined; fiatSecp256k1MulxU64(&x5, &x6, x4, (arg1[3])); var x7: u64 = undefined; var x8: u64 = undefined; fiatSecp256k1MulxU64(&x7, &x8, x4, (arg1[2])); var x9: u64 = undefined; var x10: u64 = undefined; fiatSecp256k1MulxU64(&x9, &x10, x4, (arg1[1])); var x11: u64 = undefined; var x12: u64 = undefined; fiatSecp256k1MulxU64(&x11, &x12, x4, (arg1[0])); var x13: u64 = undefined; var x14: u1 = undefined; fiatSecp256k1AddcarryxU64(&x13, &x14, 0x0, x12, x9); var x15: u64 = undefined; var x16: u1 = undefined; fiatSecp256k1AddcarryxU64(&x15, &x16, x14, x10, x7); var x17: u64 = undefined; var x18: u1 = undefined; fiatSecp256k1AddcarryxU64(&x17, &x18, x16, x8, x5); const x19: u64 = (@intCast(u64, x18) + x6); var x20: u64 = undefined; var x21: u64 = undefined; fiatSecp256k1MulxU64(&x20, &x21, x11, 0xd838091dd2253531); var x22: u64 = undefined; var x23: u64 = undefined; fiatSecp256k1MulxU64(&x22, &x23, x20, 0xffffffffffffffff); var x24: u64 = undefined; var x25: u64 = undefined; fiatSecp256k1MulxU64(&x24, &x25, x20, 0xffffffffffffffff); var x26: u64 = undefined; var x27: u64 = undefined; fiatSecp256k1MulxU64(&x26, &x27, x20, 0xffffffffffffffff); var x28: u64 = undefined; var x29: u64 = undefined; fiatSecp256k1MulxU64(&x28, &x29, x20, 0xfffffffefffffc2f); var x30: u64 = undefined; var x31: u1 = undefined; fiatSecp256k1AddcarryxU64(&x30, &x31, 0x0, x29, x26); var x32: u64 = undefined; var x33: u1 = undefined; fiatSecp256k1AddcarryxU64(&x32, &x33, x31, x27, x24); var x34: u64 = undefined; var x35: u1 = undefined; fiatSecp256k1AddcarryxU64(&x34, &x35, x33, x25, x22); const x36: u64 = (@intCast(u64, x35) + x23); var x37: u64 = undefined; var x38: u1 = undefined; fiatSecp256k1AddcarryxU64(&x37, &x38, 0x0, x11, x28); var x39: u64 = undefined; var x40: u1 = undefined; fiatSecp256k1AddcarryxU64(&x39, &x40, x38, x13, x30); var x41: u64 = undefined; var x42: u1 = undefined; fiatSecp256k1AddcarryxU64(&x41, &x42, x40, x15, x32); var x43: u64 = undefined; var x44: u1 = undefined; fiatSecp256k1AddcarryxU64(&x43, &x44, x42, x17, x34); var x45: u64 = undefined; var x46: u1 = undefined; fiatSecp256k1AddcarryxU64(&x45, &x46, x44, x19, x36); var x47: u64 = undefined; var x48: u64 = undefined; fiatSecp256k1MulxU64(&x47, &x48, x1, (arg1[3])); var x49: u64 = undefined; var x50: u64 = undefined; fiatSecp256k1MulxU64(&x49, &x50, x1, (arg1[2])); var x51: u64 = undefined; var x52: u64 = undefined; fiatSecp256k1MulxU64(&x51, &x52, x1, (arg1[1])); var x53: u64 = undefined; var x54: u64 = undefined; fiatSecp256k1MulxU64(&x53, &x54, x1, (arg1[0])); var x55: u64 = undefined; var x56: u1 = undefined; fiatSecp256k1AddcarryxU64(&x55, &x56, 0x0, x54, x51); var x57: u64 = undefined; var x58: u1 = undefined; fiatSecp256k1AddcarryxU64(&x57, &x58, x56, x52, x49); var x59: u64 = undefined; var x60: u1 = undefined; fiatSecp256k1AddcarryxU64(&x59, &x60, x58, x50, x47); const x61: u64 = (@intCast(u64, x60) + x48); var x62: u64 = undefined; var x63: u1 = undefined; fiatSecp256k1AddcarryxU64(&x62, &x63, 0x0, x39, x53); var x64: u64 = undefined; var x65: u1 = undefined; fiatSecp256k1AddcarryxU64(&x64, &x65, x63, x41, x55); var x66: u64 = undefined; var x67: u1 = undefined; fiatSecp256k1AddcarryxU64(&x66, &x67, x65, x43, x57); var x68: u64 = undefined; var x69: u1 = undefined; fiatSecp256k1AddcarryxU64(&x68, &x69, x67, x45, x59); var x70: u64 = undefined; var x71: u1 = undefined; fiatSecp256k1AddcarryxU64(&x70, &x71, x69, @intCast(u64, x46), x61); var x72: u64 = undefined; var x73: u64 = undefined; fiatSecp256k1MulxU64(&x72, &x73, x62, 0xd838091dd2253531); var x74: u64 = undefined; var x75: u64 = undefined; fiatSecp256k1MulxU64(&x74, &x75, x72, 0xffffffffffffffff); var x76: u64 = undefined; var x77: u64 = undefined; fiatSecp256k1MulxU64(&x76, &x77, x72, 0xffffffffffffffff); var x78: u64 = undefined; var x79: u64 = undefined; fiatSecp256k1MulxU64(&x78, &x79, x72, 0xffffffffffffffff); var x80: u64 = undefined; var x81: u64 = undefined; fiatSecp256k1MulxU64(&x80, &x81, x72, 0xfffffffefffffc2f); var x82: u64 = undefined; var x83: u1 = undefined; fiatSecp256k1AddcarryxU64(&x82, &x83, 0x0, x81, x78); var x84: u64 = undefined; var x85: u1 = undefined; fiatSecp256k1AddcarryxU64(&x84, &x85, x83, x79, x76); var x86: u64 = undefined; var x87: u1 = undefined; fiatSecp256k1AddcarryxU64(&x86, &x87, x85, x77, x74); const x88: u64 = (@intCast(u64, x87) + x75); var x89: u64 = undefined; var x90: u1 = undefined; fiatSecp256k1AddcarryxU64(&x89, &x90, 0x0, x62, x80); var x91: u64 = undefined; var x92: u1 = undefined; fiatSecp256k1AddcarryxU64(&x91, &x92, x90, x64, x82); var x93: u64 = undefined; var x94: u1 = undefined; fiatSecp256k1AddcarryxU64(&x93, &x94, x92, x66, x84); var x95: u64 = undefined; var x96: u1 = undefined; fiatSecp256k1AddcarryxU64(&x95, &x96, x94, x68, x86); var x97: u64 = undefined; var x98: u1 = undefined; fiatSecp256k1AddcarryxU64(&x97, &x98, x96, x70, x88); const x99: u64 = (@intCast(u64, x98) + @intCast(u64, x71)); var x100: u64 = undefined; var x101: u64 = undefined; fiatSecp256k1MulxU64(&x100, &x101, x2, (arg1[3])); var x102: u64 = undefined; var x103: u64 = undefined; fiatSecp256k1MulxU64(&x102, &x103, x2, (arg1[2])); var x104: u64 = undefined; var x105: u64 = undefined; fiatSecp256k1MulxU64(&x104, &x105, x2, (arg1[1])); var x106: u64 = undefined; var x107: u64 = undefined; fiatSecp256k1MulxU64(&x106, &x107, x2, (arg1[0])); var x108: u64 = undefined; var x109: u1 = undefined; fiatSecp256k1AddcarryxU64(&x108, &x109, 0x0, x107, x104); var x110: u64 = undefined; var x111: u1 = undefined; fiatSecp256k1AddcarryxU64(&x110, &x111, x109, x105, x102); var x112: u64 = undefined; var x113: u1 = undefined; fiatSecp256k1AddcarryxU64(&x112, &x113, x111, x103, x100); const x114: u64 = (@intCast(u64, x113) + x101); var x115: u64 = undefined; var x116: u1 = undefined; fiatSecp256k1AddcarryxU64(&x115, &x116, 0x0, x91, x106); var x117: u64 = undefined; var x118: u1 = undefined; fiatSecp256k1AddcarryxU64(&x117, &x118, x116, x93, x108); var x119: u64 = undefined; var x120: u1 = undefined; fiatSecp256k1AddcarryxU64(&x119, &x120, x118, x95, x110); var x121: u64 = undefined; var x122: u1 = undefined; fiatSecp256k1AddcarryxU64(&x121, &x122, x120, x97, x112); var x123: u64 = undefined; var x124: u1 = undefined; fiatSecp256k1AddcarryxU64(&x123, &x124, x122, x99, x114); var x125: u64 = undefined; var x126: u64 = undefined; fiatSecp256k1MulxU64(&x125, &x126, x115, 0xd838091dd2253531); var x127: u64 = undefined; var x128: u64 = undefined; fiatSecp256k1MulxU64(&x127, &x128, x125, 0xffffffffffffffff); var x129: u64 = undefined; var x130: u64 = undefined; fiatSecp256k1MulxU64(&x129, &x130, x125, 0xffffffffffffffff); var x131: u64 = undefined; var x132: u64 = undefined; fiatSecp256k1MulxU64(&x131, &x132, x125, 0xffffffffffffffff); var x133: u64 = undefined; var x134: u64 = undefined; fiatSecp256k1MulxU64(&x133, &x134, x125, 0xfffffffefffffc2f); var x135: u64 = undefined; var x136: u1 = undefined; fiatSecp256k1AddcarryxU64(&x135, &x136, 0x0, x134, x131); var x137: u64 = undefined; var x138: u1 = undefined; fiatSecp256k1AddcarryxU64(&x137, &x138, x136, x132, x129); var x139: u64 = undefined; var x140: u1 = undefined; fiatSecp256k1AddcarryxU64(&x139, &x140, x138, x130, x127); const x141: u64 = (@intCast(u64, x140) + x128); var x142: u64 = undefined; var x143: u1 = undefined; fiatSecp256k1AddcarryxU64(&x142, &x143, 0x0, x115, x133); var x144: u64 = undefined; var x145: u1 = undefined; fiatSecp256k1AddcarryxU64(&x144, &x145, x143, x117, x135); var x146: u64 = undefined; var x147: u1 = undefined; fiatSecp256k1AddcarryxU64(&x146, &x147, x145, x119, x137); var x148: u64 = undefined; var x149: u1 = undefined; fiatSecp256k1AddcarryxU64(&x148, &x149, x147, x121, x139); var x150: u64 = undefined; var x151: u1 = undefined; fiatSecp256k1AddcarryxU64(&x150, &x151, x149, x123, x141); const x152: u64 = (@intCast(u64, x151) + @intCast(u64, x124)); var x153: u64 = undefined; var x154: u64 = undefined; fiatSecp256k1MulxU64(&x153, &x154, x3, (arg1[3])); var x155: u64 = undefined; var x156: u64 = undefined; fiatSecp256k1MulxU64(&x155, &x156, x3, (arg1[2])); var x157: u64 = undefined; var x158: u64 = undefined; fiatSecp256k1MulxU64(&x157, &x158, x3, (arg1[1])); var x159: u64 = undefined; var x160: u64 = undefined; fiatSecp256k1MulxU64(&x159, &x160, x3, (arg1[0])); var x161: u64 = undefined; var x162: u1 = undefined; fiatSecp256k1AddcarryxU64(&x161, &x162, 0x0, x160, x157); var x163: u64 = undefined; var x164: u1 = undefined; fiatSecp256k1AddcarryxU64(&x163, &x164, x162, x158, x155); var x165: u64 = undefined; var x166: u1 = undefined; fiatSecp256k1AddcarryxU64(&x165, &x166, x164, x156, x153); const x167: u64 = (@intCast(u64, x166) + x154); var x168: u64 = undefined; var x169: u1 = undefined; fiatSecp256k1AddcarryxU64(&x168, &x169, 0x0, x144, x159); var x170: u64 = undefined; var x171: u1 = undefined; fiatSecp256k1AddcarryxU64(&x170, &x171, x169, x146, x161); var x172: u64 = undefined; var x173: u1 = undefined; fiatSecp256k1AddcarryxU64(&x172, &x173, x171, x148, x163); var x174: u64 = undefined; var x175: u1 = undefined; fiatSecp256k1AddcarryxU64(&x174, &x175, x173, x150, x165); var x176: u64 = undefined; var x177: u1 = undefined; fiatSecp256k1AddcarryxU64(&x176, &x177, x175, x152, x167); var x178: u64 = undefined; var x179: u64 = undefined; fiatSecp256k1MulxU64(&x178, &x179, x168, 0xd838091dd2253531); var x180: u64 = undefined; var x181: u64 = undefined; fiatSecp256k1MulxU64(&x180, &x181, x178, 0xffffffffffffffff); var x182: u64 = undefined; var x183: u64 = undefined; fiatSecp256k1MulxU64(&x182, &x183, x178, 0xffffffffffffffff); var x184: u64 = undefined; var x185: u64 = undefined; fiatSecp256k1MulxU64(&x184, &x185, x178, 0xffffffffffffffff); var x186: u64 = undefined; var x187: u64 = undefined; fiatSecp256k1MulxU64(&x186, &x187, x178, 0xfffffffefffffc2f); var x188: u64 = undefined; var x189: u1 = undefined; fiatSecp256k1AddcarryxU64(&x188, &x189, 0x0, x187, x184); var x190: u64 = undefined; var x191: u1 = undefined; fiatSecp256k1AddcarryxU64(&x190, &x191, x189, x185, x182); var x192: u64 = undefined; var x193: u1 = undefined; fiatSecp256k1AddcarryxU64(&x192, &x193, x191, x183, x180); const x194: u64 = (@intCast(u64, x193) + x181); var x195: u64 = undefined; var x196: u1 = undefined; fiatSecp256k1AddcarryxU64(&x195, &x196, 0x0, x168, x186); var x197: u64 = undefined; var x198: u1 = undefined; fiatSecp256k1AddcarryxU64(&x197, &x198, x196, x170, x188); var x199: u64 = undefined; var x200: u1 = undefined; fiatSecp256k1AddcarryxU64(&x199, &x200, x198, x172, x190); var x201: u64 = undefined; var x202: u1 = undefined; fiatSecp256k1AddcarryxU64(&x201, &x202, x200, x174, x192); var x203: u64 = undefined; var x204: u1 = undefined; fiatSecp256k1AddcarryxU64(&x203, &x204, x202, x176, x194); const x205: u64 = (@intCast(u64, x204) + @intCast(u64, x177)); var x206: u64 = undefined; var x207: u1 = undefined; fiatSecp256k1SubborrowxU64(&x206, &x207, 0x0, x197, 0xfffffffefffffc2f); var x208: u64 = undefined; var x209: u1 = undefined; fiatSecp256k1SubborrowxU64(&x208, &x209, x207, x199, 0xffffffffffffffff); var x210: u64 = undefined; var x211: u1 = undefined; fiatSecp256k1SubborrowxU64(&x210, &x211, x209, x201, 0xffffffffffffffff); var x212: u64 = undefined; var x213: u1 = undefined; fiatSecp256k1SubborrowxU64(&x212, &x213, x211, x203, 0xffffffffffffffff); var x214: u64 = undefined; var x215: u1 = undefined; fiatSecp256k1SubborrowxU64(&x214, &x215, x213, x205, @intCast(u64, 0x0)); var x216: u64 = undefined; fiatSecp256k1CmovznzU64(&x216, x215, x206, x197); var x217: u64 = undefined; fiatSecp256k1CmovznzU64(&x217, x215, x208, x199); var x218: u64 = undefined; fiatSecp256k1CmovznzU64(&x218, x215, x210, x201); var x219: u64 = undefined; fiatSecp256k1CmovznzU64(&x219, x215, x212, x203); out1[0] = x216; out1[1] = x217; out1[2] = x218; out1[3] = x219; } /// The function fiatSecp256k1Add adds two field elements in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn fiatSecp256k1Add(out1: *[4]u64, arg1: [4]u64, arg2: [4]u64) void { var x1: u64 = undefined; var x2: u1 = undefined; fiatSecp256k1AddcarryxU64(&x1, &x2, 0x0, (arg1[0]), (arg2[0])); var x3: u64 = undefined; var x4: u1 = undefined; fiatSecp256k1AddcarryxU64(&x3, &x4, x2, (arg1[1]), (arg2[1])); var x5: u64 = undefined; var x6: u1 = undefined; fiatSecp256k1AddcarryxU64(&x5, &x6, x4, (arg1[2]), (arg2[2])); var x7: u64 = undefined; var x8: u1 = undefined; fiatSecp256k1AddcarryxU64(&x7, &x8, x6, (arg1[3]), (arg2[3])); var x9: u64 = undefined; var x10: u1 = undefined; fiatSecp256k1SubborrowxU64(&x9, &x10, 0x0, x1, 0xfffffffefffffc2f); var x11: u64 = undefined; var x12: u1 = undefined; fiatSecp256k1SubborrowxU64(&x11, &x12, x10, x3, 0xffffffffffffffff); var x13: u64 = undefined; var x14: u1 = undefined; fiatSecp256k1SubborrowxU64(&x13, &x14, x12, x5, 0xffffffffffffffff); var x15: u64 = undefined; var x16: u1 = undefined; fiatSecp256k1SubborrowxU64(&x15, &x16, x14, x7, 0xffffffffffffffff); var x17: u64 = undefined; var x18: u1 = undefined; fiatSecp256k1SubborrowxU64(&x17, &x18, x16, @intCast(u64, x8), @intCast(u64, 0x0)); var x19: u64 = undefined; fiatSecp256k1CmovznzU64(&x19, x18, x9, x1); var x20: u64 = undefined; fiatSecp256k1CmovznzU64(&x20, x18, x11, x3); var x21: u64 = undefined; fiatSecp256k1CmovznzU64(&x21, x18, x13, x5); var x22: u64 = undefined; fiatSecp256k1CmovznzU64(&x22, x18, x15, x7); out1[0] = x19; out1[1] = x20; out1[2] = x21; out1[3] = x22; } /// The function fiatSecp256k1Sub subtracts two field elements in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn fiatSecp256k1Sub(out1: *[4]u64, arg1: [4]u64, arg2: [4]u64) void { var x1: u64 = undefined; var x2: u1 = undefined; fiatSecp256k1SubborrowxU64(&x1, &x2, 0x0, (arg1[0]), (arg2[0])); var x3: u64 = undefined; var x4: u1 = undefined; fiatSecp256k1SubborrowxU64(&x3, &x4, x2, (arg1[1]), (arg2[1])); var x5: u64 = undefined; var x6: u1 = undefined; fiatSecp256k1SubborrowxU64(&x5, &x6, x4, (arg1[2]), (arg2[2])); var x7: u64 = undefined; var x8: u1 = undefined; fiatSecp256k1SubborrowxU64(&x7, &x8, x6, (arg1[3]), (arg2[3])); var x9: u64 = undefined; fiatSecp256k1CmovznzU64(&x9, x8, @intCast(u64, 0x0), 0xffffffffffffffff); var x10: u64 = undefined; var x11: u1 = undefined; fiatSecp256k1AddcarryxU64(&x10, &x11, 0x0, x1, (x9 & 0xfffffffefffffc2f)); var x12: u64 = undefined; var x13: u1 = undefined; fiatSecp256k1AddcarryxU64(&x12, &x13, x11, x3, x9); var x14: u64 = undefined; var x15: u1 = undefined; fiatSecp256k1AddcarryxU64(&x14, &x15, x13, x5, x9); var x16: u64 = undefined; var x17: u1 = undefined; fiatSecp256k1AddcarryxU64(&x16, &x17, x15, x7, x9); out1[0] = x10; out1[1] = x12; out1[2] = x14; out1[3] = x16; } /// The function fiatSecp256k1Opp negates a field element in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = -eval (from_montgomery arg1) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn fiatSecp256k1Opp(out1: *[4]u64, arg1: [4]u64) void { var x1: u64 = undefined; var x2: u1 = undefined; fiatSecp256k1SubborrowxU64(&x1, &x2, 0x0, @intCast(u64, 0x0), (arg1[0])); var x3: u64 = undefined; var x4: u1 = undefined; fiatSecp256k1SubborrowxU64(&x3, &x4, x2, @intCast(u64, 0x0), (arg1[1])); var x5: u64 = undefined; var x6: u1 = undefined; fiatSecp256k1SubborrowxU64(&x5, &x6, x4, @intCast(u64, 0x0), (arg1[2])); var x7: u64 = undefined; var x8: u1 = undefined; fiatSecp256k1SubborrowxU64(&x7, &x8, x6, @intCast(u64, 0x0), (arg1[3])); var x9: u64 = undefined; fiatSecp256k1CmovznzU64(&x9, x8, @intCast(u64, 0x0), 0xffffffffffffffff); var x10: u64 = undefined; var x11: u1 = undefined; fiatSecp256k1AddcarryxU64(&x10, &x11, 0x0, x1, (x9 & 0xfffffffefffffc2f)); var x12: u64 = undefined; var x13: u1 = undefined; fiatSecp256k1AddcarryxU64(&x12, &x13, x11, x3, x9); var x14: u64 = undefined; var x15: u1 = undefined; fiatSecp256k1AddcarryxU64(&x14, &x15, x13, x5, x9); var x16: u64 = undefined; var x17: u1 = undefined; fiatSecp256k1AddcarryxU64(&x16, &x17, x15, x7, x9); out1[0] = x10; out1[1] = x12; out1[2] = x14; out1[3] = x16; } /// The function fiatSecp256k1FromMontgomery translates a field element out of the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval out1 mod m = (eval arg1 * ((2^64)⁻¹ mod m)^4) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn fiatSecp256k1FromMontgomery(out1: *[4]u64, arg1: [4]u64) void { const x1: u64 = (arg1[0]); var x2: u64 = undefined; var x3: u64 = undefined; fiatSecp256k1MulxU64(&x2, &x3, x1, 0xd838091dd2253531); var x4: u64 = undefined; var x5: u64 = undefined; fiatSecp256k1MulxU64(&x4, &x5, x2, 0xffffffffffffffff); var x6: u64 = undefined; var x7: u64 = undefined; fiatSecp256k1MulxU64(&x6, &x7, x2, 0xffffffffffffffff); var x8: u64 = undefined; var x9: u64 = undefined; fiatSecp256k1MulxU64(&x8, &x9, x2, 0xffffffffffffffff); var x10: u64 = undefined; var x11: u64 = undefined; fiatSecp256k1MulxU64(&x10, &x11, x2, 0xfffffffefffffc2f); var x12: u64 = undefined; var x13: u1 = undefined; fiatSecp256k1AddcarryxU64(&x12, &x13, 0x0, x11, x8); var x14: u64 = undefined; var x15: u1 = undefined; fiatSecp256k1AddcarryxU64(&x14, &x15, x13, x9, x6); var x16: u64 = undefined; var x17: u1 = undefined; fiatSecp256k1AddcarryxU64(&x16, &x17, x15, x7, x4); var x18: u64 = undefined; var x19: u1 = undefined; fiatSecp256k1AddcarryxU64(&x18, &x19, 0x0, x1, x10); var x20: u64 = undefined; var x21: u1 = undefined; fiatSecp256k1AddcarryxU64(&x20, &x21, x19, @intCast(u64, 0x0), x12); var x22: u64 = undefined; var x23: u1 = undefined; fiatSecp256k1AddcarryxU64(&x22, &x23, x21, @intCast(u64, 0x0), x14); var x24: u64 = undefined; var x25: u1 = undefined; fiatSecp256k1AddcarryxU64(&x24, &x25, x23, @intCast(u64, 0x0), x16); var x26: u64 = undefined; var x27: u1 = undefined; fiatSecp256k1AddcarryxU64(&x26, &x27, x25, @intCast(u64, 0x0), (@intCast(u64, x17) + x5)); var x28: u64 = undefined; var x29: u1 = undefined; fiatSecp256k1AddcarryxU64(&x28, &x29, 0x0, x20, (arg1[1])); var x30: u64 = undefined; var x31: u1 = undefined; fiatSecp256k1AddcarryxU64(&x30, &x31, x29, x22, @intCast(u64, 0x0)); var x32: u64 = undefined; var x33: u1 = undefined; fiatSecp256k1AddcarryxU64(&x32, &x33, x31, x24, @intCast(u64, 0x0)); var x34: u64 = undefined; var x35: u1 = undefined; fiatSecp256k1AddcarryxU64(&x34, &x35, x33, x26, @intCast(u64, 0x0)); var x36: u64 = undefined; var x37: u64 = undefined; fiatSecp256k1MulxU64(&x36, &x37, x28, 0xd838091dd2253531); var x38: u64 = undefined; var x39: u64 = undefined; fiatSecp256k1MulxU64(&x38, &x39, x36, 0xffffffffffffffff); var x40: u64 = undefined; var x41: u64 = undefined; fiatSecp256k1MulxU64(&x40, &x41, x36, 0xffffffffffffffff); var x42: u64 = undefined; var x43: u64 = undefined; fiatSecp256k1MulxU64(&x42, &x43, x36, 0xffffffffffffffff); var x44: u64 = undefined; var x45: u64 = undefined; fiatSecp256k1MulxU64(&x44, &x45, x36, 0xfffffffefffffc2f); var x46: u64 = undefined; var x47: u1 = undefined; fiatSecp256k1AddcarryxU64(&x46, &x47, 0x0, x45, x42); var x48: u64 = undefined; var x49: u1 = undefined; fiatSecp256k1AddcarryxU64(&x48, &x49, x47, x43, x40); var x50: u64 = undefined; var x51: u1 = undefined; fiatSecp256k1AddcarryxU64(&x50, &x51, x49, x41, x38); var x52: u64 = undefined; var x53: u1 = undefined; fiatSecp256k1AddcarryxU64(&x52, &x53, 0x0, x28, x44); var x54: u64 = undefined; var x55: u1 = undefined; fiatSecp256k1AddcarryxU64(&x54, &x55, x53, x30, x46); var x56: u64 = undefined; var x57: u1 = undefined; fiatSecp256k1AddcarryxU64(&x56, &x57, x55, x32, x48); var x58: u64 = undefined; var x59: u1 = undefined; fiatSecp256k1AddcarryxU64(&x58, &x59, x57, x34, x50); var x60: u64 = undefined; var x61: u1 = undefined; fiatSecp256k1AddcarryxU64(&x60, &x61, x59, (@intCast(u64, x35) + @intCast(u64, x27)), (@intCast(u64, x51) + x39)); var x62: u64 = undefined; var x63: u1 = undefined; fiatSecp256k1AddcarryxU64(&x62, &x63, 0x0, x54, (arg1[2])); var x64: u64 = undefined; var x65: u1 = undefined; fiatSecp256k1AddcarryxU64(&x64, &x65, x63, x56, @intCast(u64, 0x0)); var x66: u64 = undefined; var x67: u1 = undefined; fiatSecp256k1AddcarryxU64(&x66, &x67, x65, x58, @intCast(u64, 0x0)); var x68: u64 = undefined; var x69: u1 = undefined; fiatSecp256k1AddcarryxU64(&x68, &x69, x67, x60, @intCast(u64, 0x0)); var x70: u64 = undefined; var x71: u64 = undefined; fiatSecp256k1MulxU64(&x70, &x71, x62, 0xd838091dd2253531); var x72: u64 = undefined; var x73: u64 = undefined; fiatSecp256k1MulxU64(&x72, &x73, x70, 0xffffffffffffffff); var x74: u64 = undefined; var x75: u64 = undefined; fiatSecp256k1MulxU64(&x74, &x75, x70, 0xffffffffffffffff); var x76: u64 = undefined; var x77: u64 = undefined; fiatSecp256k1MulxU64(&x76, &x77, x70, 0xffffffffffffffff); var x78: u64 = undefined; var x79: u64 = undefined; fiatSecp256k1MulxU64(&x78, &x79, x70, 0xfffffffefffffc2f); var x80: u64 = undefined; var x81: u1 = undefined; fiatSecp256k1AddcarryxU64(&x80, &x81, 0x0, x79, x76); var x82: u64 = undefined; var x83: u1 = undefined; fiatSecp256k1AddcarryxU64(&x82, &x83, x81, x77, x74); var x84: u64 = undefined; var x85: u1 = undefined; fiatSecp256k1AddcarryxU64(&x84, &x85, x83, x75, x72); var x86: u64 = undefined; var x87: u1 = undefined; fiatSecp256k1AddcarryxU64(&x86, &x87, 0x0, x62, x78); var x88: u64 = undefined; var x89: u1 = undefined; fiatSecp256k1AddcarryxU64(&x88, &x89, x87, x64, x80); var x90: u64 = undefined; var x91: u1 = undefined; fiatSecp256k1AddcarryxU64(&x90, &x91, x89, x66, x82); var x92: u64 = undefined; var x93: u1 = undefined; fiatSecp256k1AddcarryxU64(&x92, &x93, x91, x68, x84); var x94: u64 = undefined; var x95: u1 = undefined; fiatSecp256k1AddcarryxU64(&x94, &x95, x93, (@intCast(u64, x69) + @intCast(u64, x61)), (@intCast(u64, x85) + x73)); var x96: u64 = undefined; var x97: u1 = undefined; fiatSecp256k1AddcarryxU64(&x96, &x97, 0x0, x88, (arg1[3])); var x98: u64 = undefined; var x99: u1 = undefined; fiatSecp256k1AddcarryxU64(&x98, &x99, x97, x90, @intCast(u64, 0x0)); var x100: u64 = undefined; var x101: u1 = undefined; fiatSecp256k1AddcarryxU64(&x100, &x101, x99, x92, @intCast(u64, 0x0)); var x102: u64 = undefined; var x103: u1 = undefined; fiatSecp256k1AddcarryxU64(&x102, &x103, x101, x94, @intCast(u64, 0x0)); var x104: u64 = undefined; var x105: u64 = undefined; fiatSecp256k1MulxU64(&x104, &x105, x96, 0xd838091dd2253531); var x106: u64 = undefined; var x107: u64 = undefined; fiatSecp256k1MulxU64(&x106, &x107, x104, 0xffffffffffffffff); var x108: u64 = undefined; var x109: u64 = undefined; fiatSecp256k1MulxU64(&x108, &x109, x104, 0xffffffffffffffff); var x110: u64 = undefined; var x111: u64 = undefined; fiatSecp256k1MulxU64(&x110, &x111, x104, 0xffffffffffffffff); var x112: u64 = undefined; var x113: u64 = undefined; fiatSecp256k1MulxU64(&x112, &x113, x104, 0xfffffffefffffc2f); var x114: u64 = undefined; var x115: u1 = undefined; fiatSecp256k1AddcarryxU64(&x114, &x115, 0x0, x113, x110); var x116: u64 = undefined; var x117: u1 = undefined; fiatSecp256k1AddcarryxU64(&x116, &x117, x115, x111, x108); var x118: u64 = undefined; var x119: u1 = undefined; fiatSecp256k1AddcarryxU64(&x118, &x119, x117, x109, x106); var x120: u64 = undefined; var x121: u1 = undefined; fiatSecp256k1AddcarryxU64(&x120, &x121, 0x0, x96, x112); var x122: u64 = undefined; var x123: u1 = undefined; fiatSecp256k1AddcarryxU64(&x122, &x123, x121, x98, x114); var x124: u64 = undefined; var x125: u1 = undefined; fiatSecp256k1AddcarryxU64(&x124, &x125, x123, x100, x116); var x126: u64 = undefined; var x127: u1 = undefined; fiatSecp256k1AddcarryxU64(&x126, &x127, x125, x102, x118); var x128: u64 = undefined; var x129: u1 = undefined; fiatSecp256k1AddcarryxU64(&x128, &x129, x127, (@intCast(u64, x103) + @intCast(u64, x95)), (@intCast(u64, x119) + x107)); var x130: u64 = undefined; var x131: u1 = undefined; fiatSecp256k1SubborrowxU64(&x130, &x131, 0x0, x122, 0xfffffffefffffc2f); var x132: u64 = undefined; var x133: u1 = undefined; fiatSecp256k1SubborrowxU64(&x132, &x133, x131, x124, 0xffffffffffffffff); var x134: u64 = undefined; var x135: u1 = undefined; fiatSecp256k1SubborrowxU64(&x134, &x135, x133, x126, 0xffffffffffffffff); var x136: u64 = undefined; var x137: u1 = undefined; fiatSecp256k1SubborrowxU64(&x136, &x137, x135, x128, 0xffffffffffffffff); var x138: u64 = undefined; var x139: u1 = undefined; fiatSecp256k1SubborrowxU64(&x138, &x139, x137, @intCast(u64, x129), @intCast(u64, 0x0)); var x140: u64 = undefined; fiatSecp256k1CmovznzU64(&x140, x139, x130, x122); var x141: u64 = undefined; fiatSecp256k1CmovznzU64(&x141, x139, x132, x124); var x142: u64 = undefined; fiatSecp256k1CmovznzU64(&x142, x139, x134, x126); var x143: u64 = undefined; fiatSecp256k1CmovznzU64(&x143, x139, x136, x128); out1[0] = x140; out1[1] = x141; out1[2] = x142; out1[3] = x143; } /// The function fiatSecp256k1ToMontgomery translates a field element into the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = eval arg1 mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn fiatSecp256k1ToMontgomery(out1: *[4]u64, arg1: [4]u64) void { const x1: u64 = (arg1[1]); const x2: u64 = (arg1[2]); const x3: u64 = (arg1[3]); const x4: u64 = (arg1[0]); var x5: u64 = undefined; var x6: u64 = undefined; fiatSecp256k1MulxU64(&x5, &x6, x4, 0x7a2000e90a1); var x7: u64 = undefined; var x8: u1 = undefined; fiatSecp256k1AddcarryxU64(&x7, &x8, 0x0, x6, x4); var x9: u64 = undefined; var x10: u64 = undefined; fiatSecp256k1MulxU64(&x9, &x10, x5, 0xd838091dd2253531); var x11: u64 = undefined; var x12: u64 = undefined; fiatSecp256k1MulxU64(&x11, &x12, x9, 0xffffffffffffffff); var x13: u64 = undefined; var x14: u64 = undefined; fiatSecp256k1MulxU64(&x13, &x14, x9, 0xffffffffffffffff); var x15: u64 = undefined; var x16: u64 = undefined; fiatSecp256k1MulxU64(&x15, &x16, x9, 0xffffffffffffffff); var x17: u64 = undefined; var x18: u64 = undefined; fiatSecp256k1MulxU64(&x17, &x18, x9, 0xfffffffefffffc2f); var x19: u64 = undefined; var x20: u1 = undefined; fiatSecp256k1AddcarryxU64(&x19, &x20, 0x0, x18, x15); var x21: u64 = undefined; var x22: u1 = undefined; fiatSecp256k1AddcarryxU64(&x21, &x22, x20, x16, x13); var x23: u64 = undefined; var x24: u1 = undefined; fiatSecp256k1AddcarryxU64(&x23, &x24, x22, x14, x11); var x25: u64 = undefined; var x26: u1 = undefined; fiatSecp256k1AddcarryxU64(&x25, &x26, 0x0, x5, x17); var x27: u64 = undefined; var x28: u1 = undefined; fiatSecp256k1AddcarryxU64(&x27, &x28, x26, x7, x19); var x29: u64 = undefined; var x30: u1 = undefined; fiatSecp256k1AddcarryxU64(&x29, &x30, x28, @intCast(u64, x8), x21); var x31: u64 = undefined; var x32: u1 = undefined; fiatSecp256k1AddcarryxU64(&x31, &x32, x30, @intCast(u64, 0x0), x23); var x33: u64 = undefined; var x34: u1 = undefined; fiatSecp256k1AddcarryxU64(&x33, &x34, x32, @intCast(u64, 0x0), (@intCast(u64, x24) + x12)); var x35: u64 = undefined; var x36: u64 = undefined; fiatSecp256k1MulxU64(&x35, &x36, x1, 0x7a2000e90a1); var x37: u64 = undefined; var x38: u1 = undefined; fiatSecp256k1AddcarryxU64(&x37, &x38, 0x0, x36, x1); var x39: u64 = undefined; var x40: u1 = undefined; fiatSecp256k1AddcarryxU64(&x39, &x40, 0x0, x27, x35); var x41: u64 = undefined; var x42: u1 = undefined; fiatSecp256k1AddcarryxU64(&x41, &x42, x40, x29, x37); var x43: u64 = undefined; var x44: u1 = undefined; fiatSecp256k1AddcarryxU64(&x43, &x44, x42, x31, @intCast(u64, x38)); var x45: u64 = undefined; var x46: u1 = undefined; fiatSecp256k1AddcarryxU64(&x45, &x46, x44, x33, @intCast(u64, 0x0)); var x47: u64 = undefined; var x48: u64 = undefined; fiatSecp256k1MulxU64(&x47, &x48, x39, 0xd838091dd2253531); var x49: u64 = undefined; var x50: u64 = undefined; fiatSecp256k1MulxU64(&x49, &x50, x47, 0xffffffffffffffff); var x51: u64 = undefined; var x52: u64 = undefined; fiatSecp256k1MulxU64(&x51, &x52, x47, 0xffffffffffffffff); var x53: u64 = undefined; var x54: u64 = undefined; fiatSecp256k1MulxU64(&x53, &x54, x47, 0xffffffffffffffff); var x55: u64 = undefined; var x56: u64 = undefined; fiatSecp256k1MulxU64(&x55, &x56, x47, 0xfffffffefffffc2f); var x57: u64 = undefined; var x58: u1 = undefined; fiatSecp256k1AddcarryxU64(&x57, &x58, 0x0, x56, x53); var x59: u64 = undefined; var x60: u1 = undefined; fiatSecp256k1AddcarryxU64(&x59, &x60, x58, x54, x51); var x61: u64 = undefined; var x62: u1 = undefined; fiatSecp256k1AddcarryxU64(&x61, &x62, x60, x52, x49); var x63: u64 = undefined; var x64: u1 = undefined; fiatSecp256k1AddcarryxU64(&x63, &x64, 0x0, x39, x55); var x65: u64 = undefined; var x66: u1 = undefined; fiatSecp256k1AddcarryxU64(&x65, &x66, x64, x41, x57); var x67: u64 = undefined; var x68: u1 = undefined; fiatSecp256k1AddcarryxU64(&x67, &x68, x66, x43, x59); var x69: u64 = undefined; var x70: u1 = undefined; fiatSecp256k1AddcarryxU64(&x69, &x70, x68, x45, x61); var x71: u64 = undefined; var x72: u1 = undefined; fiatSecp256k1AddcarryxU64(&x71, &x72, x70, (@intCast(u64, x46) + @intCast(u64, x34)), (@intCast(u64, x62) + x50)); var x73: u64 = undefined; var x74: u64 = undefined; fiatSecp256k1MulxU64(&x73, &x74, x2, 0x7a2000e90a1); var x75: u64 = undefined; var x76: u1 = undefined; fiatSecp256k1AddcarryxU64(&x75, &x76, 0x0, x74, x2); var x77: u64 = undefined; var x78: u1 = undefined; fiatSecp256k1AddcarryxU64(&x77, &x78, 0x0, x65, x73); var x79: u64 = undefined; var x80: u1 = undefined; fiatSecp256k1AddcarryxU64(&x79, &x80, x78, x67, x75); var x81: u64 = undefined; var x82: u1 = undefined; fiatSecp256k1AddcarryxU64(&x81, &x82, x80, x69, @intCast(u64, x76)); var x83: u64 = undefined; var x84: u1 = undefined; fiatSecp256k1AddcarryxU64(&x83, &x84, x82, x71, @intCast(u64, 0x0)); var x85: u64 = undefined; var x86: u64 = undefined; fiatSecp256k1MulxU64(&x85, &x86, x77, 0xd838091dd2253531); var x87: u64 = undefined; var x88: u64 = undefined; fiatSecp256k1MulxU64(&x87, &x88, x85, 0xffffffffffffffff); var x89: u64 = undefined; var x90: u64 = undefined; fiatSecp256k1MulxU64(&x89, &x90, x85, 0xffffffffffffffff); var x91: u64 = undefined; var x92: u64 = undefined; fiatSecp256k1MulxU64(&x91, &x92, x85, 0xffffffffffffffff); var x93: u64 = undefined; var x94: u64 = undefined; fiatSecp256k1MulxU64(&x93, &x94, x85, 0xfffffffefffffc2f); var x95: u64 = undefined; var x96: u1 = undefined; fiatSecp256k1AddcarryxU64(&x95, &x96, 0x0, x94, x91); var x97: u64 = undefined; var x98: u1 = undefined; fiatSecp256k1AddcarryxU64(&x97, &x98, x96, x92, x89); var x99: u64 = undefined; var x100: u1 = undefined; fiatSecp256k1AddcarryxU64(&x99, &x100, x98, x90, x87); var x101: u64 = undefined; var x102: u1 = undefined; fiatSecp256k1AddcarryxU64(&x101, &x102, 0x0, x77, x93); var x103: u64 = undefined; var x104: u1 = undefined; fiatSecp256k1AddcarryxU64(&x103, &x104, x102, x79, x95); var x105: u64 = undefined; var x106: u1 = undefined; fiatSecp256k1AddcarryxU64(&x105, &x106, x104, x81, x97); var x107: u64 = undefined; var x108: u1 = undefined; fiatSecp256k1AddcarryxU64(&x107, &x108, x106, x83, x99); var x109: u64 = undefined; var x110: u1 = undefined; fiatSecp256k1AddcarryxU64(&x109, &x110, x108, (@intCast(u64, x84) + @intCast(u64, x72)), (@intCast(u64, x100) + x88)); var x111: u64 = undefined; var x112: u64 = undefined; fiatSecp256k1MulxU64(&x111, &x112, x3, 0x7a2000e90a1); var x113: u64 = undefined; var x114: u1 = undefined; fiatSecp256k1AddcarryxU64(&x113, &x114, 0x0, x112, x3); var x115: u64 = undefined; var x116: u1 = undefined; fiatSecp256k1AddcarryxU64(&x115, &x116, 0x0, x103, x111); var x117: u64 = undefined; var x118: u1 = undefined; fiatSecp256k1AddcarryxU64(&x117, &x118, x116, x105, x113); var x119: u64 = undefined; var x120: u1 = undefined; fiatSecp256k1AddcarryxU64(&x119, &x120, x118, x107, @intCast(u64, x114)); var x121: u64 = undefined; var x122: u1 = undefined; fiatSecp256k1AddcarryxU64(&x121, &x122, x120, x109, @intCast(u64, 0x0)); var x123: u64 = undefined; var x124: u64 = undefined; fiatSecp256k1MulxU64(&x123, &x124, x115, 0xd838091dd2253531); var x125: u64 = undefined; var x126: u64 = undefined; fiatSecp256k1MulxU64(&x125, &x126, x123, 0xffffffffffffffff); var x127: u64 = undefined; var x128: u64 = undefined; fiatSecp256k1MulxU64(&x127, &x128, x123, 0xffffffffffffffff); var x129: u64 = undefined; var x130: u64 = undefined; fiatSecp256k1MulxU64(&x129, &x130, x123, 0xffffffffffffffff); var x131: u64 = undefined; var x132: u64 = undefined; fiatSecp256k1MulxU64(&x131, &x132, x123, 0xfffffffefffffc2f); var x133: u64 = undefined; var x134: u1 = undefined; fiatSecp256k1AddcarryxU64(&x133, &x134, 0x0, x132, x129); var x135: u64 = undefined; var x136: u1 = undefined; fiatSecp256k1AddcarryxU64(&x135, &x136, x134, x130, x127); var x137: u64 = undefined; var x138: u1 = undefined; fiatSecp256k1AddcarryxU64(&x137, &x138, x136, x128, x125); var x139: u64 = undefined; var x140: u1 = undefined; fiatSecp256k1AddcarryxU64(&x139, &x140, 0x0, x115, x131); var x141: u64 = undefined; var x142: u1 = undefined; fiatSecp256k1AddcarryxU64(&x141, &x142, x140, x117, x133); var x143: u64 = undefined; var x144: u1 = undefined; fiatSecp256k1AddcarryxU64(&x143, &x144, x142, x119, x135); var x145: u64 = undefined; var x146: u1 = undefined; fiatSecp256k1AddcarryxU64(&x145, &x146, x144, x121, x137); var x147: u64 = undefined; var x148: u1 = undefined; fiatSecp256k1AddcarryxU64(&x147, &x148, x146, (@intCast(u64, x122) + @intCast(u64, x110)), (@intCast(u64, x138) + x126)); var x149: u64 = undefined; var x150: u1 = undefined; fiatSecp256k1SubborrowxU64(&x149, &x150, 0x0, x141, 0xfffffffefffffc2f); var x151: u64 = undefined; var x152: u1 = undefined; fiatSecp256k1SubborrowxU64(&x151, &x152, x150, x143, 0xffffffffffffffff); var x153: u64 = undefined; var x154: u1 = undefined; fiatSecp256k1SubborrowxU64(&x153, &x154, x152, x145, 0xffffffffffffffff); var x155: u64 = undefined; var x156: u1 = undefined; fiatSecp256k1SubborrowxU64(&x155, &x156, x154, x147, 0xffffffffffffffff); var x157: u64 = undefined; var x158: u1 = undefined; fiatSecp256k1SubborrowxU64(&x157, &x158, x156, @intCast(u64, x148), @intCast(u64, 0x0)); var x159: u64 = undefined; fiatSecp256k1CmovznzU64(&x159, x158, x149, x141); var x160: u64 = undefined; fiatSecp256k1CmovznzU64(&x160, x158, x151, x143); var x161: u64 = undefined; fiatSecp256k1CmovznzU64(&x161, x158, x153, x145); var x162: u64 = undefined; fiatSecp256k1CmovznzU64(&x162, x158, x155, x147); out1[0] = x159; out1[1] = x160; out1[2] = x161; out1[3] = x162; } /// The function fiatSecp256k1Nonzero outputs a single non-zero word if the input is non-zero and zero otherwise. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// out1 = 0 ↔ eval (from_montgomery arg1) mod m = 0 /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] pub fn fiatSecp256k1Nonzero(out1: *u64, arg1: [4]u64) void { const x1: u64 = ((arg1[0]) | ((arg1[1]) | ((arg1[2]) | (arg1[3])))); out1.* = x1; } /// The function fiatSecp256k1Selectznz 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], [0x0 ~> 0xffffffffffffffff]] /// arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn fiatSecp256k1Selectznz(out1: *[4]u64, arg1: u1, arg2: [4]u64, arg3: [4]u64) void { var x1: u64 = undefined; fiatSecp256k1CmovznzU64(&x1, arg1, (arg2[0]), (arg3[0])); var x2: u64 = undefined; fiatSecp256k1CmovznzU64(&x2, arg1, (arg2[1]), (arg3[1])); var x3: u64 = undefined; fiatSecp256k1CmovznzU64(&x3, arg1, (arg2[2]), (arg3[2])); var x4: u64 = undefined; fiatSecp256k1CmovznzU64(&x4, arg1, (arg2[3]), (arg3[3])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; } /// The function fiatSecp256k1ToBytes serializes a field element NOT in the Montgomery domain to bytes in little-endian order. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..31] /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// 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 ~> 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]] pub fn fiatSecp256k1ToBytes(out1: *[32]u8, arg1: [4]u64) void { const x1: u64 = (arg1[3]); const x2: u64 = (arg1[2]); const x3: u64 = (arg1[1]); const x4: u64 = (arg1[0]); const x5: u8 = @intCast(u8, (x4 & @intCast(u64, 0xff))); const x6: u64 = (x4 >> 8); const x7: u8 = @intCast(u8, (x6 & @intCast(u64, 0xff))); const x8: u64 = (x6 >> 8); const x9: u8 = @intCast(u8, (x8 & @intCast(u64, 0xff))); const x10: u64 = (x8 >> 8); const x11: u8 = @intCast(u8, (x10 & @intCast(u64, 0xff))); const x12: u64 = (x10 >> 8); const x13: u8 = @intCast(u8, (x12 & @intCast(u64, 0xff))); const x14: u64 = (x12 >> 8); const x15: u8 = @intCast(u8, (x14 & @intCast(u64, 0xff))); const x16: u64 = (x14 >> 8); const x17: u8 = @intCast(u8, (x16 & @intCast(u64, 0xff))); const x18: u8 = @intCast(u8, (x16 >> 8)); const x19: u8 = @intCast(u8, (x3 & @intCast(u64, 0xff))); const x20: u64 = (x3 >> 8); const x21: u8 = @intCast(u8, (x20 & @intCast(u64, 0xff))); const x22: u64 = (x20 >> 8); const x23: u8 = @intCast(u8, (x22 & @intCast(u64, 0xff))); const x24: u64 = (x22 >> 8); const x25: u8 = @intCast(u8, (x24 & @intCast(u64, 0xff))); const x26: u64 = (x24 >> 8); const x27: u8 = @intCast(u8, (x26 & @intCast(u64, 0xff))); const x28: u64 = (x26 >> 8); const x29: u8 = @intCast(u8, (x28 & @intCast(u64, 0xff))); const x30: u64 = (x28 >> 8); const x31: u8 = @intCast(u8, (x30 & @intCast(u64, 0xff))); const x32: u8 = @intCast(u8, (x30 >> 8)); const x33: u8 = @intCast(u8, (x2 & @intCast(u64, 0xff))); const x34: u64 = (x2 >> 8); const x35: u8 = @intCast(u8, (x34 & @intCast(u64, 0xff))); const x36: u64 = (x34 >> 8); const x37: u8 = @intCast(u8, (x36 & @intCast(u64, 0xff))); const x38: u64 = (x36 >> 8); const x39: u8 = @intCast(u8, (x38 & @intCast(u64, 0xff))); const x40: u64 = (x38 >> 8); const x41: u8 = @intCast(u8, (x40 & @intCast(u64, 0xff))); const x42: u64 = (x40 >> 8); const x43: u8 = @intCast(u8, (x42 & @intCast(u64, 0xff))); const x44: u64 = (x42 >> 8); const x45: u8 = @intCast(u8, (x44 & @intCast(u64, 0xff))); const x46: u8 = @intCast(u8, (x44 >> 8)); const x47: u8 = @intCast(u8, (x1 & @intCast(u64, 0xff))); const x48: u64 = (x1 >> 8); const x49: u8 = @intCast(u8, (x48 & @intCast(u64, 0xff))); const x50: u64 = (x48 >> 8); const x51: u8 = @intCast(u8, (x50 & @intCast(u64, 0xff))); const x52: u64 = (x50 >> 8); const x53: u8 = @intCast(u8, (x52 & @intCast(u64, 0xff))); const x54: u64 = (x52 >> 8); const x55: u8 = @intCast(u8, (x54 & @intCast(u64, 0xff))); const x56: u64 = (x54 >> 8); const x57: u8 = @intCast(u8, (x56 & @intCast(u64, 0xff))); const x58: u64 = (x56 >> 8); const x59: u8 = @intCast(u8, (x58 & @intCast(u64, 0xff))); const x60: u8 = @intCast(u8, (x58 >> 8)); out1[0] = x5; out1[1] = x7; out1[2] = x9; out1[3] = x11; out1[4] = x13; out1[5] = x15; out1[6] = x17; out1[7] = x18; out1[8] = x19; out1[9] = x21; out1[10] = x23; out1[11] = x25; out1[12] = x27; out1[13] = x29; out1[14] = x31; out1[15] = x32; out1[16] = x33; out1[17] = x35; out1[18] = x37; out1[19] = x39; out1[20] = x41; out1[21] = x43; out1[22] = x45; out1[23] = x46; out1[24] = x47; out1[25] = x49; out1[26] = x51; out1[27] = x53; out1[28] = x55; out1[29] = x57; out1[30] = x59; out1[31] = x60; } /// The function fiatSecp256k1FromBytes deserializes a field element NOT in the Montgomery domain from bytes in little-endian order. /// Preconditions: /// 0 ≤ bytes_eval arg1 < m /// Postconditions: /// eval out1 mod m = bytes_eval arg1 mod m /// 0 ≤ eval out1 < 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 ~> 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]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn fiatSecp256k1FromBytes(out1: *[4]u64, arg1: [32]u8) void { const x1: u64 = (@intCast(u64, (arg1[31])) << 56); const x2: u64 = (@intCast(u64, (arg1[30])) << 48); const x3: u64 = (@intCast(u64, (arg1[29])) << 40); const x4: u64 = (@intCast(u64, (arg1[28])) << 32); const x5: u64 = (@intCast(u64, (arg1[27])) << 24); const x6: u64 = (@intCast(u64, (arg1[26])) << 16); const x7: u64 = (@intCast(u64, (arg1[25])) << 8); const x8: u8 = (arg1[24]); const x9: u64 = (@intCast(u64, (arg1[23])) << 56); const x10: u64 = (@intCast(u64, (arg1[22])) << 48); const x11: u64 = (@intCast(u64, (arg1[21])) << 40); const x12: u64 = (@intCast(u64, (arg1[20])) << 32); const x13: u64 = (@intCast(u64, (arg1[19])) << 24); const x14: u64 = (@intCast(u64, (arg1[18])) << 16); const x15: u64 = (@intCast(u64, (arg1[17])) << 8); const x16: u8 = (arg1[16]); const x17: u64 = (@intCast(u64, (arg1[15])) << 56); const x18: u64 = (@intCast(u64, (arg1[14])) << 48); const x19: u64 = (@intCast(u64, (arg1[13])) << 40); const x20: u64 = (@intCast(u64, (arg1[12])) << 32); const x21: u64 = (@intCast(u64, (arg1[11])) << 24); const x22: u64 = (@intCast(u64, (arg1[10])) << 16); const x23: u64 = (@intCast(u64, (arg1[9])) << 8); const x24: u8 = (arg1[8]); const x25: u64 = (@intCast(u64, (arg1[7])) << 56); const x26: u64 = (@intCast(u64, (arg1[6])) << 48); const x27: u64 = (@intCast(u64, (arg1[5])) << 40); const x28: u64 = (@intCast(u64, (arg1[4])) << 32); const x29: u64 = (@intCast(u64, (arg1[3])) << 24); const x30: u64 = (@intCast(u64, (arg1[2])) << 16); const x31: u64 = (@intCast(u64, (arg1[1])) << 8); const x32: u8 = (arg1[0]); const x33: u64 = (x31 + @intCast(u64, x32)); const x34: u64 = (x30 + x33); const x35: u64 = (x29 + x34); const x36: u64 = (x28 + x35); const x37: u64 = (x27 + x36); const x38: u64 = (x26 + x37); const x39: u64 = (x25 + x38); const x40: u64 = (x23 + @intCast(u64, x24)); const x41: u64 = (x22 + x40); const x42: u64 = (x21 + x41); const x43: u64 = (x20 + x42); const x44: u64 = (x19 + x43); const x45: u64 = (x18 + x44); const x46: u64 = (x17 + x45); const x47: u64 = (x15 + @intCast(u64, x16)); const x48: u64 = (x14 + x47); const x49: u64 = (x13 + x48); const x50: u64 = (x12 + x49); const x51: u64 = (x11 + x50); const x52: u64 = (x10 + x51); const x53: u64 = (x9 + x52); const x54: u64 = (x7 + @intCast(u64, x8)); const x55: u64 = (x6 + x54); const x56: u64 = (x5 + x55); const x57: u64 = (x4 + x56); const x58: u64 = (x3 + x57); const x59: u64 = (x2 + x58); const x60: u64 = (x1 + x59); out1[0] = x39; out1[1] = x46; out1[2] = x53; out1[3] = x60; } /// The function fiatSecp256k1SetOne returns the field element one in the Montgomery domain. /// Postconditions: /// eval (from_montgomery out1) mod m = 1 mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn fiatSecp256k1SetOne(out1: *[4]u64) void { out1[0] = 0x1000003d1; out1[1] = @intCast(u64, 0x0); out1[2] = @intCast(u64, 0x0); out1[3] = @intCast(u64, 0x0); } /// The function fiatSecp256k1Msat returns the saturated representation of the prime modulus. /// Postconditions: /// twos_complement_eval out1 = m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn fiatSecp256k1Msat(out1: *[5]u64) void { out1[0] = 0xfffffffefffffc2f; out1[1] = 0xffffffffffffffff; out1[2] = 0xffffffffffffffff; out1[3] = 0xffffffffffffffff; out1[4] = @intCast(u64, 0x0); } /// The function fiatSecp256k1Divstep computes a divstep. /// Preconditions: /// 0 ≤ eval arg4 < m /// 0 ≤ eval arg5 < m /// Postconditions: /// out1 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then 1 - arg1 else 1 + arg1) /// twos_complement_eval out2 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then twos_complement_eval arg3 else twos_complement_eval arg2) /// twos_complement_eval out3 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then ⌊(twos_complement_eval arg3 - twos_complement_eval arg2) / 2⌋ else ⌊(twos_complement_eval arg3 + (twos_complement_eval arg3 mod 2) * twos_complement_eval arg2) / 2⌋) /// eval (from_montgomery out4) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (2 * eval (from_montgomery arg5)) mod m else (2 * eval (from_montgomery arg4)) mod m) /// eval (from_montgomery out5) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (eval (from_montgomery arg4) - eval (from_montgomery arg4)) mod m else (eval (from_montgomery arg5) + (twos_complement_eval arg3 mod 2) * eval (from_montgomery arg4)) mod m) /// 0 ≤ eval out5 < m /// 0 ≤ eval out5 < m /// 0 ≤ eval out2 < m /// 0 ≤ eval out3 < m /// /// Input Bounds: /// arg1: [0x0 ~> 0xffffffffffffffff] /// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg4: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg5: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] /// out2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// out3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// out4: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// out5: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn fiatSecp256k1Divstep(out1: *u64, out2: *[5]u64, out3: *[5]u64, out4: *[4]u64, out5: *[4]u64, arg1: u64, arg2: [5]u64, arg3: [5]u64, arg4: [4]u64, arg5: [4]u64) void { var x1: u64 = undefined; var x2: u1 = undefined; fiatSecp256k1AddcarryxU64(&x1, &x2, 0x0, (~arg1), @intCast(u64, 0x1)); const x3: u1 = (@intCast(u1, (x1 >> 63)) & @intCast(u1, ((arg3[0]) & @intCast(u64, 0x1)))); var x4: u64 = undefined; var x5: u1 = undefined; fiatSecp256k1AddcarryxU64(&x4, &x5, 0x0, (~arg1), @intCast(u64, 0x1)); var x6: u64 = undefined; fiatSecp256k1CmovznzU64(&x6, x3, arg1, x4); var x7: u64 = undefined; fiatSecp256k1CmovznzU64(&x7, x3, (arg2[0]), (arg3[0])); var x8: u64 = undefined; fiatSecp256k1CmovznzU64(&x8, x3, (arg2[1]), (arg3[1])); var x9: u64 = undefined; fiatSecp256k1CmovznzU64(&x9, x3, (arg2[2]), (arg3[2])); var x10: u64 = undefined; fiatSecp256k1CmovznzU64(&x10, x3, (arg2[3]), (arg3[3])); var x11: u64 = undefined; fiatSecp256k1CmovznzU64(&x11, x3, (arg2[4]), (arg3[4])); var x12: u64 = undefined; var x13: u1 = undefined; fiatSecp256k1AddcarryxU64(&x12, &x13, 0x0, @intCast(u64, 0x1), (~(arg2[0]))); var x14: u64 = undefined; var x15: u1 = undefined; fiatSecp256k1AddcarryxU64(&x14, &x15, x13, @intCast(u64, 0x0), (~(arg2[1]))); var x16: u64 = undefined; var x17: u1 = undefined; fiatSecp256k1AddcarryxU64(&x16, &x17, x15, @intCast(u64, 0x0), (~(arg2[2]))); var x18: u64 = undefined; var x19: u1 = undefined; fiatSecp256k1AddcarryxU64(&x18, &x19, x17, @intCast(u64, 0x0), (~(arg2[3]))); var x20: u64 = undefined; var x21: u1 = undefined; fiatSecp256k1AddcarryxU64(&x20, &x21, x19, @intCast(u64, 0x0), (~(arg2[4]))); var x22: u64 = undefined; fiatSecp256k1CmovznzU64(&x22, x3, (arg3[0]), x12); var x23: u64 = undefined; fiatSecp256k1CmovznzU64(&x23, x3, (arg3[1]), x14); var x24: u64 = undefined; fiatSecp256k1CmovznzU64(&x24, x3, (arg3[2]), x16); var x25: u64 = undefined; fiatSecp256k1CmovznzU64(&x25, x3, (arg3[3]), x18); var x26: u64 = undefined; fiatSecp256k1CmovznzU64(&x26, x3, (arg3[4]), x20); var x27: u64 = undefined; fiatSecp256k1CmovznzU64(&x27, x3, (arg4[0]), (arg5[0])); var x28: u64 = undefined; fiatSecp256k1CmovznzU64(&x28, x3, (arg4[1]), (arg5[1])); var x29: u64 = undefined; fiatSecp256k1CmovznzU64(&x29, x3, (arg4[2]), (arg5[2])); var x30: u64 = undefined; fiatSecp256k1CmovznzU64(&x30, x3, (arg4[3]), (arg5[3])); var x31: u64 = undefined; var x32: u1 = undefined; fiatSecp256k1AddcarryxU64(&x31, &x32, 0x0, x27, x27); var x33: u64 = undefined; var x34: u1 = undefined; fiatSecp256k1AddcarryxU64(&x33, &x34, x32, x28, x28); var x35: u64 = undefined; var x36: u1 = undefined; fiatSecp256k1AddcarryxU64(&x35, &x36, x34, x29, x29); var x37: u64 = undefined; var x38: u1 = undefined; fiatSecp256k1AddcarryxU64(&x37, &x38, x36, x30, x30); var x39: u64 = undefined; var x40: u1 = undefined; fiatSecp256k1SubborrowxU64(&x39, &x40, 0x0, x31, 0xfffffffefffffc2f); var x41: u64 = undefined; var x42: u1 = undefined; fiatSecp256k1SubborrowxU64(&x41, &x42, x40, x33, 0xffffffffffffffff); var x43: u64 = undefined; var x44: u1 = undefined; fiatSecp256k1SubborrowxU64(&x43, &x44, x42, x35, 0xffffffffffffffff); var x45: u64 = undefined; var x46: u1 = undefined; fiatSecp256k1SubborrowxU64(&x45, &x46, x44, x37, 0xffffffffffffffff); var x47: u64 = undefined; var x48: u1 = undefined; fiatSecp256k1SubborrowxU64(&x47, &x48, x46, @intCast(u64, x38), @intCast(u64, 0x0)); const x49: u64 = (arg4[3]); const x50: u64 = (arg4[2]); const x51: u64 = (arg4[1]); const x52: u64 = (arg4[0]); var x53: u64 = undefined; var x54: u1 = undefined; fiatSecp256k1SubborrowxU64(&x53, &x54, 0x0, @intCast(u64, 0x0), x52); var x55: u64 = undefined; var x56: u1 = undefined; fiatSecp256k1SubborrowxU64(&x55, &x56, x54, @intCast(u64, 0x0), x51); var x57: u64 = undefined; var x58: u1 = undefined; fiatSecp256k1SubborrowxU64(&x57, &x58, x56, @intCast(u64, 0x0), x50); var x59: u64 = undefined; var x60: u1 = undefined; fiatSecp256k1SubborrowxU64(&x59, &x60, x58, @intCast(u64, 0x0), x49); var x61: u64 = undefined; fiatSecp256k1CmovznzU64(&x61, x60, @intCast(u64, 0x0), 0xffffffffffffffff); var x62: u64 = undefined; var x63: u1 = undefined; fiatSecp256k1AddcarryxU64(&x62, &x63, 0x0, x53, (x61 & 0xfffffffefffffc2f)); var x64: u64 = undefined; var x65: u1 = undefined; fiatSecp256k1AddcarryxU64(&x64, &x65, x63, x55, x61); var x66: u64 = undefined; var x67: u1 = undefined; fiatSecp256k1AddcarryxU64(&x66, &x67, x65, x57, x61); var x68: u64 = undefined; var x69: u1 = undefined; fiatSecp256k1AddcarryxU64(&x68, &x69, x67, x59, x61); var x70: u64 = undefined; fiatSecp256k1CmovznzU64(&x70, x3, (arg5[0]), x62); var x71: u64 = undefined; fiatSecp256k1CmovznzU64(&x71, x3, (arg5[1]), x64); var x72: u64 = undefined; fiatSecp256k1CmovznzU64(&x72, x3, (arg5[2]), x66); var x73: u64 = undefined; fiatSecp256k1CmovznzU64(&x73, x3, (arg5[3]), x68); const x74: u1 = @intCast(u1, (x22 & @intCast(u64, 0x1))); var x75: u64 = undefined; fiatSecp256k1CmovznzU64(&x75, x74, @intCast(u64, 0x0), x7); var x76: u64 = undefined; fiatSecp256k1CmovznzU64(&x76, x74, @intCast(u64, 0x0), x8); var x77: u64 = undefined; fiatSecp256k1CmovznzU64(&x77, x74, @intCast(u64, 0x0), x9); var x78: u64 = undefined; fiatSecp256k1CmovznzU64(&x78, x74, @intCast(u64, 0x0), x10); var x79: u64 = undefined; fiatSecp256k1CmovznzU64(&x79, x74, @intCast(u64, 0x0), x11); var x80: u64 = undefined; var x81: u1 = undefined; fiatSecp256k1AddcarryxU64(&x80, &x81, 0x0, x22, x75); var x82: u64 = undefined; var x83: u1 = undefined; fiatSecp256k1AddcarryxU64(&x82, &x83, x81, x23, x76); var x84: u64 = undefined; var x85: u1 = undefined; fiatSecp256k1AddcarryxU64(&x84, &x85, x83, x24, x77); var x86: u64 = undefined; var x87: u1 = undefined; fiatSecp256k1AddcarryxU64(&x86, &x87, x85, x25, x78); var x88: u64 = undefined; var x89: u1 = undefined; fiatSecp256k1AddcarryxU64(&x88, &x89, x87, x26, x79); var x90: u64 = undefined; fiatSecp256k1CmovznzU64(&x90, x74, @intCast(u64, 0x0), x27); var x91: u64 = undefined; fiatSecp256k1CmovznzU64(&x91, x74, @intCast(u64, 0x0), x28); var x92: u64 = undefined; fiatSecp256k1CmovznzU64(&x92, x74, @intCast(u64, 0x0), x29); var x93: u64 = undefined; fiatSecp256k1CmovznzU64(&x93, x74, @intCast(u64, 0x0), x30); var x94: u64 = undefined; var x95: u1 = undefined; fiatSecp256k1AddcarryxU64(&x94, &x95, 0x0, x70, x90); var x96: u64 = undefined; var x97: u1 = undefined; fiatSecp256k1AddcarryxU64(&x96, &x97, x95, x71, x91); var x98: u64 = undefined; var x99: u1 = undefined; fiatSecp256k1AddcarryxU64(&x98, &x99, x97, x72, x92); var x100: u64 = undefined; var x101: u1 = undefined; fiatSecp256k1AddcarryxU64(&x100, &x101, x99, x73, x93); var x102: u64 = undefined; var x103: u1 = undefined; fiatSecp256k1SubborrowxU64(&x102, &x103, 0x0, x94, 0xfffffffefffffc2f); var x104: u64 = undefined; var x105: u1 = undefined; fiatSecp256k1SubborrowxU64(&x104, &x105, x103, x96, 0xffffffffffffffff); var x106: u64 = undefined; var x107: u1 = undefined; fiatSecp256k1SubborrowxU64(&x106, &x107, x105, x98, 0xffffffffffffffff); var x108: u64 = undefined; var x109: u1 = undefined; fiatSecp256k1SubborrowxU64(&x108, &x109, x107, x100, 0xffffffffffffffff); var x110: u64 = undefined; var x111: u1 = undefined; fiatSecp256k1SubborrowxU64(&x110, &x111, x109, @intCast(u64, x101), @intCast(u64, 0x0)); var x112: u64 = undefined; var x113: u1 = undefined; fiatSecp256k1AddcarryxU64(&x112, &x113, 0x0, x6, @intCast(u64, 0x1)); const x114: u64 = ((x80 >> 1) | ((x82 << 63) & 0xffffffffffffffff)); const x115: u64 = ((x82 >> 1) | ((x84 << 63) & 0xffffffffffffffff)); const x116: u64 = ((x84 >> 1) | ((x86 << 63) & 0xffffffffffffffff)); const x117: u64 = ((x86 >> 1) | ((x88 << 63) & 0xffffffffffffffff)); const x118: u64 = ((x88 & 0x8000000000000000) | (x88 >> 1)); var x119: u64 = undefined; fiatSecp256k1CmovznzU64(&x119, x48, x39, x31); var x120: u64 = undefined; fiatSecp256k1CmovznzU64(&x120, x48, x41, x33); var x121: u64 = undefined; fiatSecp256k1CmovznzU64(&x121, x48, x43, x35); var x122: u64 = undefined; fiatSecp256k1CmovznzU64(&x122, x48, x45, x37); var x123: u64 = undefined; fiatSecp256k1CmovznzU64(&x123, x111, x102, x94); var x124: u64 = undefined; fiatSecp256k1CmovznzU64(&x124, x111, x104, x96); var x125: u64 = undefined; fiatSecp256k1CmovznzU64(&x125, x111, x106, x98); var x126: u64 = undefined; fiatSecp256k1CmovznzU64(&x126, x111, x108, x100); out1.* = x112; out2[0] = x7; out2[1] = x8; out2[2] = x9; out2[3] = x10; out2[4] = x11; out3[0] = x114; out3[1] = x115; out3[2] = x116; out3[3] = x117; out3[4] = x118; out4[0] = x119; out4[1] = x120; out4[2] = x121; out4[3] = x122; out5[0] = x123; out5[1] = x124; out5[2] = x125; out5[3] = x126; } /// The function fiatSecp256k1DivstepPrecomp returns the precomputed value for Bernstein-Yang-inversion (in montgomery form). /// Postconditions: /// eval (from_montgomery out1) = ⌊(m - 1) / 2⌋^(if (log2 m) + 1 < 46 then ⌊(49 * ((log2 m) + 1) + 80) / 17⌋ else ⌊(49 * ((log2 m) + 1) + 57) / 17⌋) /// 0 ≤ eval out1 < m /// /// Input Bounds: /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn fiatSecp256k1DivstepPrecomp(out1: *[4]u64) void { out1[0] = 0xf201a41831525e0a; out1[1] = 0x9953f9ddcd648d85; out1[2] = 0xe86029463db210a9; out1[3] = 0x24fb8a3104b03709; }
fiat-zig/src/secp256k1_64.zig
const std = @import("std"); const parseInt = std.fmt.parseInt; const indexOf = std.mem.indexOf; const SEP = " -> "; const Coord = struct { x: i32, y: i32 }; const Coords = std.AutoHashMap(Coord, u32); pub fn main() !void { const file = try std.fs.cwd().openFile("../inputs/05.txt", .{}); defer file.close(); std.log.info("part 1: {d}", .{run(file, false)}); std.log.info("part 2: {d}", .{run(file, true)}); } pub fn run(file: std.fs.File, with_diagonals: bool) !u32 { var gpalloc = std.heap.GeneralPurposeAllocator(.{}){}; var allocator = &gpalloc.allocator; defer std.debug.assert(!gpalloc.deinit()); try file.seekTo(0); var reader = file.reader(); var buf: [32]u8 = undefined; var coords = Coords.init(allocator); defer coords.deinit(); while (try reader.readUntilDelimiterOrEof(&buf, '\n')) |line| { const sep_idx = indexOf(u8, line, SEP) orelse return error.InvalidCoords; const from = try parseCoord(line[0..sep_idx]); const to = try parseCoord(line[sep_idx + SEP.len ..]); if (with_diagonals or from.x == to.x or from.y == to.y) { try addCoords(&coords, from, to); } } var answer: u32 = 0; var coords_iter = coords.valueIterator(); while (coords_iter.next()) |count| { if (count.* > 1) answer += 1; } return answer; } fn parseCoord(text: []const u8) !Coord { const comma_idx = indexOf(u8, text, ",") orelse return error.InvalidCoords; const x = try parseInt(i32, text[0..comma_idx], 10); const y = try parseInt(i32, text[comma_idx + 1 ..], 10); return Coord{ .x = x, .y = y }; } fn addCoords(coords: *Coords, from: Coord, to: Coord) !void { var inc_x: i8 = 0; var inc_y: i8 = 0; if (from.x > to.x) inc_x = -1 else if (from.x < to.x) inc_x = 1; if (from.y > to.y) inc_y = -1 else if (from.y < to.y) inc_y = 1; var x = from.x; var y = from.y; while (true) { const result = try coords.getOrPut(Coord{ .x = x, .y = y }); if (!result.found_existing) result.value_ptr.* = 0; result.value_ptr.* += 1; if (x == to.x and y == to.y) break; x += inc_x; y += inc_y; } }
2021/zig/05.zig
const xcb = @import("../xcb.zig"); pub const id = xcb.Extension{ .name = "XFree86-VidModeExtension", .global_id = 0 }; pub const SYNCRANGE = u32; pub const DOTCLOCK = u32; pub const ModeFlag = extern enum(c_uint) { @"Positive_HSync" = 1, @"Negative_HSync" = 2, @"Positive_VSync" = 4, @"Negative_VSync" = 8, @"Interlace" = 16, @"Composite_Sync" = 32, @"Positive_CSync" = 64, @"Negative_CSync" = 128, @"HSkew" = 256, @"Broadcast" = 512, @"Pixmux" = 1024, @"Double_Clock" = 2048, @"Half_Clock" = 4096, }; pub const ClockFlag = extern enum(c_uint) { @"Programable" = 1, }; pub const Permission = extern enum(c_uint) { @"Read" = 1, @"Write" = 2, }; /// @brief ModeInfo pub const ModeInfo = struct { @"dotclock": xcb.xf86vidmode.DOTCLOCK, @"hdisplay": u16, @"hsyncstart": u16, @"hsyncend": u16, @"htotal": u16, @"hskew": u32, @"vdisplay": u16, @"vsyncstart": u16, @"vsyncend": u16, @"vtotal": u16, @"pad0": [4]u8, @"flags": u32, @"pad1": [12]u8, @"privsize": 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, }; /// @brief QueryVersionReply pub const QueryVersionReply = struct { @"response_type": u8, @"pad0": u8, @"sequence": u16, @"length": u32, @"major_version": u16, @"minor_version": u16, }; /// @brief GetModeLinecookie pub const GetModeLinecookie = struct { sequence: c_uint, }; /// @brief GetModeLineRequest pub const GetModeLineRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 1, @"length": u16, @"screen": u16, @"pad0": [2]u8, }; /// @brief GetModeLineReply pub const GetModeLineReply = struct { @"response_type": u8, @"pad0": u8, @"sequence": u16, @"length": u32, @"dotclock": xcb.xf86vidmode.DOTCLOCK, @"hdisplay": u16, @"hsyncstart": u16, @"hsyncend": u16, @"htotal": u16, @"hskew": u16, @"vdisplay": u16, @"vsyncstart": u16, @"vsyncend": u16, @"vtotal": u16, @"pad1": [2]u8, @"flags": u32, @"pad2": [12]u8, @"privsize": u32, @"private": []u8, }; /// @brief ModModeLineRequest pub const ModModeLineRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 2, @"length": u16, @"screen": u32, @"hdisplay": u16, @"hsyncstart": u16, @"hsyncend": u16, @"htotal": u16, @"hskew": u16, @"vdisplay": u16, @"vsyncstart": u16, @"vsyncend": u16, @"vtotal": u16, @"pad0": [2]u8, @"flags": u32, @"pad1": [12]u8, @"privsize": u32, @"private": []const u8, }; /// @brief SwitchModeRequest pub const SwitchModeRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 3, @"length": u16, @"screen": u16, @"zoom": u16, }; /// @brief GetMonitorcookie pub const GetMonitorcookie = struct { sequence: c_uint, }; /// @brief GetMonitorRequest pub const GetMonitorRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 4, @"length": u16, @"screen": u16, @"pad0": [2]u8, }; /// @brief GetMonitorReply pub const GetMonitorReply = struct { @"response_type": u8, @"pad0": u8, @"sequence": u16, @"length": u32, @"vendor_length": u8, @"model_length": u8, @"num_hsync": u8, @"num_vsync": u8, @"pad1": [20]u8, @"hsync": []xcb.xf86vidmode.SYNCRANGE, @"vsync": []xcb.xf86vidmode.SYNCRANGE, @"vendor": []u8, @"alignment_pad": []u8, @"model": []u8, }; /// @brief LockModeSwitchRequest pub const LockModeSwitchRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 5, @"length": u16, @"screen": u16, @"lock": u16, }; /// @brief GetAllModeLinescookie pub const GetAllModeLinescookie = struct { sequence: c_uint, }; /// @brief GetAllModeLinesRequest pub const GetAllModeLinesRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 6, @"length": u16, @"screen": u16, @"pad0": [2]u8, }; /// @brief GetAllModeLinesReply pub const GetAllModeLinesReply = struct { @"response_type": u8, @"pad0": u8, @"sequence": u16, @"length": u32, @"modecount": u32, @"pad1": [20]u8, @"modeinfo": []xcb.xf86vidmode.ModeInfo, }; /// @brief AddModeLineRequest pub const AddModeLineRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 7, @"length": u16, @"screen": u32, @"dotclock": xcb.xf86vidmode.DOTCLOCK, @"hdisplay": u16, @"hsyncstart": u16, @"hsyncend": u16, @"htotal": u16, @"hskew": u16, @"vdisplay": u16, @"vsyncstart": u16, @"vsyncend": u16, @"vtotal": u16, @"pad0": [2]u8, @"flags": u32, @"pad1": [12]u8, @"privsize": u32, @"after_dotclock": xcb.xf86vidmode.DOTCLOCK, @"after_hdisplay": u16, @"after_hsyncstart": u16, @"after_hsyncend": u16, @"after_htotal": u16, @"after_hskew": u16, @"after_vdisplay": u16, @"after_vsyncstart": u16, @"after_vsyncend": u16, @"after_vtotal": u16, @"pad2": [2]u8, @"after_flags": u32, @"pad3": [12]u8, @"private": []const u8, }; /// @brief DeleteModeLineRequest pub const DeleteModeLineRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 8, @"length": u16, @"screen": u32, @"dotclock": xcb.xf86vidmode.DOTCLOCK, @"hdisplay": u16, @"hsyncstart": u16, @"hsyncend": u16, @"htotal": u16, @"hskew": u16, @"vdisplay": u16, @"vsyncstart": u16, @"vsyncend": u16, @"vtotal": u16, @"pad0": [2]u8, @"flags": u32, @"pad1": [12]u8, @"privsize": u32, @"private": []const u8, }; /// @brief ValidateModeLinecookie pub const ValidateModeLinecookie = struct { sequence: c_uint, }; /// @brief ValidateModeLineRequest pub const ValidateModeLineRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 9, @"length": u16, @"screen": u32, @"dotclock": xcb.xf86vidmode.DOTCLOCK, @"hdisplay": u16, @"hsyncstart": u16, @"hsyncend": u16, @"htotal": u16, @"hskew": u16, @"vdisplay": u16, @"vsyncstart": u16, @"vsyncend": u16, @"vtotal": u16, @"pad0": [2]u8, @"flags": u32, @"pad1": [12]u8, @"privsize": u32, @"private": []const u8, }; /// @brief ValidateModeLineReply pub const ValidateModeLineReply = struct { @"response_type": u8, @"pad0": u8, @"sequence": u16, @"length": u32, @"status": u32, @"pad1": [20]u8, }; /// @brief SwitchToModeRequest pub const SwitchToModeRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 10, @"length": u16, @"screen": u32, @"dotclock": xcb.xf86vidmode.DOTCLOCK, @"hdisplay": u16, @"hsyncstart": u16, @"hsyncend": u16, @"htotal": u16, @"hskew": u16, @"vdisplay": u16, @"vsyncstart": u16, @"vsyncend": u16, @"vtotal": u16, @"pad0": [2]u8, @"flags": u32, @"pad1": [12]u8, @"privsize": u32, @"private": []const u8, }; /// @brief GetViewPortcookie pub const GetViewPortcookie = struct { sequence: c_uint, }; /// @brief GetViewPortRequest pub const GetViewPortRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 11, @"length": u16, @"screen": u16, @"pad0": [2]u8, }; /// @brief GetViewPortReply pub const GetViewPortReply = struct { @"response_type": u8, @"pad0": u8, @"sequence": u16, @"length": u32, @"x": u32, @"y": u32, @"pad1": [16]u8, }; /// @brief SetViewPortRequest pub const SetViewPortRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 12, @"length": u16, @"screen": u16, @"pad0": [2]u8, @"x": u32, @"y": u32, }; /// @brief GetDotClockscookie pub const GetDotClockscookie = struct { sequence: c_uint, }; /// @brief GetDotClocksRequest pub const GetDotClocksRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 13, @"length": u16, @"screen": u16, @"pad0": [2]u8, }; /// @brief GetDotClocksReply pub const GetDotClocksReply = struct { @"response_type": u8, @"pad0": u8, @"sequence": u16, @"length": u32, @"flags": u32, @"clocks": u32, @"maxclocks": u32, @"pad1": [12]u8, @"clock": []u32, }; /// @brief SetClientVersionRequest pub const SetClientVersionRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 14, @"length": u16, @"major": u16, @"minor": u16, }; /// @brief SetGammaRequest pub const SetGammaRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 15, @"length": u16, @"screen": u16, @"pad0": [2]u8, @"red": u32, @"green": u32, @"blue": u32, @"pad1": [12]u8, }; /// @brief GetGammacookie pub const GetGammacookie = struct { sequence: c_uint, }; /// @brief GetGammaRequest pub const GetGammaRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 16, @"length": u16, @"screen": u16, @"pad0": [26]u8, }; /// @brief GetGammaReply pub const GetGammaReply = struct { @"response_type": u8, @"pad0": u8, @"sequence": u16, @"length": u32, @"red": u32, @"green": u32, @"blue": u32, @"pad1": [12]u8, }; /// @brief GetGammaRampcookie pub const GetGammaRampcookie = struct { sequence: c_uint, }; /// @brief GetGammaRampRequest pub const GetGammaRampRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 17, @"length": u16, @"screen": u16, @"size": u16, }; /// @brief GetGammaRampReply pub const GetGammaRampReply = struct { @"response_type": u8, @"pad0": u8, @"sequence": u16, @"length": u32, @"size": u16, @"pad1": [22]u8, @"red": []u16, @"green": []u16, @"blue": []u16, }; /// @brief SetGammaRampRequest pub const SetGammaRampRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 18, @"length": u16, @"screen": u16, @"size": u16, @"red": []const u16, @"green": []const u16, @"blue": []const u16, }; /// @brief GetGammaRampSizecookie pub const GetGammaRampSizecookie = struct { sequence: c_uint, }; /// @brief GetGammaRampSizeRequest pub const GetGammaRampSizeRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 19, @"length": u16, @"screen": u16, @"pad0": [2]u8, }; /// @brief GetGammaRampSizeReply pub const GetGammaRampSizeReply = struct { @"response_type": u8, @"pad0": u8, @"sequence": u16, @"length": u32, @"size": u16, @"pad1": [22]u8, }; /// @brief GetPermissionscookie pub const GetPermissionscookie = struct { sequence: c_uint, }; /// @brief GetPermissionsRequest pub const GetPermissionsRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 20, @"length": u16, @"screen": u16, @"pad0": [2]u8, }; /// @brief GetPermissionsReply pub const GetPermissionsReply = struct { @"response_type": u8, @"pad0": u8, @"sequence": u16, @"length": u32, @"permissions": u32, @"pad1": [20]u8, }; /// Opcode for BadClock. pub const BadClockOpcode = 0; /// @brief BadClockError pub const BadClockError = struct { @"response_type": u8, @"error_code": u8, @"sequence": u16, }; /// Opcode for BadHTimings. pub const BadHTimingsOpcode = 1; /// @brief BadHTimingsError pub const BadHTimingsError = struct { @"response_type": u8, @"error_code": u8, @"sequence": u16, }; /// Opcode for BadVTimings. pub const BadVTimingsOpcode = 2; /// @brief BadVTimingsError pub const BadVTimingsError = struct { @"response_type": u8, @"error_code": u8, @"sequence": u16, }; /// Opcode for ModeUnsuitable. pub const ModeUnsuitableOpcode = 3; /// @brief ModeUnsuitableError pub const ModeUnsuitableError = struct { @"response_type": u8, @"error_code": u8, @"sequence": u16, }; /// Opcode for ExtensionDisabled. pub const ExtensionDisabledOpcode = 4; /// @brief ExtensionDisabledError pub const ExtensionDisabledError = struct { @"response_type": u8, @"error_code": u8, @"sequence": u16, }; /// Opcode for ClientNotLocal. pub const ClientNotLocalOpcode = 5; /// @brief ClientNotLocalError pub const ClientNotLocalError = struct { @"response_type": u8, @"error_code": u8, @"sequence": u16, }; /// Opcode for ZoomLocked. pub const ZoomLockedOpcode = 6; /// @brief ZoomLockedError pub const ZoomLockedError = struct { @"response_type": u8, @"error_code": u8, @"sequence": u16, }; test "" { @import("std").testing.refAllDecls(@This()); }
src/auto/xf86vidmode.zig
const std = @import("../std.zig"); const CpuFeature = std.Target.Cpu.Feature; const CpuModel = std.Target.Cpu.Model; pub const Feature = enum { @"64bit", a, c, d, e, f, m, relax, reserve_x1, reserve_x10, reserve_x11, reserve_x12, reserve_x13, reserve_x14, reserve_x15, reserve_x16, reserve_x17, reserve_x18, reserve_x19, reserve_x2, reserve_x20, reserve_x21, reserve_x22, reserve_x23, reserve_x24, reserve_x25, reserve_x26, reserve_x27, reserve_x28, reserve_x29, reserve_x3, reserve_x30, reserve_x31, reserve_x4, reserve_x5, reserve_x6, reserve_x7, reserve_x8, reserve_x9, rvc_hints, }; pub usingnamespace CpuFeature.feature_set_fns(Feature); pub const all_features = blk: { const len = @typeInfo(Feature).Enum.fields.len; std.debug.assert(len <= CpuFeature.Set.needed_bit_count); var result: [len]CpuFeature = undefined; result[@enumToInt(Feature.@"64bit")] = .{ .llvm_name = "64bit", .description = "Implements RV64", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.a)] = .{ .llvm_name = "a", .description = "'A' (Atomic Instructions)", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.c)] = .{ .llvm_name = "c", .description = "'C' (Compressed Instructions)", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.d)] = .{ .llvm_name = "d", .description = "'D' (Double-Precision Floating-Point)", .dependencies = featureSet(&[_]Feature{ .f, }), }; result[@enumToInt(Feature.e)] = .{ .llvm_name = "e", .description = "Implements RV32E (provides 16 rather than 32 GPRs)", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.f)] = .{ .llvm_name = "f", .description = "'F' (Single-Precision Floating-Point)", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.m)] = .{ .llvm_name = "m", .description = "'M' (Integer Multiplication and Division)", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.relax)] = .{ .llvm_name = "relax", .description = "Enable Linker relaxation.", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x1)] = .{ .llvm_name = "reserve-x1", .description = "Reserve X1", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x10)] = .{ .llvm_name = "reserve-x10", .description = "Reserve X10", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x11)] = .{ .llvm_name = "reserve-x11", .description = "Reserve X11", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x12)] = .{ .llvm_name = "reserve-x12", .description = "Reserve X12", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x13)] = .{ .llvm_name = "reserve-x13", .description = "Reserve X13", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x14)] = .{ .llvm_name = "reserve-x14", .description = "Reserve X14", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x15)] = .{ .llvm_name = "reserve-x15", .description = "Reserve X15", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x16)] = .{ .llvm_name = "reserve-x16", .description = "Reserve X16", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x17)] = .{ .llvm_name = "reserve-x17", .description = "Reserve X17", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x18)] = .{ .llvm_name = "reserve-x18", .description = "Reserve X18", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x19)] = .{ .llvm_name = "reserve-x19", .description = "Reserve X19", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x2)] = .{ .llvm_name = "reserve-x2", .description = "Reserve X2", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x20)] = .{ .llvm_name = "reserve-x20", .description = "Reserve X20", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x21)] = .{ .llvm_name = "reserve-x21", .description = "Reserve X21", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x22)] = .{ .llvm_name = "reserve-x22", .description = "Reserve X22", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x23)] = .{ .llvm_name = "reserve-x23", .description = "Reserve X23", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x24)] = .{ .llvm_name = "reserve-x24", .description = "Reserve X24", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x25)] = .{ .llvm_name = "reserve-x25", .description = "Reserve X25", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x26)] = .{ .llvm_name = "reserve-x26", .description = "Reserve X26", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x27)] = .{ .llvm_name = "reserve-x27", .description = "Reserve X27", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x28)] = .{ .llvm_name = "reserve-x28", .description = "Reserve X28", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x29)] = .{ .llvm_name = "reserve-x29", .description = "Reserve X29", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x3)] = .{ .llvm_name = "reserve-x3", .description = "Reserve X3", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x30)] = .{ .llvm_name = "reserve-x30", .description = "Reserve X30", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x31)] = .{ .llvm_name = "reserve-x31", .description = "Reserve X31", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x4)] = .{ .llvm_name = "reserve-x4", .description = "Reserve X4", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x5)] = .{ .llvm_name = "reserve-x5", .description = "Reserve X5", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x6)] = .{ .llvm_name = "reserve-x6", .description = "Reserve X6", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x7)] = .{ .llvm_name = "reserve-x7", .description = "Reserve X7", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x8)] = .{ .llvm_name = "reserve-x8", .description = "Reserve X8", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.reserve_x9)] = .{ .llvm_name = "reserve-x9", .description = "Reserve X9", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.rvc_hints)] = .{ .llvm_name = "rvc-hints", .description = "Enable RVC Hint Instructions.", .dependencies = featureSet(&[_]Feature{}), }; const ti = @typeInfo(Feature); for (result) |*elem, i| { elem.index = i; elem.name = ti.Enum.fields[i].name; } break :blk result; }; pub const cpu = struct { pub const baseline_rv32 = CpuModel{ .name = "baseline_rv32", .llvm_name = null, .features = featureSet(&[_]Feature{ .a, .c, .d, .f, .m, }), }; pub const baseline_rv64 = CpuModel{ .name = "baseline_rv64", .llvm_name = null, .features = featureSet(&[_]Feature{ .@"64bit", .a, .c, .d, .f, .m, }), }; pub const generic_rv32 = CpuModel{ .name = "generic_rv32", .llvm_name = null, .features = featureSet(&[_]Feature{ .rvc_hints, }), }; pub const generic_rv64 = CpuModel{ .name = "generic_rv64", .llvm_name = null, .features = featureSet(&[_]Feature{ .@"64bit", .rvc_hints, }), }; };
lib/std/target/riscv.zig
const assert = @import("std").debug.assert; pub const rune_error: i32 = 0xfffd; pub const max_rune: i32 = 0x10ffff; pub const rune_self: i32 = 0x80; pub const utf_max: usize = 4; const surrogate_min: i32 = 0xD800; const surrogate_max: i32 = 0xDFFF; const t1: i32 = 0x00; // 0000 0000 const tx: i32 = 0x80; // 1000 0000 const t2: i32 = 0xC0; // 1100 0000 const t3: i32 = 0xE0; // 1110 0000 const t4: i32 = 0xF0; // 1111 0000 const t5: i32 = 0xF8; // 1111 1000 const maskx: i32 = 0x3F; // 0011 1111 const mask2: i32 = 0x1F; // 0001 1111 const mask3: i32 = 0x0F; // 0000 1111 const mask4: i32 = 0x07; // 0000 0111 const rune1Max = (1 << 7) - 1; const rune2Max = (1 << 11) - 1; const rune3Max = (1 << 16) - 1; // The default lowest and highest continuation byte. const locb: u8 = 0x80; // 1000 0000 const hicb: u8 = 0xBF; // 1011 1111 // These names of these constants are chosen to give nice alignment in the // table below. The first nibble is an index into acceptRanges or F for // special one-byte cases. The second nibble is the Rune length or the // Status for the special one-byte case. const xx: u8 = 0xF1; // invalid: size 1 const as: u8 = 0xF0; // ASCII: size 1 const s1: u8 = 0x02; // accept 0, size 2 const s2: u8 = 0x13; // accept 1, size 3 const s3: u8 = 0x03; // accept 0, size 3 const s4: u8 = 0x23; // accept 2, size 3 const s5: u8 = 0x34; // accept 3, size 4 const s6: u8 = 0x04; // accept 0, size 4 const s7: u8 = 0x44; // accept 4, size 4 // first is information about the first byte in a UTF-8 sequence. const first = [_]u8{ // 1 2 3 4 5 6 7 8 9 A B C D E F as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, // 0x00-0x0F as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, // 0x10-0x1F as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, // 0x20-0x2F as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, // 0x30-0x3F as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, // 0x40-0x4F as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, // 0x50-0x5F as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, // 0x60-0x6F as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, // 0x70-0x7F // 1 2 3 4 5 6 7 8 9 A B C D E F xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, // 0x80-0x8F xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, // 0x90-0x9F xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, // 0xA0-0xAF xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, // 0xB0-0xBF xx, xx, s1, s1, s1, s1, s1, s1, s1, s1, s1, s1, s1, s1, s1, s1, // 0xC0-0xCF s1, s1, s1, s1, s1, s1, s1, s1, s1, s1, s1, s1, s1, s1, s1, s1, // 0xD0-0xDF s2, s3, s3, s3, s3, s3, s3, s3, s3, s3, s3, s3, s3, s4, s3, s3, // 0xE0-0xEF s5, s6, s6, s6, s7, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, // 0xF0-0xFF }; const acceptRange = struct { lo: u8, hi: u8, fn init(lo: u8, hi: u8) acceptRange { return acceptRange{ .lo = lo, .hi = hi }; } }; const accept_ranges = [_]acceptRange{ acceptRange.init(locb, hicb), acceptRange.init(0xA0, hicb), acceptRange.init(locb, 0x9F), acceptRange.init(0x90, hicb), acceptRange.init(locb, 0x8F), }; pub fn fullRune(p: []const u8) bool { const n = p.len; if (n == 0) { return false; } const x = first[p[0]]; if (n >= @intCast(usize, x & 7)) { return true; // ASCII, invalid or valid. } // Must be short or invalid const accept = accept_ranges[@intCast(usize, x >> 4)]; if (n > 1 and (p[1] < accept.lo or accept.hi < p[1])) { return true; } else if (n > 2 and (p[0] < locb or hicb < p[2])) { return true; } return false; } pub const Rune = struct { value: i32, size: usize, }; /// decodeRune unpacks the first UTF-8 encoding in p and returns the rune and /// its width in bytes. If p is empty it returns RuneError. Otherwise, if /// the encoding is invalid, it returns RuneError. Both are impossible /// results for correct, non-empty UTF-8. /// /// An encoding is invalid if it is incorrect UTF-8, encodes a rune that is /// out of range, or is not the shortest possible UTF-8 encoding for the /// value. No other validation is performed. pub fn decodeRune(p: []const u8) !Rune { const n = p.len; if (n < 1) { return error.RuneError; } const p0 = p[0]; const x = first[p[0]]; if (x >= as) { // The following code simulates an additional check for x == xx and // handling the ASCII and invalid cases accordingly. This mask-and-or // approach prevents an additional branch. const mask = @intCast(i32, x) << 31 >> 31; return Rune{ .value = (@intCast(i32, p[0]) & ~mask) | (rune_error & mask), .size = 1, }; } const sz = x & 7; const accept = accept_ranges[@intCast(usize, x >> 4)]; if (n < @intCast(usize, sz)) { return error.RuneError; } const b1 = p[1]; if (b1 < accept.lo or accept.hi < b1) { return error.RuneError; } if (sz == 2) { return Rune{ .value = @intCast(i32, p0 & @intCast(u8, mask2)) << 6 | @intCast(i32, b1 & @intCast(u8, maskx)), .size = 2, }; } const b2 = p[2]; if (b2 < locb or hicb < b2) { return error.RuneError; } if (sz == 3) { return Rune{ .value = @intCast(i32, p0 & @intCast(u8, mask3)) << 12 | @intCast(i32, b1 & @intCast(u8, maskx)) << 6 | @intCast(i32, b2 & @intCast(u8, maskx)), .size = 3, }; } const b3 = p[3]; if (b3 < locb or hicb < b3) { return error.RuneError; } return Rune{ .value = @intCast(i32, p0 & @intCast(u8, mask4)) << 18 | @intCast(i32, b1 & @intCast(u8, maskx)) << 12 | @intCast(i32, b2 & @intCast(u8, maskx)) << 6 | @intCast(i32, b3 & @intCast(u8, maskx)), .size = 4, }; } pub fn runeLen(r: i32) !usize { if (r <= rune1Max) { return 1; } else if (r <= rune2Max) { return 2; } else if (surrogate_min <= r and r <= surrogate_min) { return error.RuneError; } else if (r <= rune3Max) { return 3; } else if (r <= max_rune) { return 4; } return error.RuneError; } /// runeStart reports whether the byte could be the first byte of an encoded, /// possibly invalid rune. Second and subsequent bytes always have the top two /// bits set to 10. pub fn runeStart(b: u8) bool { return b & 0xC0 != 0x80; } // decodeLastRune unpacks the last UTF-8 encoding in p and returns the rune and // its width in bytes. If p is empty it returns RuneError. Otherwise, if // the encoding is invalid, it returns RuneError Both are impossible // results for correct, non-empty UTF-8. // // An encoding is invalid if it is incorrect UTF-8, encodes a rune that is // out of range, or is not the shortest possible UTF-8 encoding for the // value. No other validation is performed. pub fn decodeLastRune(p: []const u8) !Rune { const end = p.len; if (end < 1) { return error.RuneError; } var start = end - 1; const r = @intCast(i32, p[start]); if (r < rune_self) { return Rune{ .value = r, .size = 1, }; } // guard against O(n^2) behavior when traversing // backwards through strings with long sequences of // invalid UTF-8. var lim = end - utf_max; if (lim < 0) { lim = 0; } while (start >= lim) { if (runeStart(p[start])) { break; } start -= 1; } if (start < 0) { start = 0; } var rune = try decodeRune(p[start..end]); if (start + rune.size != end) { return error.RuneError; } return rune; } pub fn encodeRune(p: []u8, r: i32) !usize { const i = r; if (i <= rune1Max) { p[0] = @intCast(u8, r); return 1; } else if (i <= rune2Max) { _ = p[1]; p[0] = @intCast(u8, t2 | (r >> 6)); p[1] = @intCast(u8, tx | (r & maskx)); return 2; } else if (i > max_rune or surrogate_min <= i and i <= surrogate_min) { return error.RuneError; } else if (i <= rune3Max) { _ = p[2]; p[0] = @intCast(u8, t3 | (r >> 12)); p[1] = @intCast(u8, tx | ((r >> 6) & maskx)); p[2] = @intCast(u8, tx | (r & maskx)); return 3; } else { _ = p[3]; p[0] = @intCast(u8, t4 | (r >> 18)); p[1] = @intCast(u8, tx | ((r >> 12) & maskx)); p[2] = @intCast(u8, tx | ((r >> 6) & maskx)); p[3] = @intCast(u8, tx | (r & maskx)); return 4; } return error.RuneError; } pub const Iterator = struct { src: []const u8, pos: usize, pub fn init(src: []const u8) Iterator { return Iterator{ .src = src, .pos = 0, }; } // resets the cursor position to index pub fn reset(self: *Iterator, index: usize) void { assert(index < self.src.len); self.pos = index; } pub fn next(self: *Iterator) !?Rune { if (self.pos >= self.src.len) { return null; } const rune = try decodeRune(self.src[self.pos..]); self.pos += rune.size; return rune; } // this is an alias for peek_nth(1) pub fn peek(self: *Iterator) !?Rune { return self.peek_nth(1); } // peek_nth reads nth rune without advancing the cursor. pub fn peek_nth(self: *Iterator, n: usize) !?Rune { var pos = self.pos; var i: usize = 0; var last_read: ?Rune = undefined; while (i < n) : (i += 1) { if (pos >= self.src.len) { return null; } const rune = try decodeRune(self.src[pos..]); pos += rune.size; last_read = rune; } return last_read; } }; // runeCount returns the number of runes in p. Erroneous and short // encodings are treated as single runes of width 1 byte. pub fn runeCount(p: []const u8) usize { const np = p.len; var n: usize = 0; var i: usize = 0; while (i < np) { n += 1; const c = p[i]; if (@intCast(u32, c) < rune_self) { i += 1; continue; } const x = first[c]; if (c == xx) { i += 1; continue; } var size = @intCast(usize, x & 7); if (i + size > np) { i += 1; // Short or invalid. continue; } const accept = accept_ranges[x >> 4]; if (p[i + 1] < accept.lo or accept.hi < p[i + 1]) { size = 1; } else if (size == 2) {} else if (p[i + 2] < locb or hicb < p[i + 2]) { size = 1; } else if (size == 3) {} else if (p[i + 3] < locb or hicb < p[i + 3]) { size = 1; } i += size; } return n; } pub fn valid(p: []const u8) bool { const n = p.len; var i: usize = 0; while (i < n) { const pi = p[i]; if (@intCast(u32, pi) < rune_self) { i += 1; continue; } const x = first[pi]; if (x == xx) { return false; // Illegal starter byte. } const size = @intCast(usize, x & 7); if (i + size > n) { return false; // Short or invalid. } const accept = accept_ranges[x >> 4]; if (p[i + 1] < accept.lo or accept.hi < p[i + 1]) { return false; } else if (size == 2) {} else if (p[i + 2] < locb or hicb < p[i + 2]) { return false; } else if (size == 3) {} else if (p[i + 3] < locb or hicb < p[i + 3]) { return false; } i += size; } return true; } // ValidRune reports whether r can be legally encoded as UTF-8. // Code points that are out of range or a surrogate half are illegal. pub fn validRune(r: u32) bool { if (0 <= r and r < surrogate_min) { return true; } else if (surrogate_min < r and r <= max_rune) { return true; } return false; }
src/utf8.zig
const std = @import("std"); const Tag = std.zig.Token.Tag; var renames: std.StringHashMap([]const u8) = undefined; const max_source_size = 1024 * 1024; // 1MB ought to be enough for anyone pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = &arena.allocator; // Populate renames with primitive types to prevent remapping // Note that arbitrary length integers will be handled by the rename function renames = @TypeOf(renames).init(allocator); inline for (primitive_types) |t| { try renames.put(t[0], t[1]); } // Don't rename the discard identifier try renames.put("_", "_"); // or the main function try renames.put("main", "main"); // Read the source in var source_buffer = std.ArrayListAligned(u8,null).init(allocator); defer source_buffer.deinit(); try std.io.getStdIn().reader().readAllArrayList(&source_buffer, max_source_size); // Make source null-terminated for the Tokenizer const source = try source_buffer.toOwnedSliceSentinel(0); defer allocator.free(source); var tokens = std.zig.Tokenizer.init(source); var output = std.io.getStdOut().writer(); // We'll iterate tokens and either write them out as-is, // renamed, or omitted entirely var tok = tokens.next(); var prev_tag: Tag = .invalid; while (tok.tag != Tag.eof) : (tok = tokens.next()) { // If the source doesn't lex, return an error if (tok.tag == Tag.invalid) return error.invalid_source; // In some circumstances we'll need space between tokens, // e.g. a keyword and an identifier if (needsSpace(prev_tag, tok.tag)) try output.writeByte(' '); const content = source[tok.loc.start..tok.loc.end]; try output.writeAll( switch (tok.tag) { // Replace identifiers with short versions // Avoid renaming an identifier immediately following a // period (e.g. std.mem) // ^ .identifier => if (prev_tag == Tag.period) content else try rename(content), // We filter comments out entirely .doc_comment, .container_doc_comment => "", // Character literal to decimal .char_literal => try charEncode(allocator, content), // Everything is output as-is else => content } ); prev_tag = tok.tag; } } // Renames variables and functions to short versions fn rename(name: []const u8) ![]const u8 { // Have we encountered this name before? if (renames.get(name)) |new_name| return new_name; // If an arbitrary length integer type, pass through if ((name[0] == 'i' or name[0] == 'u') and isDigits(name[1..])) return name; // If we're run out of short names, just pass it through as-is if (short_name_i >= short_names.len) { return name; } // Take the next available short name const new_name = short_names[short_name_i]; short_name_i += 1; try renames.put(name, new_name); return new_name; } // True if all characters in `str` are digits fn isDigits(str: []const u8) bool { for (str) |char| { if (!std.ascii.isDigit(char)) return false; } return true; } // Current short name index var short_name_i: usize = 0; // List of short names const short_names = [_][]const u8{ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", }; // Where possible use the decimal representation instead of the character literal // e.g. `'a'` => `97` saves one byte fn charEncode(allocator: *std.mem.Allocator, char: []const u8) ![]const u8 { if (std.mem.eql(u8, char, "'\n'")) return "10"; if (char.len == 3) { const actual_char = char[1]; return try std.fmt.allocPrint(allocator, "{}", .{actual_char}); } return char; } // True if `a` and `b` will need a space between them fn needsSpace(a: Tag, b: Tag) bool { // identifier@Builtin is OK if (b == Tag.builtin) return false; // `.* *` must have a space between if (a == Tag.period_asterisk and (b == Tag.asterisk or b == Tag.asterisk_asterisk or b == Tag.asterisk_equal or b == Tag.asterisk_percent or b == Tag.asterisk_percent_equal)) return true; return mightNeedSpace(a) and mightNeedSpace(b); } fn mightNeedSpace(t: Tag) bool { return switch (t) { .identifier, .builtin, .integer_literal, .float_literal, //.keyword_addrspace, .keyword_align, .keyword_allowzero, .keyword_and, .keyword_anyframe, .keyword_anytype, .keyword_asm, .keyword_async, .keyword_await, .keyword_break, .keyword_callconv, .keyword_catch, .keyword_comptime, .keyword_const, .keyword_continue, .keyword_defer, .keyword_else, .keyword_enum, .keyword_errdefer, .keyword_error, .keyword_export, .keyword_extern, .keyword_fn, .keyword_for, .keyword_if, .keyword_inline, .keyword_noalias, .keyword_noinline, .keyword_nosuspend, .keyword_opaque, .keyword_or, .keyword_orelse, .keyword_packed, .keyword_pub, .keyword_resume, .keyword_return, .keyword_linksection, .keyword_struct, .keyword_suspend, .keyword_switch, .keyword_test, .keyword_threadlocal, .keyword_try, .keyword_union, .keyword_unreachable, .keyword_usingnamespace, .keyword_var, .keyword_volatile, .keyword_while => true, else => false }; } const primitive_types = .{ // On code.golf the arch is 64bit so these two renames are good .{"isize","i64"}, .{"usize","u64"}, .{"f16","f16"}, .{"f32","f32"}, .{"f64","f64"}, .{"f128","f128"}, .{"bool","bool"}, .{"void","void"}, .{"noreturn","noreturn"}, .{"type","type"}, .{"anyerror","anyerror"}, .{"comptime_int","comptime_int"}, .{"comptime_float","comptime_float"}, };
src/minifier.zig
pub const spdx = &[_][]const u8{ "0BSD", "AAL", "ADSL", "AFL-1.1", "AFL-1.2", "AFL-2.0", "AFL-2.1", "AFL-3.0", "AGPL-1.0", "AGPL-1.0-only", "AGPL-1.0-or-later", "AGPL-3.0", "AGPL-3.0-only", "AGPL-3.0-or-later", "AMDPLPA", "AML", "AMPAS", "ANTLR-PD", "ANTLR-PD-fallback", "APAFML", "APL-1.0", "APSL-1.0", "APSL-1.1", "APSL-1.2", "APSL-2.0", "Abstyles", "Adobe-2006", "Adobe-Glyph", "Afmparse", "Aladdin", "Apache-1.0", "Apache-1.1", "Apache-2.0", "Artistic-1.0", "Artistic-1.0-Perl", "Artistic-1.0-cl8", "Artistic-2.0", "BSD-1-Clause", "BSD-2-Clause", "BSD-2-Clause-FreeBSD", "BSD-2-Clause-NetBSD", "BSD-2-Clause-Patent", "BSD-2-Clause-Views", "BSD-3-Clause", "BSD-3-Clause-Attribution", "BSD-3-Clause-Clear", "BSD-3-Clause-LBNL", "BSD-3-Clause-Modification", "BSD-3-Clause-No-Military-License", "BSD-3-Clause-No-Nuclear-License", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause-No-Nuclear-Warranty", "BSD-3-Clause-Open-MPI", "BSD-4-Clause", "BSD-4-Clause-Shortened", "BSD-4-Clause-UC", "BSD-Protection", "BSD-Source-Code", "BSL-1.0", "BUSL-1.1", "Bahyph", "Barr", "Beerware", "BitTorrent-1.0", "BitTorrent-1.1", "BlueOak-1.0.0", "Borceux", "C-UDA-1.0", "CAL-1.0", "CAL-1.0-Combined-Work-Exception", "CATOSL-1.1", "CC-BY-1.0", "CC-BY-2.0", "CC-BY-2.5", "CC-BY-2.5-AU", "CC-BY-3.0", "CC-BY-3.0-AT", "CC-BY-3.0-US", "CC-BY-4.0", "CC-BY-NC-1.0", "CC-BY-NC-2.0", "CC-BY-NC-2.5", "CC-BY-NC-3.0", "CC-BY-NC-4.0", "CC-BY-NC-ND-1.0", "CC-BY-NC-ND-2.0", "CC-BY-NC-ND-2.5", "CC-BY-NC-ND-3.0", "CC-BY-NC-ND-3.0-IGO", "CC-BY-NC-ND-4.0", "CC-BY-NC-SA-1.0", "CC-BY-NC-SA-2.0", "CC-BY-NC-SA-2.5", "CC-BY-NC-SA-3.0", "CC-BY-NC-SA-4.0", "CC-BY-ND-1.0", "CC-BY-ND-2.0", "CC-BY-ND-2.5", "CC-BY-ND-3.0", "CC-BY-ND-4.0", "CC-BY-SA-1.0", "CC-BY-SA-2.0", "CC-BY-SA-2.0-UK", "CC-BY-SA-2.1-JP", "CC-BY-SA-2.5", "CC-BY-SA-3.0", "CC-BY-SA-3.0-AT", "CC-BY-SA-4.0", "CC-PDDC", "CC0-1.0", "CDDL-1.0", "CDDL-1.1", "CDL-1.0", "CDLA-Permissive-1.0", "CDLA-Sharing-1.0", "CECILL-1.0", "CECILL-1.1", "CECILL-2.0", "CECILL-2.1", "CECILL-B", "CECILL-C", "CERN-OHL-1.1", "CERN-OHL-1.2", "CERN-OHL-P-2.0", "CERN-OHL-S-2.0", "CERN-OHL-W-2.0", "CNRI-Jython", "CNRI-Python", "CNRI-Python-GPL-Compatible", "CPAL-1.0", "CPL-1.0", "CPOL-1.02", "CUA-OPL-1.0", "Caldera", "ClArtistic", "Condor-1.1", "Crossword", "CrystalStacker", "Cube", "D-FSL-1.0", "DOC", "DRL-1.0", "DSDP", "Dotseqn", "ECL-1.0", "ECL-2.0", "EFL-1.0", "EFL-2.0", "EPICS", "EPL-1.0", "EPL-2.0", "EUDatagrid", "EUPL-1.0", "EUPL-1.1", "EUPL-1.2", "Entessa", "ErlPL-1.1", "Eurosym", "FSFAP", "FSFUL", "FSFULLR", "FTL", "Fair", "Frameworx-1.0", "FreeBSD-DOC", "FreeImage", "GD", "GFDL-1.1", "GFDL-1.1-invariants-only", "GFDL-1.1-invariants-or-later", "GFDL-1.1-no-invariants-only", "GFDL-1.1-no-invariants-or-later", "GFDL-1.1-only", "GFDL-1.1-or-later", "GFDL-1.2", "GFDL-1.2-invariants-only", "GFDL-1.2-invariants-or-later", "GFDL-1.2-no-invariants-only", "GFDL-1.2-no-invariants-or-later", "GFDL-1.2-only", "GFDL-1.2-or-later", "GFDL-1.3", "GFDL-1.3-invariants-only", "GFDL-1.3-invariants-or-later", "GFDL-1.3-no-invariants-only", "GFDL-1.3-no-invariants-or-later", "GFDL-1.3-only", "GFDL-1.3-or-later", "GL2PS", "GLWTPL", "GPL-1.0", "GPL-1.0+", "GPL-1.0-only", "GPL-1.0-or-later", "GPL-2.0", "GPL-2.0+", "GPL-2.0-only", "GPL-2.0-or-later", "GPL-2.0-with-GCC-exception", "GPL-2.0-with-autoconf-exception", "GPL-2.0-with-bison-exception", "GPL-2.0-with-classpath-exception", "GPL-2.0-with-font-exception", "GPL-3.0", "GPL-3.0+", "GPL-3.0-only", "GPL-3.0-or-later", "GPL-3.0-with-GCC-exception", "GPL-3.0-with-autoconf-exception", "Giftware", "Glide", "Glulxe", "HPND", "HPND-sell-variant", "HTMLTIDY", "HaskellReport", "Hippocratic-2.1", "IBM-pibs", "ICU", "IJG", "IPA", "IPL-1.0", "ISC", "ImageMagick", "Imlib2", "Info-ZIP", "Intel", "Intel-ACPI", "Interbase-1.0", "JPNIC", "JSON", "JasPer-2.0", "LAL-1.2", "LAL-1.3", "LGPL-2.0", "LGPL-2.0+", "LGPL-2.0-only", "LGPL-2.0-or-later", "LGPL-2.1", "LGPL-2.1+", "LGPL-2.1-only", "LGPL-2.1-or-later", "LGPL-3.0", "LGPL-3.0+", "LGPL-3.0-only", "LGPL-3.0-or-later", "LGPLLR", "LPL-1.0", "LPL-1.02", "LPPL-1.0", "LPPL-1.1", "LPPL-1.2", "LPPL-1.3a", "LPPL-1.3c", "Latex2e", "Leptonica", "LiLiQ-P-1.1", "LiLiQ-R-1.1", "LiLiQ-Rplus-1.1", "Libpng", "Linux-OpenIB", "MIT", "MIT-0", "MIT-CMU", "MIT-Modern-Variant", "MIT-advertising", "MIT-enna", "MIT-feh", "MIT-open-group", "MITNFA", "MPL-1.0", "MPL-1.1", "MPL-2.0", "MPL-2.0-no-copyleft-exception", "MS-PL", "MS-RL", "MTLL", "MakeIndex", "MirOS", "Motosoto", "MulanPSL-1.0", "MulanPSL-2.0", "Multics", "Mup", "NAIST-2003", "NASA-1.3", "NBPL-1.0", "NCGL-UK-2.0", "NCSA", "NGPL", "NIST-PD", "NIST-PD-fallback", "NLOD-1.0", "NLPL", "NOSL", "NPL-1.0", "NPL-1.1", "NPOSL-3.0", "NRL", "NTP", "NTP-0", "Naumen", "Net-SNMP", "NetCDF", "Newsletr", "Nokia", "Noweb", "Nunit", "O-UDA-1.0", "OCCT-PL", "OCLC-2.0", "ODC-By-1.0", "ODbL-1.0", "OFL-1.0", "OFL-1.0-RFN", "OFL-1.0-no-RFN", "OFL-1.1", "OFL-1.1-RFN", "OFL-1.1-no-RFN", "OGC-1.0", "OGDL-Taiwan-1.0", "OGL-Canada-2.0", "OGL-UK-1.0", "OGL-UK-2.0", "OGL-UK-3.0", "OGTSL", "OLDAP-1.1", "OLDAP-1.2", "OLDAP-1.3", "OLDAP-1.4", "OLDAP-2.0", "OLDAP-2.0.1", "OLDAP-2.1", "OLDAP-2.2", "OLDAP-2.2.1", "OLDAP-2.2.2", "OLDAP-2.3", "OLDAP-2.4", "OLDAP-2.5", "OLDAP-2.6", "OLDAP-2.7", "OLDAP-2.8", "OML", "OPL-1.0", "OPUBL-1.0", "OSET-PL-2.1", "OSL-1.0", "OSL-1.1", "OSL-2.0", "OSL-2.1", "OSL-3.0", "OpenSSL", "PDDL-1.0", "PHP-3.0", "PHP-3.01", "PSF-2.0", "Parity-6.0.0", "Parity-7.0.0", "Plexus", "PolyForm-Noncommercial-1.0.0", "PolyForm-Small-Business-1.0.0", "PostgreSQL", "Python-2.0", "QPL-1.0", "Qhull", "RHeCos-1.1", "RPL-1.1", "RPL-1.5", "RPSL-1.0", "RSA-MD", "RSCPL", "Rdisc", "Ruby", "SAX-PD", "SCEA", "SGI-B-1.0", "SGI-B-1.1", "SGI-B-2.0", "SHL-0.5", "SHL-0.51", "SISSL", "SISSL-1.2", "SMLNJ", "SMPPL", "SNIA", "SPL-1.0", "SSH-OpenSSH", "SSH-short", "SSPL-1.0", "SWL", "Saxpath", "Sendmail", "Sendmail-8.23", "SimPL-2.0", "Sleepycat", "Spencer-86", "Spencer-94", "Spencer-99", "StandardML-NJ", "SugarCRM-1.1.3", "TAPR-OHL-1.0", "TCL", "TCP-wrappers", "TMate", "TORQUE-1.1", "TOSL", "TU-Berlin-1.0", "TU-Berlin-2.0", "UCL-1.0", "UPL-1.0", "Unicode-DFS-2015", "Unicode-DFS-2016", "Unicode-TOU", "Unlicense", "VOSTROM", "VSL-1.0", "Vim", "W3C", "W3C-19980720", "W3C-20150513", "WTFPL", "Watcom-1.0", "Wsuipa", "X11", "XFree86-1.1", "XSkat", "Xerox", "Xnet", "YPL-1.0", "YPL-1.1", "ZPL-1.1", "ZPL-2.0", "ZPL-2.1", "Zed", "Zend-2.0", "Zimbra-1.3", "Zimbra-1.4", "Zlib", "blessing", "bzip2-1.0.5", "bzip2-1.0.6", "copyleft-next-0.3.0", "copyleft-next-0.3.1", "curl", "diffmark", "dvipdfm", "eCos-2.0", "eGenix", "etalab-2.0", "gSOAP-1.3b", "gnuplot", "iMatix", "libpng-2.0", "libselinux-1.0", "libtiff", "mpich2", "psfrag", "psutils", "wxWindows", "xinetd", "xpp", "zlib-acknowledgement", }; pub const osi = &[_][]const u8{ "0BSD", "AAL", "AFL-1.1", "AFL-1.2", "AFL-2.0", "AFL-2.1", "AFL-3.0", "AGPL-3.0", "AGPL-3.0-only", "AGPL-3.0-or-later", "APL-1.0", "APSL-1.0", "APSL-1.1", "APSL-1.2", "APSL-2.0", "Apache-1.1", "Apache-2.0", "Artistic-1.0", "Artistic-1.0-Perl", "Artistic-1.0-cl8", "Artistic-2.0", "BSD-1-Clause", "BSD-2-Clause", "BSD-2-Clause-Patent", "BSD-3-Clause", "BSD-3-Clause-LBNL", "BSL-1.0", "CAL-1.0", "CAL-1.0-Combined-Work-Exception", "CATOSL-1.1", "CDDL-1.0", "CECILL-2.1", "CERN-OHL-P-2.0", "CERN-OHL-S-2.0", "CERN-OHL-W-2.0", "CNRI-Python", "CPAL-1.0", "CPL-1.0", "CUA-OPL-1.0", "ECL-1.0", "ECL-2.0", "EFL-1.0", "EFL-2.0", "EPL-1.0", "EPL-2.0", "EUDatagrid", "EUPL-1.1", "EUPL-1.2", "Entessa", "Fair", "Frameworx-1.0", "GPL-2.0", "GPL-2.0+", "GPL-2.0-only", "GPL-2.0-or-later", "GPL-3.0", "GPL-3.0+", "GPL-3.0-only", "GPL-3.0-or-later", "GPL-3.0-with-GCC-exception", "HPND", "IPA", "IPL-1.0", "ISC", "Intel", "LGPL-2.0", "LGPL-2.0+", "LGPL-2.0-only", "LGPL-2.0-or-later", "LGPL-2.1", "LGPL-2.1+", "LGPL-2.1-only", "LGPL-2.1-or-later", "LGPL-3.0", "LGPL-3.0+", "LGPL-3.0-only", "LGPL-3.0-or-later", "LPL-1.0", "LPL-1.02", "LPPL-1.3c", "LiLiQ-P-1.1", "LiLiQ-R-1.1", "LiLiQ-Rplus-1.1", "MIT", "MIT-0", "MIT-Modern-Variant", "MPL-1.0", "MPL-1.1", "MPL-2.0", "MPL-2.0-no-copyleft-exception", "MS-PL", "MS-RL", "MirOS", "Motosoto", "MulanPSL-2.0", "Multics", "NASA-1.3", "NCSA", "NGPL", "NPOSL-3.0", "NTP", "Naumen", "Nokia", "OCLC-2.0", "OFL-1.1", "OFL-1.1-RFN", "OFL-1.1-no-RFN", "OGTSL", "OLDAP-2.8", "OSET-PL-2.1", "OSL-1.0", "OSL-2.0", "OSL-2.1", "OSL-3.0", "PHP-3.0", "PHP-3.01", "PostgreSQL", "Python-2.0", "QPL-1.0", "RPL-1.1", "RPL-1.5", "RPSL-1.0", "RSCPL", "SISSL", "SPL-1.0", "SimPL-2.0", "Sleepycat", "UCL-1.0", "UPL-1.0", "Unicode-DFS-2016", "Unlicense", "VSL-1.0", "W3C", "Watcom-1.0", "Xnet", "ZPL-2.0", "ZPL-2.1", "Zlib", }; // Blue Oak Council data generated from https://blueoakcouncil.org/list // // Last generated from version 9 // pub const blueoak = struct { pub const model = &[_][]const u8{ "BlueOak-1.0.0", }; pub const gold = &[_][]const u8{ "BSD-2-Clause-Patent", }; pub const silver = &[_][]const u8{ "ADSL", "Apache-2.0", "APAFML", "BSD-1-Clause", "BSD-2-Clause", "BSD-2-Clause-FreeBSD", "BSD-2-Clause-NetBSD", "BSD-2-Clause-Views", "BSL-1.0", "DSDP", "ECL-1.0", "ECL-2.0", "ImageMagick", "ISC", "Linux-OpenIB", "MIT", "MIT-Modern-Variant", "MS-PL", "MulanPSL-1.0", "Mup", "PostgreSQL", "Spencer-99", "UPL-1.0", "Xerox", }; pub const bronze = &[_][]const u8{ "0BSD", "AFL-1.1", "AFL-1.2", "AFL-2.0", "AFL-2.1", "AFL-3.0", "AMDPLPA", "AML", "AMPAS", "ANTLR-PD", "ANTLR-PD-fallback", "Apache-1.0", "Apache-1.1", "Artistic-2.0", "Bahyph", "Barr", "BSD-3-Clause", "BSD-3-Clause-Attribution", "BSD-3-Clause-Clear", "BSD-3-Clause-LBNL", "BSD-3-Clause-Modification", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause-No-Nuclear-Warranty", "BSD-3-Clause-Open-MPI", "BSD-4-Clause", "BSD-4-Clause-Shortened", "BSD-4-Clause-UC", "BSD-Source-Code", "bzip2-1.0.5", "bzip2-1.0.6", "CC0-1.0", "CNRI-Jython", "CNRI-Python", "CNRI-Python-GPL-Compatible", "Cube", "curl", "eGenix", "Entessa", "FTL", "HTMLTIDY", "IBM-pibs", "ICU", "Info-ZIP", "Intel", "JasPer-2.0", "Libpng", "libpng-2.0", "libtiff", "LPPL-1.3c", "MIT-0", "MIT-advertising", "MIT-open-group", "MIT-CMU", "MIT-enna", "MIT-feh", "MITNFA", "MTLL", "MulanPSL-2.0", "Multics", "Naumen", "NCSA", "Net-SNMP", "NetCDF", "NTP", "OLDAP-2.0", "OLDAP-2.0.1", "OLDAP-2.1", "OLDAP-2.2", "OLDAP-2.2.1", "OLDAP-2.2.2", "OLDAP-2.3", "OLDAP-2.4", "OLDAP-2.5", "OLDAP-2.6", "OLDAP-2.7", "OLDAP-2.8", "OML", "OpenSSL", "PHP-3.0", "PHP-3.01", "Plexus", "PSF-2.0", "Python-2.0", "Ruby", "Saxpath", "SGI-B-2.0", "SMLNJ", "SWL", "TCL", "TCP-wrappers", "Unicode-DFS-2015", "Unicode-DFS-2016", "Unlicense", "VSL-1.0", "W3C", "X11", "XFree86-1.1", "Xnet", "xpp", "Zlib", "zlib-acknowledgement", "ZPL-2.0", "ZPL-2.1", }; pub const lead = &[_][]const u8{ "AAL", "Adobe-2006", "Afmparse", "Artistic-1.0", "Artistic-1.0-cl8", "Artistic-1.0-Perl", "Beerware", "blessing", "Borceux", "CECILL-B", "ClArtistic", "Condor-1.1", "Crossword", "CrystalStacker", "diffmark", "DOC", "EFL-1.0", "EFL-2.0", "Fair", "FSFUL", "FSFULLR", "Giftware", "HPND", "IJG", "Leptonica", "LPL-1.0", "LPL-1.02", "MirOS", "mpich2", "NASA-1.3", "NBPL-1.0", "Newsletr", "NLPL", "NRL", "OGTSL", "OLDAP-1.1", "OLDAP-1.2", "OLDAP-1.3", "OLDAP-1.4", "psutils", "Qhull", "Rdisc", "RSA-MD", "Spencer-86", "Spencer-94", "TU-Berlin-1.0", "TU-Berlin-2.0", "Vim", "W3C-19980720", "W3C-20150513", "Wsuipa", "WTFPL", "xinetd", "Zed", "Zend-2.0", "ZPL-1.1", }; };
src/lib.zig
const std = @import("std"); const gen1 = @import("../../gen1/data.zig"); const assert = std.debug.assert; const Effectiveness = gen1.Effectiveness; const S = Effectiveness.Super; const N = Effectiveness.Neutral; const R = Effectiveness.Resisted; const I = Effectiveness.Immune; pub const Type = enum(u8) { Normal, Fighting, Flying, Poison, Ground, Rock, Bug, Ghost, Steel, @"???", Fire, Water, Grass, Electric, Psychic, Ice, Dragon, Dark, const CHART = [18][18]Effectiveness{ [_]Effectiveness{ N, N, N, N, N, R, N, I, R, N, N, N, N, N, N, N, N, N }, // Normal [_]Effectiveness{ S, N, R, R, N, S, R, I, S, N, N, N, N, N, R, S, N, S }, // Fighting [_]Effectiveness{ N, S, N, N, N, R, S, N, R, N, N, N, S, R, N, N, N, N }, // Flying [_]Effectiveness{ N, N, N, R, R, R, N, R, I, N, N, N, S, N, N, N, N, N }, // Poison [_]Effectiveness{ N, N, I, S, N, S, R, N, S, N, S, N, R, S, N, N, N, N }, // Ground [_]Effectiveness{ N, R, S, N, R, N, S, N, R, N, S, N, N, N, N, S, N, N }, // Rock [_]Effectiveness{ N, R, R, R, N, N, N, R, R, N, R, N, S, N, S, N, N, S }, // Bug [_]Effectiveness{ I, N, N, N, N, N, N, S, R, N, N, N, N, N, S, N, N, R }, // Ghost [_]Effectiveness{ N, N, N, N, N, S, N, N, R, N, R, R, N, R, N, S, N, N }, // Steel [_]Effectiveness{ N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N }, // ??? [_]Effectiveness{ N, N, N, N, N, R, S, N, S, N, R, R, S, N, N, S, R, N }, // Fire [_]Effectiveness{ N, N, N, N, S, S, N, N, N, N, S, R, R, N, N, N, R, N }, // Water [_]Effectiveness{ N, N, R, R, S, S, R, N, R, N, R, S, R, N, N, N, R, N }, // Grass [_]Effectiveness{ N, N, S, N, I, N, N, N, N, N, N, S, R, R, N, N, R, N }, // Electric [_]Effectiveness{ N, S, N, S, N, N, N, N, R, N, N, N, N, N, R, N, N, I }, // Psychic [_]Effectiveness{ N, N, S, N, S, N, N, N, R, N, R, R, S, N, N, R, S, N }, // Ice [_]Effectiveness{ N, N, N, N, N, N, N, N, R, N, N, N, N, N, N, N, S, N }, // Dragon [_]Effectiveness{ N, R, N, N, N, N, N, S, R, N, N, N, N, N, S, N, N, R }, // Dark }; comptime { assert(@bitSizeOf(Type) == 8); assert(@sizeOf(@TypeOf(CHART)) == 324); } pub inline fn special(self: Type) bool { return @enumToInt(self) >= @enumToInt(Type.Fire); } pub inline fn effectiveness(t1: Type, t2: Type) Effectiveness { return CHART[@enumToInt(t1)][@enumToInt(t2)]; } }; pub const Types = extern struct { type1: Type = .Normal, type2: Type = .Normal, comptime { assert(@bitSizeOf(Types) == 16); } pub inline fn immune(self: Types, t: Type) bool { return t.effectiveness(self.type1) == I or t.effectiveness(self.type2) == I; } pub inline fn includes(self: Types, t: Type) bool { return self.type1 == t or self.type2 == t; } };
src/lib/gen2/data/types.zig
const std = @import("std"); const g711 = @import("./g711.zig"); const io = std.io; pub const Header = struct { const Self = @This(); format: u16, num_channels: u16, sample_rate: u32, byte_rate: u32, block_align: u16, bits_per_sample: u16, extension_size: u16, valid_bits_per_sample: u16, channel_mask: u32, sub_format: struct { format: u16, fixed_string: [14]u8 }, pub const Format = enum(u16) { PCM = 1, IEEEFloat = 3, ALaw = 6, ULaw = 7, Extensible = 0xFFFE, }; fn getFormat(self: Self) !Format { const fmt = std.meta.intToEnum(Format, self.format) catch return error.UnsupportedFormat; if (fmt == Format.Extensible) { return std.meta.intToEnum(Format, self.sub_format.format) catch return error.UnsupportedFormat; } return fmt; } }; pub fn WaveReader(comptime ReaderType: type, comptime SampleType: type, comptime sampleBufSize: u32) type { return struct { const Self = @This(); pub const Error = ReaderType.Error || error{ BadHeader, UnexpectedEOF, BadState, UnsupportedFormat, UnsupportedSampleType }; pub const Reader = io.Reader(*Self, Error, readFn); const max_bits_per_sample = 32; const data_buf_size = (max_bits_per_sample / 8) * sampleBufSize; const SampleFifoType = std.fifo.LinearFifo(SampleType, .{ .Static = sampleBufSize }); source: ReaderType, source_unread_data_size: usize = 0, header: ?Header = null, source_buf: [data_buf_size]u8 = undefined, sample_fifo: SampleFifoType = SampleFifoType.init(), sample_i32_buf: [sampleBufSize]i32 = undefined, has_error: bool = false, pub fn readSamples(self: *Self, dst: []SampleType) Error!usize { if (self.has_error) return Error.BadState; errdefer self.has_error = true; if (self.header == null) { const hdr = try self.getHeader(); } if (self.sample_fifo.count > 0) { return self.sample_fifo.read(dst); } // sample fifo is empty; fill it up. if (self.source_unread_data_size == 0) { return 0; // valid eof } // depending on bits_per_sample, we may not be able to read into source_buf fully. const bytes_per_sample = self.header.?.bits_per_sample / 8; const max_samples_in_buf = (self.sample_i32_buf.len / bytes_per_sample); var buf_len = std.math.min(self.source_unread_data_size, max_samples_in_buf * bytes_per_sample); const n = try self.source.readAll(self.source_buf[0..buf_len]); if (n == 0) return Error.UnexpectedEOF; self.source_unread_data_size -= n; if ((n % bytes_per_sample) != 0) { return Error.UnexpectedEOF; } try self.decodeSamples(self.source_buf[0..n], self.sample_i32_buf[0..]); const num_samples = (n / bytes_per_sample); for (self.sample_i32_buf[0..num_samples]) |v| { switch (SampleType) { i16 => { var out = if (std.math.cast(i16, v >> 16)) |value| value else |err| std.math.maxInt(i16); self.sample_fifo.writeItemAssumeCapacity(out); }, f32 => { var out = @intToFloat(f32, v); out /= (1 + @intToFloat(f32, std.math.maxInt(@TypeOf(v)))); self.sample_fifo.writeItemAssumeCapacity(out); }, else => { return Error.UnsupportedSampleType; }, } } return self.sample_fifo.read(dst); } fn decodeSamples(self: *Self, src: []u8, dst: []i32) !void { switch (try self.header.?.getFormat()) { Header.Format.PCM => { switch (self.header.?.bits_per_sample) { 8 => { const samples = std.mem.bytesAsSlice(u8, src); for (samples) |s, idx| { dst[idx] = (@as(i32, s) << 24) ^ std.math.minInt(i32); } }, 16 => { const samples = std.mem.bytesAsSlice(i16, src); for (samples) |s, idx| { dst[idx] = @as(i32, s) << 16; } }, 24 => { // sizeof(i24)= 4 therefore mem.bytesAsSlice does not do what we want. var i: usize = 0; while (i < src.len) : (i += 3) { const sample = std.mem.readIntLittle(i24, src[i..][0..3]); dst[i / 3] = @as(i32, sample) << 8; } }, 32 => { const samples = std.mem.bytesAsSlice(i32, src); for (samples) |s, idx| { dst[idx] = s; } }, else => { return Error.UnsupportedFormat; }, } }, Header.Format.IEEEFloat => { switch (self.header.?.bits_per_sample) { 32 => { const samples = std.mem.bytesAsSlice(f32, src); for (samples) |s, idx| { var out: i32 = undefined; var tmp: f64 = s; const max_sample_f32 = @intToFloat(f32, std.math.maxInt(i32)); const min_sample_f32 = @intToFloat(f32, std.math.minInt(i32)); tmp *= (1.0 + max_sample_f32); if (tmp < 0) { if (tmp <= min_sample_f32 - 0.5) { out = std.math.minInt(i32); } else { out = @floatToInt(i32, tmp - 0.5); } } else { if (tmp >= max_sample_f32 + 0.5) { out = std.math.maxInt(i32); } else { out = @floatToInt(i32, tmp + 0.5); } } dst[idx] = out; } }, else => { return Error.UnsupportedFormat; }, } }, Header.Format.ULaw => { switch (self.header.?.bits_per_sample) { 8 => { const samples = std.mem.bytesAsSlice(u8, src); for (samples) |s, idx| { dst[idx] = @as(i32, g711.ulaw_to_i16[s]) << 16; } }, else => { return Error.UnsupportedFormat; }, } }, Header.Format.ALaw => { switch (self.header.?.bits_per_sample) { 8 => { const samples = std.mem.bytesAsSlice(u8, src); for (samples) |s, idx| { dst[idx] = @as(i32, g711.alaw_to_i16[s]) << 16; } }, else => { return Error.UnsupportedFormat; }, } }, else => { return Error.UnsupportedFormat; }, } } /// read header and seek source reader to the start of wave data. pub fn getHeader(self: *Self) Error!Header { if (self.header != null) return self.header.?; if (self.has_error) return Error.BadState; errdefer self.has_error = true; var buf: [8]u8 = undefined; try self.readFull(&buf); if (!std.mem.eql(u8, buf[0..4], "RIFF")) { return Error.BadHeader; } try self.readFull(buf[0..4]); if (!std.mem.eql(u8, buf[0..4], "WAVE")) { return Error.BadHeader; } while (true) { try self.readFull(&buf); const chunk_type = buf[0..4]; const chunk_size = std.mem.readIntLittle(u32, buf[4..8]); if (std.mem.eql(u8, chunk_type, "data")) { if (self.header == null) { return Error.BadHeader; } self.source_unread_data_size = chunk_size; return self.header.?; } else if (!std.mem.eql(u8, chunk_type, "fmt ")) { // discard all chunks other than data and fmt self.source.skipBytes(chunk_size, .{}) catch |err| { if (err == error.EndOfStream) { return Error.UnexpectedEOF; } else { self.has_error = true; return Error.BadState; } }; continue; } // now reading fmt chunk var fmt_buf_max: [40]u8 = undefined; // fmt chunk max size is 40. var fmt_buf = fmt_buf_max[0..chunk_size]; try self.readFull(fmt_buf); var hdr: Header = undefined; hdr.format = std.mem.readIntLittle(u16, fmt_buf[0..2]); hdr.num_channels = std.mem.readIntLittle(u16, fmt_buf[2..4]); hdr.sample_rate = std.mem.readIntLittle(u32, fmt_buf[4..8]); hdr.byte_rate = std.mem.readIntLittle(u32, fmt_buf[8..12]); hdr.block_align = std.mem.readIntLittle(u16, fmt_buf[12..14]); hdr.bits_per_sample = std.mem.readIntLittle(u16, fmt_buf[14..16]); if (chunk_size > 16) { hdr.extension_size = std.mem.readIntLittle(u16, fmt_buf[16..18]); if (chunk_size > 18) { hdr.valid_bits_per_sample = std.mem.readIntLittle(u16, fmt_buf[18..20]); hdr.channel_mask = std.mem.readIntLittle(u32, fmt_buf[20..24]); hdr.sub_format.format = std.mem.readIntLittle(u16, fmt_buf[24..26]); std.mem.copy(u8, hdr.sub_format.fixed_string[0..], fmt_buf[26..40]); } } // validate the header const fmt = try hdr.getFormat(); switch (hdr.bits_per_sample) { 8, 16, 24, 32 => {}, else => { return Error.UnsupportedFormat; }, } self.header = hdr; continue; } } /// read into the given buffer fully, EOF means input is invalid. fn readFull(self: *Self, buf: []u8) Error!void { const n = try self.source.readAll(buf); if (n < buf.len) { return Error.UnexpectedEOF; } } /// implements the io.Reader interface fn readFn(self: *Self, buf: []u8) Error!usize { // find how many samples can fit in buf. const sample_size = @sizeOf(SampleType); const max_samples = buf.len / sample_size; if (max_samples == 0) return 0; var tmp: [512]SampleType = undefined; const len = if (tmp.len < max_samples) tmp.len else max_samples; const n = try self.readSamples(tmp[0..len]); if (n == 0) return 0; const tmp_u8 = std.mem.sliceAsBytes(tmp[0..n]); std.mem.copy(u8, buf, tmp_u8); return n * sample_size; } pub fn reader(self: *Self) Reader { return .{ .context = self }; } }; } pub fn waveReaderFloat32(reader: anytype) WaveReader(@TypeOf(reader), f32, 1024) { return .{ .source = reader }; } pub fn waveReaderPCM16(reader: anytype) WaveReader(@TypeOf(reader), i16, 1024) { return .{ .source = reader }; } fn testReader(comptime truthType: anytype, comptime wavFile: []const u8, comptime truthFile: []const u8) !void { var r = std.io.fixedBufferStream(@embedFile(wavFile)).reader(); var wavr = WaveReader(@TypeOf(r), truthType, 1024){ .source = r }; var truthReader = std.io.fixedBufferStream(@embedFile(truthFile)).reader(); var got: [512]truthType = undefined; while (true) { const n = try wavr.readSamples(got[0..]); if (n == 0) { try std.testing.expectError(error.EndOfStream, truthReader.readByte()); break; } for (got[0..n]) |g| { switch (truthType) { i16 => { const want = try truthReader.readIntLittle(i16); if (wavr.header.?.bits_per_sample > 16) { // converting from 24/32 bit to 16 bit can lead to rounding differences. try std.testing.expectApproxEqRel(@intToFloat(f32, want), @intToFloat(f32, g), 1.0); } else { try std.testing.expectEqual(want, g); } }, f32 => { const want = @bitCast(f32, try truthReader.readIntLittle(i32)); try std.testing.expectApproxEqRel(want, g, 0.001); }, else => { return error.UnknownType; }, } } } } test "wavereader src=pcm08" { try testReader(i16, "testdata/test_pcm08.wav", "testdata/test_pcm08.i16.raw"); try testReader(f32, "testdata/test_pcm08.wav", "testdata/test_pcm08.f32.raw"); } test "wavereader src=pcm16" { try testReader(i16, "testdata/test_pcm16.wav", "testdata/test_pcm16.i16.raw"); try testReader(f32, "testdata/test_pcm16.wav", "testdata/test_pcm16.f32.raw"); } test "wavereader src=pcm24" { try testReader(i16, "testdata/test_pcm24.wav", "testdata/test_pcm24.i16.raw"); try testReader(f32, "testdata/test_pcm24.wav", "testdata/test_pcm24.f32.raw"); } test "wavereader src=pcm32" { try testReader(i16, "testdata/test_pcm32.wav", "testdata/test_pcm32.i16.raw"); try testReader(f32, "testdata/test_pcm32.wav", "testdata/test_pcm32.f32.raw"); } test "wavereader src=flt32" { try testReader(i16, "testdata/test_flt32.wav", "testdata/test_flt32.i16.raw"); try testReader(f32, "testdata/test_flt32.wav", "testdata/test_flt32.f32.raw"); } test "wavereader src=u-law" { try testReader(i16, "testdata/test_u-law.wav", "testdata/test_u-law.i16.raw"); try testReader(f32, "testdata/test_u-law.wav", "testdata/test_u-law.f32.raw"); } test "wavereader src=a-law" { try testReader(i16, "testdata/test_a-law.wav", "testdata/test_a-law.i16.raw"); try testReader(f32, "testdata/test_a-law.wav", "testdata/test_a-law.f32.raw"); } test "invalid inputs" { try std.testing.expectError(error.UnexpectedEOF, testReader(i16, "testdata/bad_empty.wav", "testdata/test_pcm16.i16.raw")); try std.testing.expectError(error.UnexpectedEOF, testReader(i16, "testdata/bad_data_eof.wav", "testdata/test_pcm16.i16.raw")); try std.testing.expectError(error.BadHeader, testReader(i16, "testdata/bad_no_riff.wav", "testdata/test_pcm16.i16.raw")); try std.testing.expectError(error.BadHeader, testReader(i16, "testdata/bad_no_fmt.wav", "testdata/test_pcm16.i16.raw")); } test "wavereader io.Reader" { var r = std.io.fixedBufferStream(@embedFile("testdata/test_pcm16.wav")).reader(); var wavr = waveReaderPCM16(r).reader(); const got = try wavr.readAllAlloc(std.testing.allocator, std.math.maxInt(usize)); defer std.testing.allocator.free(got); var truth = std.io.fixedBufferStream(@embedFile("testdata/test_pcm16.i16.raw")).reader(); const want = try truth.readAllAlloc(std.testing.allocator, std.math.maxInt(usize)); defer std.testing.allocator.free(want); try std.testing.expectEqualSlices(u8, want, got); }
src/wav/wav.zig
const std = @import("std"); const Context = @import("connection.zig").Context; const Object = @import("connection.zig").Object; // wl_display pub const wl_display_interface = struct { // core global object @"error": ?fn (*Context, Object, Object, u32, []u8) anyerror!void, delete_id: ?fn (*Context, Object, u32) anyerror!void, }; fn wl_display_error_default(context: *Context, object: Object, object_id: Object, code: u32, message: []u8) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_display_delete_id_default(context: *Context, object: Object, id: u32) anyerror!void { return error.DebugFunctionNotImplemented; } pub var WL_DISPLAY = wl_display_interface{ .@"error" = wl_display_error_default, .delete_id = wl_display_delete_id_default, }; pub fn new_wl_display(id: u32, context: *Context, container: usize) Object { return Object{ .id = id, .dispatch = wl_display_dispatch, .context = context, .version = 0, .container = container, }; } fn wl_display_dispatch(object: Object, opcode: u16) anyerror!void { switch (opcode) { // error 0 => { var object_id: Object = object.context.objects.get(try object.context.next_u32()).?; var code: u32 = try object.context.next_u32(); var message: []u8 = try object.context.next_string(); if (WL_DISPLAY.@"error") |@"error"| { try @"error"(object.context, object, object_id, code, message); } }, // delete_id 1 => { var id: u32 = try object.context.next_u32(); if (WL_DISPLAY.delete_id) |delete_id| { try delete_id(object.context, object, id); } }, else => {}, } } pub const wl_display_error = enum(u32) { invalid_object = 0, invalid_method = 1, no_memory = 2, implementation = 3, }; // // The sync request asks the server to emit the 'done' event // on the returned wl_callback object. Since requests are // handled in-order and events are delivered in-order, this can // be used as a barrier to ensure all previous requests and the // resulting events have been handled. // // The object returned by this request will be destroyed by the // compositor after the callback is fired and as such the client must not // attempt to use it after that point. // // The callback_data passed in the callback is the event serial. // pub fn wl_display_send_sync(object: Object, callback: u32) anyerror!void { object.context.startWrite(); object.context.putU32(callback); object.context.finishWrite(object.id, 0); } // // This request creates a registry object that allows the client // to list and bind the global objects available from the // compositor. // // It should be noted that the server side resources consumed in // response to a get_registry request can only be released when the // client disconnects, not when the client side proxy is destroyed. // Therefore, clients should invoke get_registry as infrequently as // possible to avoid wasting memory. // pub fn wl_display_send_get_registry(object: Object, registry: u32) anyerror!void { object.context.startWrite(); object.context.putU32(registry); object.context.finishWrite(object.id, 1); } // wl_registry pub const wl_registry_interface = struct { // global registry object global: ?fn (*Context, Object, u32, []u8, u32) anyerror!void, global_remove: ?fn (*Context, Object, u32) anyerror!void, }; fn wl_registry_global_default(context: *Context, object: Object, name: u32, interface: []u8, version: u32) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_registry_global_remove_default(context: *Context, object: Object, name: u32) anyerror!void { return error.DebugFunctionNotImplemented; } pub var WL_REGISTRY = wl_registry_interface{ .global = wl_registry_global_default, .global_remove = wl_registry_global_remove_default, }; pub fn new_wl_registry(id: u32, context: *Context, container: usize) Object { return Object{ .id = id, .dispatch = wl_registry_dispatch, .context = context, .version = 0, .container = container, }; } fn wl_registry_dispatch(object: Object, opcode: u16) anyerror!void { switch (opcode) { // global 0 => { var name: u32 = try object.context.next_u32(); var interface: []u8 = try object.context.next_string(); var version: u32 = try object.context.next_u32(); if (WL_REGISTRY.global) |global| { try global(object.context, object, name, interface, version); } }, // global_remove 1 => { var name: u32 = try object.context.next_u32(); if (WL_REGISTRY.global_remove) |global_remove| { try global_remove(object.context, object, name); } }, else => {}, } } // // Binds a new, client-created object to the server using the // specified name as the identifier. // pub fn wl_registry_send_bind(object: Object, name: u32, name_string: []const u8, version: u32, id: u32) anyerror!void { object.context.startWrite(); object.context.putU32(name); object.context.putString(name_string); object.context.putU32(version); object.context.putU32(id); object.context.finishWrite(object.id, 0); } // wl_callback pub const wl_callback_interface = struct { // callback object done: ?fn (*Context, Object, u32) anyerror!void, }; fn wl_callback_done_default(context: *Context, object: Object, callback_data: u32) anyerror!void { return error.DebugFunctionNotImplemented; } pub var WL_CALLBACK = wl_callback_interface{ .done = wl_callback_done_default, }; pub fn new_wl_callback(id: u32, context: *Context, container: usize) Object { return Object{ .id = id, .dispatch = wl_callback_dispatch, .context = context, .version = 0, .container = container, }; } fn wl_callback_dispatch(object: Object, opcode: u16) anyerror!void { switch (opcode) { // done 0 => { var callback_data: u32 = try object.context.next_u32(); if (WL_CALLBACK.done) |done| { try done(object.context, object, callback_data); } }, else => {}, } } // wl_compositor pub const wl_compositor_interface = struct { // the compositor singleton }; pub var WL_COMPOSITOR = wl_compositor_interface{}; pub fn new_wl_compositor(id: u32, context: *Context, container: usize) Object { return Object{ .id = id, .dispatch = wl_compositor_dispatch, .context = context, .version = 0, .container = container, }; } fn wl_compositor_dispatch(object: Object, opcode: u16) anyerror!void { switch (opcode) { else => {}, } } // // Ask the compositor to create a new surface. // pub fn wl_compositor_send_create_surface(object: Object, id: u32) anyerror!void { object.context.startWrite(); object.context.putU32(id); object.context.finishWrite(object.id, 0); } // // Ask the compositor to create a new region. // pub fn wl_compositor_send_create_region(object: Object, id: u32) anyerror!void { object.context.startWrite(); object.context.putU32(id); object.context.finishWrite(object.id, 1); } // wl_shm_pool pub const wl_shm_pool_interface = struct { // a shared memory pool }; pub var WL_SHM_POOL = wl_shm_pool_interface{}; pub fn new_wl_shm_pool(id: u32, context: *Context, container: usize) Object { return Object{ .id = id, .dispatch = wl_shm_pool_dispatch, .context = context, .version = 0, .container = container, }; } fn wl_shm_pool_dispatch(object: Object, opcode: u16) anyerror!void { switch (opcode) { else => {}, } } // // Create a wl_buffer object from the pool. // // The buffer is created offset bytes into the pool and has // width and height as specified. The stride argument specifies // the number of bytes from the beginning of one row to the beginning // of the next. The format is the pixel format of the buffer and // must be one of those advertised through the wl_shm.format event. // // A buffer will keep a reference to the pool it was created from // so it is valid to destroy the pool immediately after creating // a buffer from it. // pub fn wl_shm_pool_send_create_buffer(object: Object, id: u32, offset: i32, width: i32, height: i32, stride: i32, format: u32) anyerror!void { object.context.startWrite(); object.context.putU32(id); object.context.putI32(offset); object.context.putI32(width); object.context.putI32(height); object.context.putI32(stride); object.context.putU32(format); object.context.finishWrite(object.id, 0); } // // Destroy the shared memory pool. // // The mmapped memory will be released when all // buffers that have been created from this pool // are gone. // pub fn wl_shm_pool_send_destroy(object: Object) anyerror!void { object.context.startWrite(); object.context.finishWrite(object.id, 1); } // // This request will cause the server to remap the backing memory // for the pool from the file descriptor passed when the pool was // created, but using the new size. This request can only be // used to make the pool bigger. // pub fn wl_shm_pool_send_resize(object: Object, size: i32) anyerror!void { object.context.startWrite(); object.context.putI32(size); object.context.finishWrite(object.id, 2); } // wl_shm pub const wl_shm_interface = struct { // shared memory support format: ?fn (*Context, Object, u32) anyerror!void, }; fn wl_shm_format_default(context: *Context, object: Object, format: u32) anyerror!void { return error.DebugFunctionNotImplemented; } pub var WL_SHM = wl_shm_interface{ .format = wl_shm_format_default, }; pub fn new_wl_shm(id: u32, context: *Context, container: usize) Object { return Object{ .id = id, .dispatch = wl_shm_dispatch, .context = context, .version = 0, .container = container, }; } fn wl_shm_dispatch(object: Object, opcode: u16) anyerror!void { switch (opcode) { // format 0 => { var format: u32 = try object.context.next_u32(); if (WL_SHM.format) |format| { try format(object.context, object, format); } }, else => {}, } } pub const wl_shm_error = enum(u32) { invalid_format = 0, invalid_stride = 1, invalid_fd = 2, }; pub const wl_shm_format = enum(u32) { argb8888 = 0, xrgb8888 = 1, c8 = 0x20203843, rgb332 = 0x38424752, bgr233 = 0x38524742, xrgb4444 = 0x32315258, xbgr4444 = 0x32314258, rgbx4444 = 0x32315852, bgrx4444 = 0x32315842, argb4444 = 0x32315241, abgr4444 = 0x32314241, rgba4444 = 0x32314152, bgra4444 = 0x32314142, xrgb1555 = 0x35315258, xbgr1555 = 0x35314258, rgbx5551 = 0x35315852, bgrx5551 = 0x35315842, argb1555 = 0x35315241, abgr1555 = 0x35314241, rgba5551 = 0x35314152, bgra5551 = 0x35314142, rgb565 = 0x36314752, bgr565 = 0x36314742, rgb888 = 0x34324752, bgr888 = 0x34324742, xbgr8888 = 0x34324258, rgbx8888 = 0x34325852, bgrx8888 = 0x34325842, abgr8888 = 0x34324241, rgba8888 = 0x34324152, bgra8888 = 0x34324142, xrgb2101010 = 0x30335258, xbgr2101010 = 0x30334258, rgbx1010102 = 0x30335852, bgrx1010102 = 0x30335842, argb2101010 = 0x30335241, abgr2101010 = 0x30334241, rgba1010102 = 0x30334152, bgra1010102 = 0x30334142, yuyv = 0x56595559, yvyu = 0x55595659, uyvy = 0x59565955, vyuy = 0x59555956, ayuv = 0x56555941, nv12 = 0x3231564e, nv21 = 0x3132564e, nv16 = 0x3631564e, nv61 = 0x3136564e, yuv410 = 0x39565559, yvu410 = 0x39555659, yuv411 = 0x31315559, yvu411 = 0x31315659, yuv420 = 0x32315559, yvu420 = 0x32315659, yuv422 = 0x36315559, yvu422 = 0x36315659, yuv444 = 0x34325559, yvu444 = 0x34325659, }; // // Create a new wl_shm_pool object. // // The pool can be used to create shared memory based buffer // objects. The server will mmap size bytes of the passed file // descriptor, to use as backing memory for the pool. // pub fn wl_shm_send_create_pool(object: Object, id: u32, fd: i32, size: i32) anyerror!void { object.context.startWrite(); object.context.putU32(id); object.context.putFd(fd); object.context.putI32(size); object.context.finishWrite(object.id, 0); } // wl_buffer pub const wl_buffer_interface = struct { // content for a wl_surface release: ?fn ( *Context, Object, ) anyerror!void, }; fn wl_buffer_release_default(context: *Context, object: Object) anyerror!void { return error.DebugFunctionNotImplemented; } pub var WL_BUFFER = wl_buffer_interface{ .release = wl_buffer_release_default, }; pub fn new_wl_buffer(id: u32, context: *Context, container: usize) Object { return Object{ .id = id, .dispatch = wl_buffer_dispatch, .context = context, .version = 0, .container = container, }; } fn wl_buffer_dispatch(object: Object, opcode: u16) anyerror!void { switch (opcode) { // release 0 => { if (WL_BUFFER.release) |release| { try release( object.context, object, ); } }, else => {}, } } // // Destroy a buffer. If and how you need to release the backing // storage is defined by the buffer factory interface. // // For possible side-effects to a surface, see wl_surface.attach. // pub fn wl_buffer_send_destroy(object: Object) anyerror!void { object.context.startWrite(); object.context.finishWrite(object.id, 0); } // wl_data_offer pub const wl_data_offer_interface = struct { // offer to transfer data offer: ?fn (*Context, Object, []u8) anyerror!void, source_actions: ?fn (*Context, Object, u32) anyerror!void, action: ?fn (*Context, Object, u32) anyerror!void, }; fn wl_data_offer_offer_default(context: *Context, object: Object, mime_type: []u8) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_data_offer_source_actions_default(context: *Context, object: Object, source_actions: u32) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_data_offer_action_default(context: *Context, object: Object, dnd_action: u32) anyerror!void { return error.DebugFunctionNotImplemented; } pub var WL_DATA_OFFER = wl_data_offer_interface{ .offer = wl_data_offer_offer_default, .source_actions = wl_data_offer_source_actions_default, .action = wl_data_offer_action_default, }; pub fn new_wl_data_offer(id: u32, context: *Context, container: usize) Object { return Object{ .id = id, .dispatch = wl_data_offer_dispatch, .context = context, .version = 0, .container = container, }; } fn wl_data_offer_dispatch(object: Object, opcode: u16) anyerror!void { switch (opcode) { // offer 0 => { var mime_type: []u8 = try object.context.next_string(); if (WL_DATA_OFFER.offer) |offer| { try offer(object.context, object, mime_type); } }, // source_actions 1 => { var source_actions: u32 = try object.context.next_u32(); if (WL_DATA_OFFER.source_actions) |source_actions| { try source_actions(object.context, object, source_actions); } }, // action 2 => { var dnd_action: u32 = try object.context.next_u32(); if (WL_DATA_OFFER.action) |action| { try action(object.context, object, dnd_action); } }, else => {}, } } pub const wl_data_offer_error = enum(u32) { invalid_finish = 0, invalid_action_mask = 1, invalid_action = 2, invalid_offer = 3, }; // // Indicate that the client can accept the given mime type, or // NULL for not accepted. // // For objects of version 2 or older, this request is used by the // client to give feedback whether the client can receive the given // mime type, or NULL if none is accepted; the feedback does not // determine whether the drag-and-drop operation succeeds or not. // // For objects of version 3 or newer, this request determines the // final result of the drag-and-drop operation. If the end result // is that no mime types were accepted, the drag-and-drop operation // will be cancelled and the corresponding drag source will receive // wl_data_source.cancelled. Clients may still use this event in // conjunction with wl_data_source.action for feedback. // pub fn wl_data_offer_send_accept(object: Object, serial: u32, mime_type: []const u8) anyerror!void { object.context.startWrite(); object.context.putU32(serial); object.context.putString(mime_type); object.context.finishWrite(object.id, 0); } // // To transfer the offered data, the client issues this request // and indicates the mime type it wants to receive. The transfer // happens through the passed file descriptor (typically created // with the pipe system call). The source client writes the data // in the mime type representation requested and then closes the // file descriptor. // // The receiving client reads from the read end of the pipe until // EOF and then closes its end, at which point the transfer is // complete. // // This request may happen multiple times for different mime types, // both before and after wl_data_device.drop. Drag-and-drop destination // clients may preemptively fetch data or examine it more closely to // determine acceptance. // pub fn wl_data_offer_send_receive(object: Object, mime_type: []const u8, fd: i32) anyerror!void { object.context.startWrite(); object.context.putString(mime_type); object.context.putFd(fd); object.context.finishWrite(object.id, 1); } // // Destroy the data offer. // pub fn wl_data_offer_send_destroy(object: Object) anyerror!void { object.context.startWrite(); object.context.finishWrite(object.id, 2); } // // Notifies the compositor that the drag destination successfully // finished the drag-and-drop operation. // // Upon receiving this request, the compositor will emit // wl_data_source.dnd_finished on the drag source client. // // It is a client error to perform other requests than // wl_data_offer.destroy after this one. It is also an error to perform // this request after a NULL mime type has been set in // wl_data_offer.accept or no action was received through // wl_data_offer.action. // pub fn wl_data_offer_send_finish(object: Object) anyerror!void { object.context.startWrite(); object.context.finishWrite(object.id, 3); } // // Sets the actions that the destination side client supports for // this operation. This request may trigger the emission of // wl_data_source.action and wl_data_offer.action events if the compositor // needs to change the selected action. // // This request can be called multiple times throughout the // drag-and-drop operation, typically in response to wl_data_device.enter // or wl_data_device.motion events. // // This request determines the final result of the drag-and-drop // operation. If the end result is that no action is accepted, // the drag source will receive wl_drag_source.cancelled. // // The dnd_actions argument must contain only values expressed in the // wl_data_device_manager.dnd_actions enum, and the preferred_action // argument must only contain one of those values set, otherwise it // will result in a protocol error. // // While managing an "ask" action, the destination drag-and-drop client // may perform further wl_data_offer.receive requests, and is expected // to perform one last wl_data_offer.set_actions request with a preferred // action other than "ask" (and optionally wl_data_offer.accept) before // requesting wl_data_offer.finish, in order to convey the action selected // by the user. If the preferred action is not in the // wl_data_offer.source_actions mask, an error will be raised. // // If the "ask" action is dismissed (e.g. user cancellation), the client // is expected to perform wl_data_offer.destroy right away. // // This request can only be made on drag-and-drop offers, a protocol error // will be raised otherwise. // pub fn wl_data_offer_send_set_actions(object: Object, dnd_actions: u32, preferred_action: u32) anyerror!void { object.context.startWrite(); object.context.putU32(dnd_actions); object.context.putU32(preferred_action); object.context.finishWrite(object.id, 4); } // wl_data_source pub const wl_data_source_interface = struct { // offer to transfer data target: ?fn (*Context, Object, []u8) anyerror!void, send: ?fn (*Context, Object, []u8, i32) anyerror!void, cancelled: ?fn ( *Context, Object, ) anyerror!void, dnd_drop_performed: ?fn ( *Context, Object, ) anyerror!void, dnd_finished: ?fn ( *Context, Object, ) anyerror!void, action: ?fn (*Context, Object, u32) anyerror!void, }; fn wl_data_source_target_default(context: *Context, object: Object, mime_type: []u8) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_data_source_send_default(context: *Context, object: Object, mime_type: []u8, fd: i32) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_data_source_cancelled_default(context: *Context, object: Object) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_data_source_dnd_drop_performed_default(context: *Context, object: Object) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_data_source_dnd_finished_default(context: *Context, object: Object) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_data_source_action_default(context: *Context, object: Object, dnd_action: u32) anyerror!void { return error.DebugFunctionNotImplemented; } pub var WL_DATA_SOURCE = wl_data_source_interface{ .target = wl_data_source_target_default, .send = wl_data_source_send_default, .cancelled = wl_data_source_cancelled_default, .dnd_drop_performed = wl_data_source_dnd_drop_performed_default, .dnd_finished = wl_data_source_dnd_finished_default, .action = wl_data_source_action_default, }; pub fn new_wl_data_source(id: u32, context: *Context, container: usize) Object { return Object{ .id = id, .dispatch = wl_data_source_dispatch, .context = context, .version = 0, .container = container, }; } fn wl_data_source_dispatch(object: Object, opcode: u16) anyerror!void { switch (opcode) { // target 0 => { var mime_type: []u8 = try object.context.next_string(); if (WL_DATA_SOURCE.target) |target| { try target(object.context, object, mime_type); } }, // send 1 => { var mime_type: []u8 = try object.context.next_string(); var fd: i32 = try object.context.next_fd(); if (WL_DATA_SOURCE.send) |send| { try send(object.context, object, mime_type, fd); } }, // cancelled 2 => { if (WL_DATA_SOURCE.cancelled) |cancelled| { try cancelled( object.context, object, ); } }, // dnd_drop_performed 3 => { if (WL_DATA_SOURCE.dnd_drop_performed) |dnd_drop_performed| { try dnd_drop_performed( object.context, object, ); } }, // dnd_finished 4 => { if (WL_DATA_SOURCE.dnd_finished) |dnd_finished| { try dnd_finished( object.context, object, ); } }, // action 5 => { var dnd_action: u32 = try object.context.next_u32(); if (WL_DATA_SOURCE.action) |action| { try action(object.context, object, dnd_action); } }, else => {}, } } pub const wl_data_source_error = enum(u32) { invalid_action_mask = 0, invalid_source = 1, }; // // This request adds a mime type to the set of mime types // advertised to targets. Can be called several times to offer // multiple types. // pub fn wl_data_source_send_offer(object: Object, mime_type: []const u8) anyerror!void { object.context.startWrite(); object.context.putString(mime_type); object.context.finishWrite(object.id, 0); } // // Destroy the data source. // pub fn wl_data_source_send_destroy(object: Object) anyerror!void { object.context.startWrite(); object.context.finishWrite(object.id, 1); } // // Sets the actions that the source side client supports for this // operation. This request may trigger wl_data_source.action and // wl_data_offer.action events if the compositor needs to change the // selected action. // // The dnd_actions argument must contain only values expressed in the // wl_data_device_manager.dnd_actions enum, otherwise it will result // in a protocol error. // // This request must be made once only, and can only be made on sources // used in drag-and-drop, so it must be performed before // wl_data_device.start_drag. Attempting to use the source other than // for drag-and-drop will raise a protocol error. // pub fn wl_data_source_send_set_actions(object: Object, dnd_actions: u32) anyerror!void { object.context.startWrite(); object.context.putU32(dnd_actions); object.context.finishWrite(object.id, 2); } // wl_data_device pub const wl_data_device_interface = struct { // data transfer device data_offer: ?fn (*Context, Object, u32) anyerror!void, enter: ?fn (*Context, Object, u32, Object, f32, f32, ?Object) anyerror!void, leave: ?fn ( *Context, Object, ) anyerror!void, motion: ?fn (*Context, Object, u32, f32, f32) anyerror!void, drop: ?fn ( *Context, Object, ) anyerror!void, selection: ?fn (*Context, Object, ?Object) anyerror!void, }; fn wl_data_device_data_offer_default(context: *Context, object: Object, id: u32) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_data_device_enter_default(context: *Context, object: Object, serial: u32, surface: Object, x: f32, y: f32, id: ?Object) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_data_device_leave_default(context: *Context, object: Object) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_data_device_motion_default(context: *Context, object: Object, time: u32, x: f32, y: f32) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_data_device_drop_default(context: *Context, object: Object) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_data_device_selection_default(context: *Context, object: Object, id: ?Object) anyerror!void { return error.DebugFunctionNotImplemented; } pub var WL_DATA_DEVICE = wl_data_device_interface{ .data_offer = wl_data_device_data_offer_default, .enter = wl_data_device_enter_default, .leave = wl_data_device_leave_default, .motion = wl_data_device_motion_default, .drop = wl_data_device_drop_default, .selection = wl_data_device_selection_default, }; pub fn new_wl_data_device(id: u32, context: *Context, container: usize) Object { return Object{ .id = id, .dispatch = wl_data_device_dispatch, .context = context, .version = 0, .container = container, }; } fn wl_data_device_dispatch(object: Object, opcode: u16) anyerror!void { switch (opcode) { // data_offer 0 => { var id: u32 = try object.context.next_u32(); if (WL_DATA_DEVICE.data_offer) |data_offer| { try data_offer(object.context, object, id); } }, // enter 1 => { var serial: u32 = try object.context.next_u32(); var surface: Object = object.context.objects.get(try object.context.next_u32()).?; if (surface.dispatch != wl_surface_dispatch) { return error.ObjectWrongType; } var x: f32 = try object.context.next_fixed(); var y: f32 = try object.context.next_fixed(); var id: ?Object = object.context.objects.get(try object.context.next_u32()); if (id != null) { if (id.?.dispatch != wl_data_offer_dispatch) { return error.ObjectWrongType; } } if (WL_DATA_DEVICE.enter) |enter| { try enter(object.context, object, serial, surface, x, y, id); } }, // leave 2 => { if (WL_DATA_DEVICE.leave) |leave| { try leave( object.context, object, ); } }, // motion 3 => { var time: u32 = try object.context.next_u32(); var x: f32 = try object.context.next_fixed(); var y: f32 = try object.context.next_fixed(); if (WL_DATA_DEVICE.motion) |motion| { try motion(object.context, object, time, x, y); } }, // drop 4 => { if (WL_DATA_DEVICE.drop) |drop| { try drop( object.context, object, ); } }, // selection 5 => { var id: ?Object = object.context.objects.get(try object.context.next_u32()); if (id != null) { if (id.?.dispatch != wl_data_offer_dispatch) { return error.ObjectWrongType; } } if (WL_DATA_DEVICE.selection) |selection| { try selection(object.context, object, id); } }, else => {}, } } pub const wl_data_device_error = enum(u32) { role = 0, }; // // This request asks the compositor to start a drag-and-drop // operation on behalf of the client. // // The source argument is the data source that provides the data // for the eventual data transfer. If source is NULL, enter, leave // and motion events are sent only to the client that initiated the // drag and the client is expected to handle the data passing // internally. // // The origin surface is the surface where the drag originates and // the client must have an active implicit grab that matches the // serial. // // The icon surface is an optional (can be NULL) surface that // provides an icon to be moved around with the cursor. Initially, // the top-left corner of the icon surface is placed at the cursor // hotspot, but subsequent wl_surface.attach request can move the // relative position. Attach requests must be confirmed with // wl_surface.commit as usual. The icon surface is given the role of // a drag-and-drop icon. If the icon surface already has another role, // it raises a protocol error. // // The current and pending input regions of the icon wl_surface are // cleared, and wl_surface.set_input_region is ignored until the // wl_surface is no longer used as the icon surface. When the use // as an icon ends, the current and pending input regions become // undefined, and the wl_surface is unmapped. // pub fn wl_data_device_send_start_drag(object: Object, source: u32, origin: u32, icon: u32, serial: u32) anyerror!void { object.context.startWrite(); object.context.putU32(source); object.context.putU32(origin); object.context.putU32(icon); object.context.putU32(serial); object.context.finishWrite(object.id, 0); } // // This request asks the compositor to set the selection // to the data from the source on behalf of the client. // // To unset the selection, set the source to NULL. // pub fn wl_data_device_send_set_selection(object: Object, source: u32, serial: u32) anyerror!void { object.context.startWrite(); object.context.putU32(source); object.context.putU32(serial); object.context.finishWrite(object.id, 1); } // // This request destroys the data device. // pub fn wl_data_device_send_release(object: Object) anyerror!void { object.context.startWrite(); object.context.finishWrite(object.id, 2); } // wl_data_device_manager pub const wl_data_device_manager_interface = struct { // data transfer interface }; pub var WL_DATA_DEVICE_MANAGER = wl_data_device_manager_interface{}; pub fn new_wl_data_device_manager(id: u32, context: *Context, container: usize) Object { return Object{ .id = id, .dispatch = wl_data_device_manager_dispatch, .context = context, .version = 0, .container = container, }; } fn wl_data_device_manager_dispatch(object: Object, opcode: u16) anyerror!void { switch (opcode) { else => {}, } } pub const wl_data_device_manager_dnd_action = enum(u32) { none = 0, copy = 1, move = 2, ask = 4, }; // // Create a new data source. // pub fn wl_data_device_manager_send_create_data_source(object: Object, id: u32) anyerror!void { object.context.startWrite(); object.context.putU32(id); object.context.finishWrite(object.id, 0); } // // Create a new data device for a given seat. // pub fn wl_data_device_manager_send_get_data_device(object: Object, id: u32, seat: u32) anyerror!void { object.context.startWrite(); object.context.putU32(id); object.context.putU32(seat); object.context.finishWrite(object.id, 1); } // wl_shell pub const wl_shell_interface = struct { // create desktop-style surfaces }; pub var WL_SHELL = wl_shell_interface{}; pub fn new_wl_shell(id: u32, context: *Context, container: usize) Object { return Object{ .id = id, .dispatch = wl_shell_dispatch, .context = context, .version = 0, .container = container, }; } fn wl_shell_dispatch(object: Object, opcode: u16) anyerror!void { switch (opcode) { else => {}, } } pub const wl_shell_error = enum(u32) { role = 0, }; // // Create a shell surface for an existing surface. This gives // the wl_surface the role of a shell surface. If the wl_surface // already has another role, it raises a protocol error. // // Only one shell surface can be associated with a given surface. // pub fn wl_shell_send_get_shell_surface(object: Object, id: u32, surface: u32) anyerror!void { object.context.startWrite(); object.context.putU32(id); object.context.putU32(surface); object.context.finishWrite(object.id, 0); } // wl_shell_surface pub const wl_shell_surface_interface = struct { // desktop-style metadata interface ping: ?fn (*Context, Object, u32) anyerror!void, configure: ?fn (*Context, Object, u32, i32, i32) anyerror!void, popup_done: ?fn ( *Context, Object, ) anyerror!void, }; fn wl_shell_surface_ping_default(context: *Context, object: Object, serial: u32) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_shell_surface_configure_default(context: *Context, object: Object, edges: u32, width: i32, height: i32) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_shell_surface_popup_done_default(context: *Context, object: Object) anyerror!void { return error.DebugFunctionNotImplemented; } pub var WL_SHELL_SURFACE = wl_shell_surface_interface{ .ping = wl_shell_surface_ping_default, .configure = wl_shell_surface_configure_default, .popup_done = wl_shell_surface_popup_done_default, }; pub fn new_wl_shell_surface(id: u32, context: *Context, container: usize) Object { return Object{ .id = id, .dispatch = wl_shell_surface_dispatch, .context = context, .version = 0, .container = container, }; } fn wl_shell_surface_dispatch(object: Object, opcode: u16) anyerror!void { switch (opcode) { // ping 0 => { var serial: u32 = try object.context.next_u32(); if (WL_SHELL_SURFACE.ping) |ping| { try ping(object.context, object, serial); } }, // configure 1 => { var edges: u32 = try object.context.next_u32(); var width: i32 = try object.context.next_i32(); var height: i32 = try object.context.next_i32(); if (WL_SHELL_SURFACE.configure) |configure| { try configure(object.context, object, edges, width, height); } }, // popup_done 2 => { if (WL_SHELL_SURFACE.popup_done) |popup_done| { try popup_done( object.context, object, ); } }, else => {}, } } pub const wl_shell_surface_resize = enum(u32) { none = 0, top = 1, bottom = 2, left = 4, top_left = 5, bottom_left = 6, right = 8, top_right = 9, bottom_right = 10, }; pub const wl_shell_surface_transient = enum(u32) { inactive = 0x1, }; pub const wl_shell_surface_fullscreen_method = enum(u32) { default = 0, scale = 1, driver = 2, fill = 3, }; // // A client must respond to a ping event with a pong request or // the client may be deemed unresponsive. // pub fn wl_shell_surface_send_pong(object: Object, serial: u32) anyerror!void { object.context.startWrite(); object.context.putU32(serial); object.context.finishWrite(object.id, 0); } // // Start a pointer-driven move of the surface. // // This request must be used in response to a button press event. // The server may ignore move requests depending on the state of // the surface (e.g. fullscreen or maximized). // pub fn wl_shell_surface_send_move(object: Object, seat: u32, serial: u32) anyerror!void { object.context.startWrite(); object.context.putU32(seat); object.context.putU32(serial); object.context.finishWrite(object.id, 1); } // // Start a pointer-driven resizing of the surface. // // This request must be used in response to a button press event. // The server may ignore resize requests depending on the state of // the surface (e.g. fullscreen or maximized). // pub fn wl_shell_surface_send_resize(object: Object, seat: u32, serial: u32, edges: u32) anyerror!void { object.context.startWrite(); object.context.putU32(seat); object.context.putU32(serial); object.context.putU32(edges); object.context.finishWrite(object.id, 2); } // // Map the surface as a toplevel surface. // // A toplevel surface is not fullscreen, maximized or transient. // pub fn wl_shell_surface_send_set_toplevel(object: Object) anyerror!void { object.context.startWrite(); object.context.finishWrite(object.id, 3); } // // Map the surface relative to an existing surface. // // The x and y arguments specify the location of the upper left // corner of the surface relative to the upper left corner of the // parent surface, in surface-local coordinates. // // The flags argument controls details of the transient behaviour. // pub fn wl_shell_surface_send_set_transient(object: Object, parent: u32, x: i32, y: i32, flags: u32) anyerror!void { object.context.startWrite(); object.context.putU32(parent); object.context.putI32(x); object.context.putI32(y); object.context.putU32(flags); object.context.finishWrite(object.id, 4); } // // Map the surface as a fullscreen surface. // // If an output parameter is given then the surface will be made // fullscreen on that output. If the client does not specify the // output then the compositor will apply its policy - usually // choosing the output on which the surface has the biggest surface // area. // // The client may specify a method to resolve a size conflict // between the output size and the surface size - this is provided // through the method parameter. // // The framerate parameter is used only when the method is set // to "driver", to indicate the preferred framerate. A value of 0 // indicates that the client does not care about framerate. The // framerate is specified in mHz, that is framerate of 60000 is 60Hz. // // A method of "scale" or "driver" implies a scaling operation of // the surface, either via a direct scaling operation or a change of // the output mode. This will override any kind of output scaling, so // that mapping a surface with a buffer size equal to the mode can // fill the screen independent of buffer_scale. // // A method of "fill" means we don't scale up the buffer, however // any output scale is applied. This means that you may run into // an edge case where the application maps a buffer with the same // size of the output mode but buffer_scale 1 (thus making a // surface larger than the output). In this case it is allowed to // downscale the results to fit the screen. // // The compositor must reply to this request with a configure event // with the dimensions for the output on which the surface will // be made fullscreen. // pub fn wl_shell_surface_send_set_fullscreen(object: Object, method: u32, framerate: u32, output: u32) anyerror!void { object.context.startWrite(); object.context.putU32(method); object.context.putU32(framerate); object.context.putU32(output); object.context.finishWrite(object.id, 5); } // // Map the surface as a popup. // // A popup surface is a transient surface with an added pointer // grab. // // An existing implicit grab will be changed to owner-events mode, // and the popup grab will continue after the implicit grab ends // (i.e. releasing the mouse button does not cause the popup to // be unmapped). // // The popup grab continues until the window is destroyed or a // mouse button is pressed in any other client's window. A click // in any of the client's surfaces is reported as normal, however, // clicks in other clients' surfaces will be discarded and trigger // the callback. // // The x and y arguments specify the location of the upper left // corner of the surface relative to the upper left corner of the // parent surface, in surface-local coordinates. // pub fn wl_shell_surface_send_set_popup(object: Object, seat: u32, serial: u32, parent: u32, x: i32, y: i32, flags: u32) anyerror!void { object.context.startWrite(); object.context.putU32(seat); object.context.putU32(serial); object.context.putU32(parent); object.context.putI32(x); object.context.putI32(y); object.context.putU32(flags); object.context.finishWrite(object.id, 6); } // // Map the surface as a maximized surface. // // If an output parameter is given then the surface will be // maximized on that output. If the client does not specify the // output then the compositor will apply its policy - usually // choosing the output on which the surface has the biggest surface // area. // // The compositor will reply with a configure event telling // the expected new surface size. The operation is completed // on the next buffer attach to this surface. // // A maximized surface typically fills the entire output it is // bound to, except for desktop elements such as panels. This is // the main difference between a maximized shell surface and a // fullscreen shell surface. // // The details depend on the compositor implementation. // pub fn wl_shell_surface_send_set_maximized(object: Object, output: u32) anyerror!void { object.context.startWrite(); object.context.putU32(output); object.context.finishWrite(object.id, 7); } // // Set a short title for the surface. // // This string may be used to identify the surface in a task bar, // window list, or other user interface elements provided by the // compositor. // // The string must be encoded in UTF-8. // pub fn wl_shell_surface_send_set_title(object: Object, title: []const u8) anyerror!void { object.context.startWrite(); object.context.putString(title); object.context.finishWrite(object.id, 8); } // // Set a class for the surface. // // The surface class identifies the general class of applications // to which the surface belongs. A common convention is to use the // file name (or the full path if it is a non-standard location) of // the application's .desktop file as the class. // pub fn wl_shell_surface_send_set_class(object: Object, class_: []const u8) anyerror!void { object.context.startWrite(); object.context.putString(class_); object.context.finishWrite(object.id, 9); } // wl_surface pub const wl_surface_interface = struct { // an onscreen surface enter: ?fn (*Context, Object, Object) anyerror!void, leave: ?fn (*Context, Object, Object) anyerror!void, }; fn wl_surface_enter_default(context: *Context, object: Object, output: Object) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_surface_leave_default(context: *Context, object: Object, output: Object) anyerror!void { return error.DebugFunctionNotImplemented; } pub var WL_SURFACE = wl_surface_interface{ .enter = wl_surface_enter_default, .leave = wl_surface_leave_default, }; pub fn new_wl_surface(id: u32, context: *Context, container: usize) Object { return Object{ .id = id, .dispatch = wl_surface_dispatch, .context = context, .version = 0, .container = container, }; } fn wl_surface_dispatch(object: Object, opcode: u16) anyerror!void { switch (opcode) { // enter 0 => { var output: Object = object.context.objects.get(try object.context.next_u32()).?; if (output.dispatch != wl_output_dispatch) { return error.ObjectWrongType; } if (WL_SURFACE.enter) |enter| { try enter(object.context, object, output); } }, // leave 1 => { var output: Object = object.context.objects.get(try object.context.next_u32()).?; if (output.dispatch != wl_output_dispatch) { return error.ObjectWrongType; } if (WL_SURFACE.leave) |leave| { try leave(object.context, object, output); } }, else => {}, } } pub const wl_surface_error = enum(u32) { invalid_scale = 0, invalid_transform = 1, }; // // Deletes the surface and invalidates its object ID. // pub fn wl_surface_send_destroy(object: Object) anyerror!void { object.context.startWrite(); object.context.finishWrite(object.id, 0); } // // Set a buffer as the content of this surface. // // The new size of the surface is calculated based on the buffer // size transformed by the inverse buffer_transform and the // inverse buffer_scale. This means that the supplied buffer // must be an integer multiple of the buffer_scale. // // The x and y arguments specify the location of the new pending // buffer's upper left corner, relative to the current buffer's upper // left corner, in surface-local coordinates. In other words, the // x and y, combined with the new surface size define in which // directions the surface's size changes. // // Surface contents are double-buffered state, see wl_surface.commit. // // The initial surface contents are void; there is no content. // wl_surface.attach assigns the given wl_buffer as the pending // wl_buffer. wl_surface.commit makes the pending wl_buffer the new // surface contents, and the size of the surface becomes the size // calculated from the wl_buffer, as described above. After commit, // there is no pending buffer until the next attach. // // Committing a pending wl_buffer allows the compositor to read the // pixels in the wl_buffer. The compositor may access the pixels at // any time after the wl_surface.commit request. When the compositor // will not access the pixels anymore, it will send the // wl_buffer.release event. Only after receiving wl_buffer.release, // the client may reuse the wl_buffer. A wl_buffer that has been // attached and then replaced by another attach instead of committed // will not receive a release event, and is not used by the // compositor. // // Destroying the wl_buffer after wl_buffer.release does not change // the surface contents. However, if the client destroys the // wl_buffer before receiving the wl_buffer.release event, the surface // contents become undefined immediately. // // If wl_surface.attach is sent with a NULL wl_buffer, the // following wl_surface.commit will remove the surface content. // pub fn wl_surface_send_attach(object: Object, buffer: u32, x: i32, y: i32) anyerror!void { object.context.startWrite(); object.context.putU32(buffer); object.context.putI32(x); object.context.putI32(y); object.context.finishWrite(object.id, 1); } // // This request is used to describe the regions where the pending // buffer is different from the current surface contents, and where // the surface therefore needs to be repainted. The compositor // ignores the parts of the damage that fall outside of the surface. // // Damage is double-buffered state, see wl_surface.commit. // // The damage rectangle is specified in surface-local coordinates, // where x and y specify the upper left corner of the damage rectangle. // // The initial value for pending damage is empty: no damage. // wl_surface.damage adds pending damage: the new pending damage // is the union of old pending damage and the given rectangle. // // wl_surface.commit assigns pending damage as the current damage, // and clears pending damage. The server will clear the current // damage as it repaints the surface. // // Note! New clients should not use this request. Instead damage can be // posted with wl_surface.damage_buffer which uses buffer coordinates // instead of surface coordinates. // pub fn wl_surface_send_damage(object: Object, x: i32, y: i32, width: i32, height: i32) anyerror!void { object.context.startWrite(); object.context.putI32(x); object.context.putI32(y); object.context.putI32(width); object.context.putI32(height); object.context.finishWrite(object.id, 2); } // // Request a notification when it is a good time to start drawing a new // frame, by creating a frame callback. This is useful for throttling // redrawing operations, and driving animations. // // When a client is animating on a wl_surface, it can use the 'frame' // request to get notified when it is a good time to draw and commit the // next frame of animation. If the client commits an update earlier than // that, it is likely that some updates will not make it to the display, // and the client is wasting resources by drawing too often. // // The frame request will take effect on the next wl_surface.commit. // The notification will only be posted for one frame unless // requested again. For a wl_surface, the notifications are posted in // the order the frame requests were committed. // // The server must send the notifications so that a client // will not send excessive updates, while still allowing // the highest possible update rate for clients that wait for the reply // before drawing again. The server should give some time for the client // to draw and commit after sending the frame callback events to let it // hit the next output refresh. // // A server should avoid signaling the frame callbacks if the // surface is not visible in any way, e.g. the surface is off-screen, // or completely obscured by other opaque surfaces. // // The object returned by this request will be destroyed by the // compositor after the callback is fired and as such the client must not // attempt to use it after that point. // // The callback_data passed in the callback is the current time, in // milliseconds, with an undefined base. // pub fn wl_surface_send_frame(object: Object, callback: u32) anyerror!void { object.context.startWrite(); object.context.putU32(callback); object.context.finishWrite(object.id, 3); } // // This request sets the region of the surface that contains // opaque content. // // The opaque region is an optimization hint for the compositor // that lets it optimize the redrawing of content behind opaque // regions. Setting an opaque region is not required for correct // behaviour, but marking transparent content as opaque will result // in repaint artifacts. // // The opaque region is specified in surface-local coordinates. // // The compositor ignores the parts of the opaque region that fall // outside of the surface. // // Opaque region is double-buffered state, see wl_surface.commit. // // wl_surface.set_opaque_region changes the pending opaque region. // wl_surface.commit copies the pending region to the current region. // Otherwise, the pending and current regions are never changed. // // The initial value for an opaque region is empty. Setting the pending // opaque region has copy semantics, and the wl_region object can be // destroyed immediately. A NULL wl_region causes the pending opaque // region to be set to empty. // pub fn wl_surface_send_set_opaque_region(object: Object, region: u32) anyerror!void { object.context.startWrite(); object.context.putU32(region); object.context.finishWrite(object.id, 4); } // // This request sets the region of the surface that can receive // pointer and touch events. // // Input events happening outside of this region will try the next // surface in the server surface stack. The compositor ignores the // parts of the input region that fall outside of the surface. // // The input region is specified in surface-local coordinates. // // Input region is double-buffered state, see wl_surface.commit. // // wl_surface.set_input_region changes the pending input region. // wl_surface.commit copies the pending region to the current region. // Otherwise the pending and current regions are never changed, // except cursor and icon surfaces are special cases, see // wl_pointer.set_cursor and wl_data_device.start_drag. // // The initial value for an input region is infinite. That means the // whole surface will accept input. Setting the pending input region // has copy semantics, and the wl_region object can be destroyed // immediately. A NULL wl_region causes the input region to be set // to infinite. // pub fn wl_surface_send_set_input_region(object: Object, region: u32) anyerror!void { object.context.startWrite(); object.context.putU32(region); object.context.finishWrite(object.id, 5); } // // Surface state (input, opaque, and damage regions, attached buffers, // etc.) is double-buffered. Protocol requests modify the pending state, // as opposed to the current state in use by the compositor. A commit // request atomically applies all pending state, replacing the current // state. After commit, the new pending state is as documented for each // related request. // // On commit, a pending wl_buffer is applied first, and all other state // second. This means that all coordinates in double-buffered state are // relative to the new wl_buffer coming into use, except for // wl_surface.attach itself. If there is no pending wl_buffer, the // coordinates are relative to the current surface contents. // // All requests that need a commit to become effective are documented // to affect double-buffered state. // // Other interfaces may add further double-buffered surface state. // pub fn wl_surface_send_commit(object: Object) anyerror!void { object.context.startWrite(); object.context.finishWrite(object.id, 6); } // // This request sets an optional transformation on how the compositor // interprets the contents of the buffer attached to the surface. The // accepted values for the transform parameter are the values for // wl_output.transform. // // Buffer transform is double-buffered state, see wl_surface.commit. // // A newly created surface has its buffer transformation set to normal. // // wl_surface.set_buffer_transform changes the pending buffer // transformation. wl_surface.commit copies the pending buffer // transformation to the current one. Otherwise, the pending and current // values are never changed. // // The purpose of this request is to allow clients to render content // according to the output transform, thus permitting the compositor to // use certain optimizations even if the display is rotated. Using // hardware overlays and scanning out a client buffer for fullscreen // surfaces are examples of such optimizations. Those optimizations are // highly dependent on the compositor implementation, so the use of this // request should be considered on a case-by-case basis. // // Note that if the transform value includes 90 or 270 degree rotation, // the width of the buffer will become the surface height and the height // of the buffer will become the surface width. // // If transform is not one of the values from the // wl_output.transform enum the invalid_transform protocol error // is raised. // pub fn wl_surface_send_set_buffer_transform(object: Object, transform: i32) anyerror!void { object.context.startWrite(); object.context.putI32(transform); object.context.finishWrite(object.id, 7); } // // This request sets an optional scaling factor on how the compositor // interprets the contents of the buffer attached to the window. // // Buffer scale is double-buffered state, see wl_surface.commit. // // A newly created surface has its buffer scale set to 1. // // wl_surface.set_buffer_scale changes the pending buffer scale. // wl_surface.commit copies the pending buffer scale to the current one. // Otherwise, the pending and current values are never changed. // // The purpose of this request is to allow clients to supply higher // resolution buffer data for use on high resolution outputs. It is // intended that you pick the same buffer scale as the scale of the // output that the surface is displayed on. This means the compositor // can avoid scaling when rendering the surface on that output. // // Note that if the scale is larger than 1, then you have to attach // a buffer that is larger (by a factor of scale in each dimension) // than the desired surface size. // // If scale is not positive the invalid_scale protocol error is // raised. // pub fn wl_surface_send_set_buffer_scale(object: Object, scale: i32) anyerror!void { object.context.startWrite(); object.context.putI32(scale); object.context.finishWrite(object.id, 8); } // // This request is used to describe the regions where the pending // buffer is different from the current surface contents, and where // the surface therefore needs to be repainted. The compositor // ignores the parts of the damage that fall outside of the surface. // // Damage is double-buffered state, see wl_surface.commit. // // The damage rectangle is specified in buffer coordinates, // where x and y specify the upper left corner of the damage rectangle. // // The initial value for pending damage is empty: no damage. // wl_surface.damage_buffer adds pending damage: the new pending // damage is the union of old pending damage and the given rectangle. // // wl_surface.commit assigns pending damage as the current damage, // and clears pending damage. The server will clear the current // damage as it repaints the surface. // // This request differs from wl_surface.damage in only one way - it // takes damage in buffer coordinates instead of surface-local // coordinates. While this generally is more intuitive than surface // coordinates, it is especially desirable when using wp_viewport // or when a drawing library (like EGL) is unaware of buffer scale // and buffer transform. // // Note: Because buffer transformation changes and damage requests may // be interleaved in the protocol stream, it is impossible to determine // the actual mapping between surface and buffer damage until // wl_surface.commit time. Therefore, compositors wishing to take both // kinds of damage into account will have to accumulate damage from the // two requests separately and only transform from one to the other // after receiving the wl_surface.commit. // pub fn wl_surface_send_damage_buffer(object: Object, x: i32, y: i32, width: i32, height: i32) anyerror!void { object.context.startWrite(); object.context.putI32(x); object.context.putI32(y); object.context.putI32(width); object.context.putI32(height); object.context.finishWrite(object.id, 9); } // wl_seat pub const wl_seat_interface = struct { // group of input devices capabilities: ?fn (*Context, Object, u32) anyerror!void, name: ?fn (*Context, Object, []u8) anyerror!void, }; fn wl_seat_capabilities_default(context: *Context, object: Object, capabilities: u32) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_seat_name_default(context: *Context, object: Object, name: []u8) anyerror!void { return error.DebugFunctionNotImplemented; } pub var WL_SEAT = wl_seat_interface{ .capabilities = wl_seat_capabilities_default, .name = wl_seat_name_default, }; pub fn new_wl_seat(id: u32, context: *Context, container: usize) Object { return Object{ .id = id, .dispatch = wl_seat_dispatch, .context = context, .version = 0, .container = container, }; } fn wl_seat_dispatch(object: Object, opcode: u16) anyerror!void { switch (opcode) { // capabilities 0 => { var capabilities: u32 = try object.context.next_u32(); if (WL_SEAT.capabilities) |capabilities| { try capabilities(object.context, object, capabilities); } }, // name 1 => { var name: []u8 = try object.context.next_string(); if (WL_SEAT.name) |name| { try name(object.context, object, name); } }, else => {}, } } pub const wl_seat_capability = enum(u32) { pointer = 1, keyboard = 2, touch = 4, }; // // The ID provided will be initialized to the wl_pointer interface // for this seat. // // This request only takes effect if the seat has the pointer // capability, or has had the pointer capability in the past. // It is a protocol violation to issue this request on a seat that has // never had the pointer capability. // pub fn wl_seat_send_get_pointer(object: Object, id: u32) anyerror!void { object.context.startWrite(); object.context.putU32(id); object.context.finishWrite(object.id, 0); } // // The ID provided will be initialized to the wl_keyboard interface // for this seat. // // This request only takes effect if the seat has the keyboard // capability, or has had the keyboard capability in the past. // It is a protocol violation to issue this request on a seat that has // never had the keyboard capability. // pub fn wl_seat_send_get_keyboard(object: Object, id: u32) anyerror!void { object.context.startWrite(); object.context.putU32(id); object.context.finishWrite(object.id, 1); } // // The ID provided will be initialized to the wl_touch interface // for this seat. // // This request only takes effect if the seat has the touch // capability, or has had the touch capability in the past. // It is a protocol violation to issue this request on a seat that has // never had the touch capability. // pub fn wl_seat_send_get_touch(object: Object, id: u32) anyerror!void { object.context.startWrite(); object.context.putU32(id); object.context.finishWrite(object.id, 2); } // // Using this request a client can tell the server that it is not going to // use the seat object anymore. // pub fn wl_seat_send_release(object: Object) anyerror!void { object.context.startWrite(); object.context.finishWrite(object.id, 3); } // wl_pointer pub const wl_pointer_interface = struct { // pointer input device enter: ?fn (*Context, Object, u32, Object, f32, f32) anyerror!void, leave: ?fn (*Context, Object, u32, Object) anyerror!void, motion: ?fn (*Context, Object, u32, f32, f32) anyerror!void, button: ?fn (*Context, Object, u32, u32, u32, u32) anyerror!void, axis: ?fn (*Context, Object, u32, u32, f32) anyerror!void, frame: ?fn ( *Context, Object, ) anyerror!void, axis_source: ?fn (*Context, Object, u32) anyerror!void, axis_stop: ?fn (*Context, Object, u32, u32) anyerror!void, axis_discrete: ?fn (*Context, Object, u32, i32) anyerror!void, }; fn wl_pointer_enter_default(context: *Context, object: Object, serial: u32, surface: Object, surface_x: f32, surface_y: f32) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_pointer_leave_default(context: *Context, object: Object, serial: u32, surface: Object) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_pointer_motion_default(context: *Context, object: Object, time: u32, surface_x: f32, surface_y: f32) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_pointer_button_default(context: *Context, object: Object, serial: u32, time: u32, button: u32, state: u32) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_pointer_axis_default(context: *Context, object: Object, time: u32, axis: u32, value: f32) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_pointer_frame_default(context: *Context, object: Object) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_pointer_axis_source_default(context: *Context, object: Object, axis_source: u32) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_pointer_axis_stop_default(context: *Context, object: Object, time: u32, axis: u32) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_pointer_axis_discrete_default(context: *Context, object: Object, axis: u32, discrete: i32) anyerror!void { return error.DebugFunctionNotImplemented; } pub var WL_POINTER = wl_pointer_interface{ .enter = wl_pointer_enter_default, .leave = wl_pointer_leave_default, .motion = wl_pointer_motion_default, .button = wl_pointer_button_default, .axis = wl_pointer_axis_default, .frame = wl_pointer_frame_default, .axis_source = wl_pointer_axis_source_default, .axis_stop = wl_pointer_axis_stop_default, .axis_discrete = wl_pointer_axis_discrete_default, }; pub fn new_wl_pointer(id: u32, context: *Context, container: usize) Object { return Object{ .id = id, .dispatch = wl_pointer_dispatch, .context = context, .version = 0, .container = container, }; } fn wl_pointer_dispatch(object: Object, opcode: u16) anyerror!void { switch (opcode) { // enter 0 => { var serial: u32 = try object.context.next_u32(); var surface: Object = object.context.objects.get(try object.context.next_u32()).?; if (surface.dispatch != wl_surface_dispatch) { return error.ObjectWrongType; } var surface_x: f32 = try object.context.next_fixed(); var surface_y: f32 = try object.context.next_fixed(); if (WL_POINTER.enter) |enter| { try enter(object.context, object, serial, surface, surface_x, surface_y); } }, // leave 1 => { var serial: u32 = try object.context.next_u32(); var surface: Object = object.context.objects.get(try object.context.next_u32()).?; if (surface.dispatch != wl_surface_dispatch) { return error.ObjectWrongType; } if (WL_POINTER.leave) |leave| { try leave(object.context, object, serial, surface); } }, // motion 2 => { var time: u32 = try object.context.next_u32(); var surface_x: f32 = try object.context.next_fixed(); var surface_y: f32 = try object.context.next_fixed(); if (WL_POINTER.motion) |motion| { try motion(object.context, object, time, surface_x, surface_y); } }, // button 3 => { var serial: u32 = try object.context.next_u32(); var time: u32 = try object.context.next_u32(); var button: u32 = try object.context.next_u32(); var state: u32 = try object.context.next_u32(); if (WL_POINTER.button) |button| { try button(object.context, object, serial, time, button, state); } }, // axis 4 => { var time: u32 = try object.context.next_u32(); var axis: u32 = try object.context.next_u32(); var value: f32 = try object.context.next_fixed(); if (WL_POINTER.axis) |axis| { try axis(object.context, object, time, axis, value); } }, // frame 5 => { if (WL_POINTER.frame) |frame| { try frame( object.context, object, ); } }, // axis_source 6 => { var axis_source: u32 = try object.context.next_u32(); if (WL_POINTER.axis_source) |axis_source| { try axis_source(object.context, object, axis_source); } }, // axis_stop 7 => { var time: u32 = try object.context.next_u32(); var axis: u32 = try object.context.next_u32(); if (WL_POINTER.axis_stop) |axis_stop| { try axis_stop(object.context, object, time, axis); } }, // axis_discrete 8 => { var axis: u32 = try object.context.next_u32(); var discrete: i32 = try object.context.next_i32(); if (WL_POINTER.axis_discrete) |axis_discrete| { try axis_discrete(object.context, object, axis, discrete); } }, else => {}, } } pub const wl_pointer_error = enum(u32) { role = 0, }; pub const wl_pointer_button_state = enum(u32) { released = 0, pressed = 1, }; pub const wl_pointer_axis = enum(u32) { vertical_scroll = 0, horizontal_scroll = 1, }; pub const wl_pointer_axis_source = enum(u32) { wheel = 0, finger = 1, continuous = 2, wheel_tilt = 3, }; // // Set the pointer surface, i.e., the surface that contains the // pointer image (cursor). This request gives the surface the role // of a cursor. If the surface already has another role, it raises // a protocol error. // // The cursor actually changes only if the pointer // focus for this device is one of the requesting client's surfaces // or the surface parameter is the current pointer surface. If // there was a previous surface set with this request it is // replaced. If surface is NULL, the pointer image is hidden. // // The parameters hotspot_x and hotspot_y define the position of // the pointer surface relative to the pointer location. Its // top-left corner is always at (x, y) - (hotspot_x, hotspot_y), // where (x, y) are the coordinates of the pointer location, in // surface-local coordinates. // // On surface.attach requests to the pointer surface, hotspot_x // and hotspot_y are decremented by the x and y parameters // passed to the request. Attach must be confirmed by // wl_surface.commit as usual. // // The hotspot can also be updated by passing the currently set // pointer surface to this request with new values for hotspot_x // and hotspot_y. // // The current and pending input regions of the wl_surface are // cleared, and wl_surface.set_input_region is ignored until the // wl_surface is no longer used as the cursor. When the use as a // cursor ends, the current and pending input regions become // undefined, and the wl_surface is unmapped. // pub fn wl_pointer_send_set_cursor(object: Object, serial: u32, surface: u32, hotspot_x: i32, hotspot_y: i32) anyerror!void { object.context.startWrite(); object.context.putU32(serial); object.context.putU32(surface); object.context.putI32(hotspot_x); object.context.putI32(hotspot_y); object.context.finishWrite(object.id, 0); } // // Using this request a client can tell the server that it is not going to // use the pointer object anymore. // // This request destroys the pointer proxy object, so clients must not call // wl_pointer_destroy() after using this request. // pub fn wl_pointer_send_release(object: Object) anyerror!void { object.context.startWrite(); object.context.finishWrite(object.id, 1); } // wl_keyboard pub const wl_keyboard_interface = struct { // keyboard input device keymap: ?fn (*Context, Object, u32, i32, u32) anyerror!void, enter: ?fn (*Context, Object, u32, Object, []u32) anyerror!void, leave: ?fn (*Context, Object, u32, Object) anyerror!void, key: ?fn (*Context, Object, u32, u32, u32, u32) anyerror!void, modifiers: ?fn (*Context, Object, u32, u32, u32, u32, u32) anyerror!void, repeat_info: ?fn (*Context, Object, i32, i32) anyerror!void, }; fn wl_keyboard_keymap_default(context: *Context, object: Object, format: u32, fd: i32, size: u32) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_keyboard_enter_default(context: *Context, object: Object, serial: u32, surface: Object, keys: []u32) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_keyboard_leave_default(context: *Context, object: Object, serial: u32, surface: Object) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_keyboard_key_default(context: *Context, object: Object, serial: u32, time: u32, key: u32, state: u32) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_keyboard_modifiers_default(context: *Context, object: Object, serial: u32, mods_depressed: u32, mods_latched: u32, mods_locked: u32, group: u32) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_keyboard_repeat_info_default(context: *Context, object: Object, rate: i32, delay: i32) anyerror!void { return error.DebugFunctionNotImplemented; } pub var WL_KEYBOARD = wl_keyboard_interface{ .keymap = wl_keyboard_keymap_default, .enter = wl_keyboard_enter_default, .leave = wl_keyboard_leave_default, .key = wl_keyboard_key_default, .modifiers = wl_keyboard_modifiers_default, .repeat_info = wl_keyboard_repeat_info_default, }; pub fn new_wl_keyboard(id: u32, context: *Context, container: usize) Object { return Object{ .id = id, .dispatch = wl_keyboard_dispatch, .context = context, .version = 0, .container = container, }; } fn wl_keyboard_dispatch(object: Object, opcode: u16) anyerror!void { switch (opcode) { // keymap 0 => { var format: u32 = try object.context.next_u32(); var fd: i32 = try object.context.next_fd(); var size: u32 = try object.context.next_u32(); if (WL_KEYBOARD.keymap) |keymap| { try keymap(object.context, object, format, fd, size); } }, // enter 1 => { var serial: u32 = try object.context.next_u32(); var surface: Object = object.context.objects.get(try object.context.next_u32()).?; if (surface.dispatch != wl_surface_dispatch) { return error.ObjectWrongType; } var keys: []u32 = try object.context.next_array(); if (WL_KEYBOARD.enter) |enter| { try enter(object.context, object, serial, surface, keys); } }, // leave 2 => { var serial: u32 = try object.context.next_u32(); var surface: Object = object.context.objects.get(try object.context.next_u32()).?; if (surface.dispatch != wl_surface_dispatch) { return error.ObjectWrongType; } if (WL_KEYBOARD.leave) |leave| { try leave(object.context, object, serial, surface); } }, // key 3 => { var serial: u32 = try object.context.next_u32(); var time: u32 = try object.context.next_u32(); var key: u32 = try object.context.next_u32(); var state: u32 = try object.context.next_u32(); if (WL_KEYBOARD.key) |key| { try key(object.context, object, serial, time, key, state); } }, // modifiers 4 => { var serial: u32 = try object.context.next_u32(); var mods_depressed: u32 = try object.context.next_u32(); var mods_latched: u32 = try object.context.next_u32(); var mods_locked: u32 = try object.context.next_u32(); var group: u32 = try object.context.next_u32(); if (WL_KEYBOARD.modifiers) |modifiers| { try modifiers(object.context, object, serial, mods_depressed, mods_latched, mods_locked, group); } }, // repeat_info 5 => { var rate: i32 = try object.context.next_i32(); var delay: i32 = try object.context.next_i32(); if (WL_KEYBOARD.repeat_info) |repeat_info| { try repeat_info(object.context, object, rate, delay); } }, else => {}, } } pub const wl_keyboard_keymap_format = enum(u32) { no_keymap = 0, xkb_v1 = 1, }; pub const wl_keyboard_key_state = enum(u32) { released = 0, pressed = 1, }; pub fn wl_keyboard_send_release(object: Object) anyerror!void { object.context.startWrite(); object.context.finishWrite(object.id, 0); } // wl_touch pub const wl_touch_interface = struct { // touchscreen input device down: ?fn (*Context, Object, u32, u32, Object, i32, f32, f32) anyerror!void, up: ?fn (*Context, Object, u32, u32, i32) anyerror!void, motion: ?fn (*Context, Object, u32, i32, f32, f32) anyerror!void, frame: ?fn ( *Context, Object, ) anyerror!void, cancel: ?fn ( *Context, Object, ) anyerror!void, shape: ?fn (*Context, Object, i32, f32, f32) anyerror!void, orientation: ?fn (*Context, Object, i32, f32) anyerror!void, }; fn wl_touch_down_default(context: *Context, object: Object, serial: u32, time: u32, surface: Object, id: i32, x: f32, y: f32) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_touch_up_default(context: *Context, object: Object, serial: u32, time: u32, id: i32) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_touch_motion_default(context: *Context, object: Object, time: u32, id: i32, x: f32, y: f32) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_touch_frame_default(context: *Context, object: Object) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_touch_cancel_default(context: *Context, object: Object) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_touch_shape_default(context: *Context, object: Object, id: i32, major: f32, minor: f32) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_touch_orientation_default(context: *Context, object: Object, id: i32, orientation: f32) anyerror!void { return error.DebugFunctionNotImplemented; } pub var WL_TOUCH = wl_touch_interface{ .down = wl_touch_down_default, .up = wl_touch_up_default, .motion = wl_touch_motion_default, .frame = wl_touch_frame_default, .cancel = wl_touch_cancel_default, .shape = wl_touch_shape_default, .orientation = wl_touch_orientation_default, }; pub fn new_wl_touch(id: u32, context: *Context, container: usize) Object { return Object{ .id = id, .dispatch = wl_touch_dispatch, .context = context, .version = 0, .container = container, }; } fn wl_touch_dispatch(object: Object, opcode: u16) anyerror!void { switch (opcode) { // down 0 => { var serial: u32 = try object.context.next_u32(); var time: u32 = try object.context.next_u32(); var surface: Object = object.context.objects.get(try object.context.next_u32()).?; if (surface.dispatch != wl_surface_dispatch) { return error.ObjectWrongType; } var id: i32 = try object.context.next_i32(); var x: f32 = try object.context.next_fixed(); var y: f32 = try object.context.next_fixed(); if (WL_TOUCH.down) |down| { try down(object.context, object, serial, time, surface, id, x, y); } }, // up 1 => { var serial: u32 = try object.context.next_u32(); var time: u32 = try object.context.next_u32(); var id: i32 = try object.context.next_i32(); if (WL_TOUCH.up) |up| { try up(object.context, object, serial, time, id); } }, // motion 2 => { var time: u32 = try object.context.next_u32(); var id: i32 = try object.context.next_i32(); var x: f32 = try object.context.next_fixed(); var y: f32 = try object.context.next_fixed(); if (WL_TOUCH.motion) |motion| { try motion(object.context, object, time, id, x, y); } }, // frame 3 => { if (WL_TOUCH.frame) |frame| { try frame( object.context, object, ); } }, // cancel 4 => { if (WL_TOUCH.cancel) |cancel| { try cancel( object.context, object, ); } }, // shape 5 => { var id: i32 = try object.context.next_i32(); var major: f32 = try object.context.next_fixed(); var minor: f32 = try object.context.next_fixed(); if (WL_TOUCH.shape) |shape| { try shape(object.context, object, id, major, minor); } }, // orientation 6 => { var id: i32 = try object.context.next_i32(); var orientation: f32 = try object.context.next_fixed(); if (WL_TOUCH.orientation) |orientation| { try orientation(object.context, object, id, orientation); } }, else => {}, } } pub fn wl_touch_send_release(object: Object) anyerror!void { object.context.startWrite(); object.context.finishWrite(object.id, 0); } // wl_output pub const wl_output_interface = struct { // compositor output region geometry: ?fn (*Context, Object, i32, i32, i32, i32, i32, []u8, []u8, i32) anyerror!void, mode: ?fn (*Context, Object, u32, i32, i32, i32) anyerror!void, done: ?fn ( *Context, Object, ) anyerror!void, scale: ?fn (*Context, Object, i32) anyerror!void, }; fn wl_output_geometry_default(context: *Context, object: Object, x: i32, y: i32, physical_width: i32, physical_height: i32, subpixel: i32, make: []u8, model: []u8, transform: i32) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_output_mode_default(context: *Context, object: Object, flags: u32, width: i32, height: i32, refresh: i32) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_output_done_default(context: *Context, object: Object) anyerror!void { return error.DebugFunctionNotImplemented; } fn wl_output_scale_default(context: *Context, object: Object, factor: i32) anyerror!void { return error.DebugFunctionNotImplemented; } pub var WL_OUTPUT = wl_output_interface{ .geometry = wl_output_geometry_default, .mode = wl_output_mode_default, .done = wl_output_done_default, .scale = wl_output_scale_default, }; pub fn new_wl_output(id: u32, context: *Context, container: usize) Object { return Object{ .id = id, .dispatch = wl_output_dispatch, .context = context, .version = 0, .container = container, }; } fn wl_output_dispatch(object: Object, opcode: u16) anyerror!void { switch (opcode) { // geometry 0 => { var x: i32 = try object.context.next_i32(); var y: i32 = try object.context.next_i32(); var physical_width: i32 = try object.context.next_i32(); var physical_height: i32 = try object.context.next_i32(); var subpixel: i32 = try object.context.next_i32(); var make: []u8 = try object.context.next_string(); var model: []u8 = try object.context.next_string(); var transform: i32 = try object.context.next_i32(); if (WL_OUTPUT.geometry) |geometry| { try geometry(object.context, object, x, y, physical_width, physical_height, subpixel, make, model, transform); } }, // mode 1 => { var flags: u32 = try object.context.next_u32(); var width: i32 = try object.context.next_i32(); var height: i32 = try object.context.next_i32(); var refresh: i32 = try object.context.next_i32(); if (WL_OUTPUT.mode) |mode| { try mode(object.context, object, flags, width, height, refresh); } }, // done 2 => { if (WL_OUTPUT.done) |done| { try done( object.context, object, ); } }, // scale 3 => { var factor: i32 = try object.context.next_i32(); if (WL_OUTPUT.scale) |scale| { try scale(object.context, object, factor); } }, else => {}, } } pub const wl_output_subpixel = enum(u32) { unknown = 0, none = 1, horizontal_rgb = 2, horizontal_bgr = 3, vertical_rgb = 4, vertical_bgr = 5, }; pub const wl_output_transform = enum(u32) { normal = 0, @"90" = 1, @"180" = 2, @"270" = 3, flipped = 4, flipped_90 = 5, flipped_180 = 6, flipped_270 = 7, }; pub const wl_output_mode = enum(u32) { current = 0x1, preferred = 0x2, }; // // Using this request a client can tell the server that it is not going to // use the output object anymore. // pub fn wl_output_send_release(object: Object) anyerror!void { object.context.startWrite(); object.context.finishWrite(object.id, 0); } // wl_region pub const wl_region_interface = struct { // region interface }; pub var WL_REGION = wl_region_interface{}; pub fn new_wl_region(id: u32, context: *Context, container: usize) Object { return Object{ .id = id, .dispatch = wl_region_dispatch, .context = context, .version = 0, .container = container, }; } fn wl_region_dispatch(object: Object, opcode: u16) anyerror!void { switch (opcode) { else => {}, } } // // Destroy the region. This will invalidate the object ID. // pub fn wl_region_send_destroy(object: Object) anyerror!void { object.context.startWrite(); object.context.finishWrite(object.id, 0); } // // Add the specified rectangle to the region. // pub fn wl_region_send_add(object: Object, x: i32, y: i32, width: i32, height: i32) anyerror!void { object.context.startWrite(); object.context.putI32(x); object.context.putI32(y); object.context.putI32(width); object.context.putI32(height); object.context.finishWrite(object.id, 1); } // // Subtract the specified rectangle from the region. // pub fn wl_region_send_subtract(object: Object, x: i32, y: i32, width: i32, height: i32) anyerror!void { object.context.startWrite(); object.context.putI32(x); object.context.putI32(y); object.context.putI32(width); object.context.putI32(height); object.context.finishWrite(object.id, 2); } // wl_subcompositor pub const wl_subcompositor_interface = struct { // sub-surface compositing }; pub var WL_SUBCOMPOSITOR = wl_subcompositor_interface{}; pub fn new_wl_subcompositor(id: u32, context: *Context, container: usize) Object { return Object{ .id = id, .dispatch = wl_subcompositor_dispatch, .context = context, .version = 0, .container = container, }; } fn wl_subcompositor_dispatch(object: Object, opcode: u16) anyerror!void { switch (opcode) { else => {}, } } pub const wl_subcompositor_error = enum(u32) { bad_surface = 0, }; // // Informs the server that the client will not be using this // protocol object anymore. This does not affect any other // objects, wl_subsurface objects included. // pub fn wl_subcompositor_send_destroy(object: Object) anyerror!void { object.context.startWrite(); object.context.finishWrite(object.id, 0); } // // Create a sub-surface interface for the given surface, and // associate it with the given parent surface. This turns a // plain wl_surface into a sub-surface. // // The to-be sub-surface must not already have another role, and it // must not have an existing wl_subsurface object. Otherwise a protocol // error is raised. // // Adding sub-surfaces to a parent is a double-buffered operation on the // parent (see wl_surface.commit). The effect of adding a sub-surface // becomes visible on the next time the state of the parent surface is // applied. // // This request modifies the behaviour of wl_surface.commit request on // the sub-surface, see the documentation on wl_subsurface interface. // pub fn wl_subcompositor_send_get_subsurface(object: Object, id: u32, surface: u32, parent: u32) anyerror!void { object.context.startWrite(); object.context.putU32(id); object.context.putU32(surface); object.context.putU32(parent); object.context.finishWrite(object.id, 1); } // wl_subsurface pub const wl_subsurface_interface = struct { // sub-surface interface to a wl_surface }; pub var WL_SUBSURFACE = wl_subsurface_interface{}; pub fn new_wl_subsurface(id: u32, context: *Context, container: usize) Object { return Object{ .id = id, .dispatch = wl_subsurface_dispatch, .context = context, .version = 0, .container = container, }; } fn wl_subsurface_dispatch(object: Object, opcode: u16) anyerror!void { switch (opcode) { else => {}, } } pub const wl_subsurface_error = enum(u32) { bad_surface = 0, }; // // The sub-surface interface is removed from the wl_surface object // that was turned into a sub-surface with a // wl_subcompositor.get_subsurface request. The wl_surface's association // to the parent is deleted, and the wl_surface loses its role as // a sub-surface. The wl_surface is unmapped immediately. // pub fn wl_subsurface_send_destroy(object: Object) anyerror!void { object.context.startWrite(); object.context.finishWrite(object.id, 0); } // // This schedules a sub-surface position change. // The sub-surface will be moved so that its origin (top left // corner pixel) will be at the location x, y of the parent surface // coordinate system. The coordinates are not restricted to the parent // surface area. Negative values are allowed. // // The scheduled coordinates will take effect whenever the state of the // parent surface is applied. When this happens depends on whether the // parent surface is in synchronized mode or not. See // wl_subsurface.set_sync and wl_subsurface.set_desync for details. // // If more than one set_position request is invoked by the client before // the commit of the parent surface, the position of a new request always // replaces the scheduled position from any previous request. // // The initial position is 0, 0. // pub fn wl_subsurface_send_set_position(object: Object, x: i32, y: i32) anyerror!void { object.context.startWrite(); object.context.putI32(x); object.context.putI32(y); object.context.finishWrite(object.id, 1); } // // This sub-surface is taken from the stack, and put back just // above the reference surface, changing the z-order of the sub-surfaces. // The reference surface must be one of the sibling surfaces, or the // parent surface. Using any other surface, including this sub-surface, // will cause a protocol error. // // The z-order is double-buffered. Requests are handled in order and // applied immediately to a pending state. The final pending state is // copied to the active state the next time the state of the parent // surface is applied. When this happens depends on whether the parent // surface is in synchronized mode or not. See wl_subsurface.set_sync and // wl_subsurface.set_desync for details. // // A new sub-surface is initially added as the top-most in the stack // of its siblings and parent. // pub fn wl_subsurface_send_place_above(object: Object, sibling: u32) anyerror!void { object.context.startWrite(); object.context.putU32(sibling); object.context.finishWrite(object.id, 2); } // // The sub-surface is placed just below the reference surface. // See wl_subsurface.place_above. // pub fn wl_subsurface_send_place_below(object: Object, sibling: u32) anyerror!void { object.context.startWrite(); object.context.putU32(sibling); object.context.finishWrite(object.id, 3); } // // Change the commit behaviour of the sub-surface to synchronized // mode, also described as the parent dependent mode. // // In synchronized mode, wl_surface.commit on a sub-surface will // accumulate the committed state in a cache, but the state will // not be applied and hence will not change the compositor output. // The cached state is applied to the sub-surface immediately after // the parent surface's state is applied. This ensures atomic // updates of the parent and all its synchronized sub-surfaces. // Applying the cached state will invalidate the cache, so further // parent surface commits do not (re-)apply old state. // // See wl_subsurface for the recursive effect of this mode. // pub fn wl_subsurface_send_set_sync(object: Object) anyerror!void { object.context.startWrite(); object.context.finishWrite(object.id, 4); } // // Change the commit behaviour of the sub-surface to desynchronized // mode, also described as independent or freely running mode. // // In desynchronized mode, wl_surface.commit on a sub-surface will // apply the pending state directly, without caching, as happens // normally with a wl_surface. Calling wl_surface.commit on the // parent surface has no effect on the sub-surface's wl_surface // state. This mode allows a sub-surface to be updated on its own. // // If cached state exists when wl_surface.commit is called in // desynchronized mode, the pending state is added to the cached // state, and applied as a whole. This invalidates the cache. // // Note: even if a sub-surface is set to desynchronized, a parent // sub-surface may override it to behave as synchronized. For details, // see wl_subsurface. // // If a surface's parent surface behaves as desynchronized, then // the cached state is applied on set_desync. // pub fn wl_subsurface_send_set_desync(object: Object) anyerror!void { object.context.startWrite(); object.context.finishWrite(object.id, 5); } // fw_control pub const fw_control_interface = struct { // protocol for querying and controlling foxwhale client: ?fn (*Context, Object, u32) anyerror!void, window: ?fn (*Context, Object, u32, i32, u32, u32, i32, i32, i32, i32, i32, i32, i32, i32, u32) anyerror!void, toplevel_window: ?fn (*Context, Object, u32, i32, u32, u32, i32, i32, i32, i32, u32) anyerror!void, region_rect: ?fn (*Context, Object, u32, i32, i32, i32, i32, i32) anyerror!void, done: ?fn ( *Context, Object, ) anyerror!void, }; fn fw_control_client_default(context: *Context, object: Object, index: u32) anyerror!void { return error.DebugFunctionNotImplemented; } fn fw_control_window_default(context: *Context, object: Object, index: u32, parent: i32, wl_surface_id: u32, surface_type: u32, x: i32, y: i32, width: i32, height: i32, sibling_prev: i32, sibling_next: i32, children_prev: i32, children_next: i32, input_region_id: u32) anyerror!void { return error.DebugFunctionNotImplemented; } fn fw_control_toplevel_window_default(context: *Context, object: Object, index: u32, parent: i32, wl_surface_id: u32, surface_type: u32, x: i32, y: i32, width: i32, height: i32, input_region_id: u32) anyerror!void { return error.DebugFunctionNotImplemented; } fn fw_control_region_rect_default(context: *Context, object: Object, index: u32, x: i32, y: i32, width: i32, height: i32, op: i32) anyerror!void { return error.DebugFunctionNotImplemented; } fn fw_control_done_default(context: *Context, object: Object) anyerror!void { return error.DebugFunctionNotImplemented; } pub var FW_CONTROL = fw_control_interface{ .client = fw_control_client_default, .window = fw_control_window_default, .toplevel_window = fw_control_toplevel_window_default, .region_rect = fw_control_region_rect_default, .done = fw_control_done_default, }; pub fn new_fw_control(id: u32, context: *Context, container: usize) Object { return Object{ .id = id, .dispatch = fw_control_dispatch, .context = context, .version = 0, .container = container, }; } fn fw_control_dispatch(object: Object, opcode: u16) anyerror!void { switch (opcode) { // client 0 => { var index: u32 = try object.context.next_u32(); if (FW_CONTROL.client) |client| { try client(object.context, object, index); } }, // window 1 => { var index: u32 = try object.context.next_u32(); var parent: i32 = try object.context.next_i32(); var wl_surface_id: u32 = try object.context.next_u32(); var surface_type: u32 = try object.context.next_u32(); var x: i32 = try object.context.next_i32(); var y: i32 = try object.context.next_i32(); var width: i32 = try object.context.next_i32(); var height: i32 = try object.context.next_i32(); var sibling_prev: i32 = try object.context.next_i32(); var sibling_next: i32 = try object.context.next_i32(); var children_prev: i32 = try object.context.next_i32(); var children_next: i32 = try object.context.next_i32(); var input_region_id: u32 = try object.context.next_u32(); if (FW_CONTROL.window) |window| { try window(object.context, object, index, parent, wl_surface_id, surface_type, x, y, width, height, sibling_prev, sibling_next, children_prev, children_next, input_region_id); } }, // toplevel_window 2 => { var index: u32 = try object.context.next_u32(); var parent: i32 = try object.context.next_i32(); var wl_surface_id: u32 = try object.context.next_u32(); var surface_type: u32 = try object.context.next_u32(); var x: i32 = try object.context.next_i32(); var y: i32 = try object.context.next_i32(); var width: i32 = try object.context.next_i32(); var height: i32 = try object.context.next_i32(); var input_region_id: u32 = try object.context.next_u32(); if (FW_CONTROL.toplevel_window) |toplevel_window| { try toplevel_window(object.context, object, index, parent, wl_surface_id, surface_type, x, y, width, height, input_region_id); } }, // region_rect 3 => { var index: u32 = try object.context.next_u32(); var x: i32 = try object.context.next_i32(); var y: i32 = try object.context.next_i32(); var width: i32 = try object.context.next_i32(); var height: i32 = try object.context.next_i32(); var op: i32 = try object.context.next_i32(); if (FW_CONTROL.region_rect) |region_rect| { try region_rect(object.context, object, index, x, y, width, height, op); } }, // done 4 => { if (FW_CONTROL.done) |done| { try done( object.context, object, ); } }, else => {}, } } pub const fw_control_surface_type = enum(u32) { wl_surface = 0, wl_subsurface = 1, xdg_toplevel = 2, xdg_popup = 3, }; // // Gets metadata about all the clients currently connected to foxwhale. // pub fn fw_control_send_get_clients(object: Object) anyerror!void { object.context.startWrite(); object.context.finishWrite(object.id, 0); } // // Gets metadata about all the windows currently connected to foxwhale. // pub fn fw_control_send_get_windows(object: Object) anyerror!void { object.context.startWrite(); object.context.finishWrite(object.id, 1); } // // Gets metadata about all the windows currently connected to foxwhale. // pub fn fw_control_send_get_window_trees(object: Object) anyerror!void { object.context.startWrite(); object.context.finishWrite(object.id, 2); } // // Cleans up fw_control object. // pub fn fw_control_send_destroy(object: Object) anyerror!void { object.context.startWrite(); object.context.finishWrite(object.id, 3); }
src/foxwhalectl/protocols.zig
const std = @import("std"); const debug = std.debug; const assert = debug.assert; const testing = std.testing; const log = std.log; const mem = std.mem; const Allocator = mem.Allocator; const maxInt = std.math.maxInt; const BufMap = std.BufMap; pub const DotEnv = struct { const Self = @This(); const Error = error{ InvalidVariableName, SyntaxError, DanglingEscape, QuoteNotClosed, } || Allocator.Error || std.os.WriteError; arena: std.heap.ArenaAllocator, map: BufMap, pub fn init(allocator: Allocator) Self { return .{ .arena = std.heap.ArenaAllocator.init(allocator), .map = BufMap.init(allocator), }; } pub fn deinit(self: *Self) void { self.map.deinit(); self.arena.deinit(); } pub fn parse(self: *Self, str: []const u8) !void { var start: usize = 0; var key: ?[]const u8 = null; var state: enum { SkipWhitespace, Key, ValueBegin, Value, Comment, Equals, SingleQuote, DoubleQuote, } = .SkipWhitespace; for (str) |c, i| { switch (state) { .SkipWhitespace => switch (c) { 0x09, 0x0A, 0x0D, 0x20 => { // whitespace: tab, newline, carriage return, space }, '#' => { state = .Comment; }, 'a'...'z', 'A'...'Z', '_' => { state = .Key; start = i; }, else => { return error.SyntaxError; }, }, .Comment => switch (c) { '\n' => state = .SkipWhitespace, else => {}, }, .Key => switch (c) { 'a'...'z', 'A'...'Z', '_', '0'...'9' => {}, ' ', '\t' => { key = str[start..i]; state = .Equals; }, '=' => { key = str[start..i]; state = .ValueBegin; }, else => { return error.InvalidVariableName; }, }, .Equals => switch (c) { ' ', '\t' => {}, '=' => { state = .ValueBegin; }, else => { return error.SyntaxError; }, }, .SingleQuote => switch (c) { '\'' => { try self.map.put(key.?, str[start..i]); state = .SkipWhitespace; }, else => {}, }, .DoubleQuote => switch (c) { '"' => { try self.map.put(key.?, str[start..i]); state = .SkipWhitespace; }, else => {}, }, .ValueBegin => switch (c) { ' ', '\t' => {}, '\'' => { state = .SingleQuote; start = i + 1; }, '"' => { state = .DoubleQuote; start = i + 1; }, else => { state = .Value; start = i; }, }, .Value => switch (c) { 0x09, 0x0A, 0x0D, 0x20 => { // whitespace: tab, newline, carriage return, space try self.map.put(key.?, str[start..i]); state = .SkipWhitespace; }, else => {}, }, } } switch (state) { .Comment, .SkipWhitespace => return, .Value => { try self.map.put(key.?, str[start..]); return; }, .Key, .Equals, .ValueBegin, => return Error.SyntaxError, .SingleQuote, .DoubleQuote => return Error.QuoteNotClosed, } } }; fn testDotEnvOk(str: []const u8, expect: BufMap) !void { var allocator = testing.allocator; var dotenvkv = DotEnv.init(allocator, str); defer dotenvkv.deinit(); var actual = try dotenvkv.parse(); var iter = expect.iterator(); while (iter.next()) |entry| { try testing.expectEqualStrings(entry.value_ptr.*, actual.get(entry.key_ptr.*).?); actual.remove(entry.key_ptr.*); } try testing.expect(0 == actual.count()); } test "DotEnv" { var expected = BufMap.init(testing.allocator); defer expected.deinit(); try expected.put("A", "B"); try testDotEnvOk("A=B\n", expected); try testDotEnvOk("A=B\r\n", expected); try testDotEnvOk(" A = B ", expected); try testDotEnvOk("A=B", expected); try expected.put("A", "42"); try testDotEnvOk("A=42\n", expected); try testDotEnvOk("A=42\r\n", expected); try testDotEnvOk(" A = 42 ", expected); try testDotEnvOk("\tA\t=\t42\t", expected); expected.remove("A"); try expected.put("B", "quoted string"); try expected.put("C", "single quoted string"); try testDotEnvOk("B=\"quoted string\"\nC=\'single quoted string\'", expected); }
src/dotenv.zig
const std = @import("std"); const c = @import("c.zig"); const File = std.fs.File; pub fn main() anyerror!void { std.debug.warn("starting zixel\n", .{}); if (c.glfwInit() == c.GLFW_FALSE) { std.debug.warn("failed to initialize glfw\n", .{}); return; } 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); var window = c.glfwCreateWindow(800, 600, "Hello zig", null, null); if (window == null) { std.debug.warn("failed to create glfw window\n", .{}); return; } // Make the window's context current c.glfwMakeContextCurrent(window); _ = c.glfwSetFramebufferSizeCallback(window, framebufferSizeCallback); // Now, glad can be initialized. if (c.gladLoadGLLoader(@ptrCast(c.GLADloadproc, c.glfwGetProcAddress)) == 0) { std.debug.warn("unable to init glad\n", .{}); return; } // build and compile our shader program // ------------------------------------ var vertexShader = try compileShader("shaders/vertex.glsl", c.GL_VERTEX_SHADER); var fragmentShader = try compileShader("shaders/fragment.glsl", c.GL_FRAGMENT_SHADER); const shaderProgram = try linkShaders(vertexShader, fragmentShader); // vertex data var vertices: [9]c.GLfloat = .{ -0.5, -0.5, 0.0, // left 0.5, -0.5, 0.0, // right 0.0, 0.5, 0.0, // top }; var VBO: c_uint = 0; var VAO: c_uint = 0; c.glGenVertexArrays(1, &VAO); c.glGenBuffers(1, &VBO); // bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s). c.glBindVertexArray(VAO); c.glBindBuffer(c.GL_ARRAY_BUFFER, VBO); c.glBufferData(c.GL_ARRAY_BUFFER, 9 * @sizeOf(c.GLfloat), &vertices, c.GL_STATIC_DRAW); c.glVertexAttribPointer(0, 3, c.GL_FLOAT, c.GL_FALSE, 3 * @sizeOf(f32), null); c.glEnableVertexAttribArray(0); // note that this is allowed, the call to c.glVertexAttribPointer registered VBO as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind c.glBindBuffer(c.GL_ARRAY_BUFFER, 0); // You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other // VAOs requires a call to c.glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary. c.glBindVertexArray(0); std.debug.warn("VBO: {} VAO: {}\n", .{ VBO, VAO }); // Loop until the user closes the window while (c.glfwWindowShouldClose(window) == 0) { processInput(window); // Clear then render c.glClearColor(0.2, 0.3, 0.3, 1.0); c.glClear(c.GL_COLOR_BUFFER_BIT); // draw our first triangle c.glBindVertexArray(VAO); // seeing as we only have a single VAO there's no need to bind it every time, but we'll do so to keep things a bit more organized c.glUseProgram(shaderProgram); c.glDrawArrays(c.GL_TRIANGLES, 0, 3); // swap the buffers c.glfwSwapBuffers(window); // Poll for and process events c.glfwPollEvents(); } c.glDeleteVertexArrays(1, &VAO); c.glDeleteBuffers(1, &VBO); c.glDeleteProgram(shaderProgram); } fn framebufferSizeCallback(window: ?*c.GLFWwindow, width: c_int, height: c_int) callconv(.C) void { c.glViewport(0, 0, width, height); } fn processInput(window: ?*c.GLFWwindow) callconv(.C) void { if (c.glfwGetKey(window, c.GLFW_KEY_ESCAPE) == c.GLFW_PRESS) c.glfwSetWindowShouldClose(window, c.GL_TRUE); } fn compileShader(file: []const u8, shader_type: c_uint) !c.GLuint { std.debug.warn("shader loading file: {}\n", .{file}); const source = try std.fs.cwd().readFileAllocOptions(std.heap.c_allocator, file, 1000000, @alignOf(u8), 0); defer std.heap.c_allocator.free(source); var shader = c.glCreateShader(shader_type); c.glShaderSource(shader, 1, &(&source[0]), null); c.glCompileShader(shader); // check for shader compile errors var success: c.GLint = 0; var infoLog = [_]u8{0} ** 512; c.glGetShaderiv(shader, c.GL_COMPILE_STATUS, &success); if (success == 0) { c.glGetShaderInfoLog(shader, 512, null, &infoLog); std.debug.warn("error compiling shader: {}\n", .{infoLog}); return error.ShaderCompilerError; } return shader; } fn linkShaders(vertexShader: c.GLuint, fragmentShader: c.GLuint) !c.GLuint { std.debug.warn("linking shader program\n", .{}); // link shaders var program = c.glCreateProgram(); c.glAttachShader(program, vertexShader); c.glAttachShader(program, fragmentShader); c.glLinkProgram(program); // check for linking errors var success: c.GLint = 0; var infoLog = [_]u8{0} ** 512; c.glGetProgramiv(program, c.GL_LINK_STATUS, &success); if (success == 0) { c.glGetProgramInfoLog(program, 512, null, &infoLog); std.debug.warn("error linking shader program: {}\n", .{infoLog}); return error.ShaderLinkerError; } c.glDeleteShader(vertexShader); c.glDeleteShader(fragmentShader); return program; }
src/main.zig
const std = @import("std"); const util = @import("util.zig"); const Board = struct { grid: [5][5]u64, marked: [5][5]bool, done: bool, const Self = @This(); fn init() Self { return .{ .grid = undefined, .marked = std.mem.zeroes([5][5]bool), .done = false }; } fn mark(self: *Self, call: u64) ?u64 { for (self.grid) |row, y| { for (row) |cell, x| { if (cell == call) { self.marked[y][x] = true; if (self.row_marked(y) or self.col_marked(x)) { self.done = true; return self.unmarked_sum(); } } } } return null; } fn row_marked(self: *const Self, row: usize) bool { var x: usize = 0; var marked: bool = true; while (x < 5) : (x += 1) { marked = marked and self.marked[row][x]; } return marked; } fn col_marked(self: *const Self, col: usize) bool { var y: usize = 0; var marked: bool = true; while (y < 5) : (y += 1) { marked = marked and self.marked[y][col]; } return marked; } fn unmarked_sum(self: *const Self) u64 { var sum: u64 = 0; for (self.marked) |row, y| { for (row) |cell, x| { if (!cell) { sum += self.grid[y][x]; } } } return sum; } }; pub fn part1(input: []const u8) !u64 { var inp = std.mem.trimRight(u8, input, "\n"); var lines = std.mem.split(u8, inp, "\n"); var calls = std.mem.tokenize(u8, lines.next().?, ","); var boards = std.ArrayList(Board).init(std.heap.page_allocator); defer boards.deinit(); while (lines.next()) |_| { var board = Board.init(); var y: usize = 0; while (y < 5) : (y += 1) { const row = lines.next().?; var cols = std.mem.tokenize(u8, row, " "); var x: usize = 0; while (x < 5) : (x += 1) { board.grid[y][x] = util.parseInt(u64, cols.next().?); } } try boards.append(board); } while (calls.next()) |call| { const call_num = util.parseInt(u64, call); for (boards.items) |*board| { if (board.mark(call_num)) |sum| { return sum * call_num; } } } unreachable; } pub fn part2(input: []const u8) !u64 { var inp = std.mem.trimRight(u8, input, "\n"); var lines = std.mem.split(u8, inp, "\n"); var calls = std.mem.tokenize(u8, lines.next().?, ","); var boards = std.ArrayList(Board).init(std.heap.page_allocator); defer boards.deinit(); while (lines.next()) |_| { var board = Board.init(); var y: usize = 0; while (y < 5) : (y += 1) { const row = lines.next().?; var cols = std.mem.tokenize(u8, row, " "); var x: usize = 0; while (x < 5) : (x += 1) { board.grid[y][x] = util.parseInt(u64, cols.next().?); } } try boards.append(board); } while (calls.next()) |call| { const call_num = util.parseInt(u64, call); var boards_left: usize = 0; var last_board_sum: ?u64 = null; for (boards.items) |*board| { if (board.done) continue; boards_left += 1; if (board.mark(call_num)) |sum| { last_board_sum = sum; } } if (boards_left == 1) { if (last_board_sum) |sum| { return sum * call_num; } } } unreachable; } test "day 4 part 1" { const test_input = \\7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1 \\ \\22 13 17 11 0 \\ 8 2 23 4 24 \\21 9 14 16 7 \\ 6 10 3 18 5 \\ 1 12 20 15 19 \\ \\ 3 15 0 2 22 \\ 9 18 13 17 5 \\19 8 7 25 23 \\20 11 10 24 4 \\14 21 16 12 6 \\ \\14 21 17 24 4 \\10 16 15 9 19 \\18 8 23 26 20 \\22 11 13 6 5 \\ 2 0 12 3 7 ; try std.testing.expectEqual(part1(test_input), 4512); } test "day 4 part 2" { const test_input = \\7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1 \\ \\22 13 17 11 0 \\ 8 2 23 4 24 \\21 9 14 16 7 \\ 6 10 3 18 5 \\ 1 12 20 15 19 \\ \\ 3 15 0 2 22 \\ 9 18 13 17 5 \\19 8 7 25 23 \\20 11 10 24 4 \\14 21 16 12 6 \\ \\14 21 17 24 4 \\10 16 15 9 19 \\18 8 23 26 20 \\22 11 13 6 5 \\ 2 0 12 3 7 ; try std.testing.expectEqual(part2(test_input), 1924); }
zig/src/day4.zig
const io = @import("io.zig"); const PortIO = io.PortIO; const Serial = io.Serial; const utils = @import("utils.zig"); const Paging = utils.Paging; const interrupts = @import("interrupts.zig"); const InterruptContext = interrupts.InterruptContext; const InterruptError = interrupts.InterruptError; const PIC = @import("pic.zig"); const INTERRUPT_PAGEFAULT = 0x0e; const INTERRUPT_KEYBOARD = 0x21; const INTERRUPT_SERIAL0 = 0x23; const INTERRUPT_SERIAL1 = 0x24; const INTERRUPT_USER = 0x80; extern var serialboot_mode: bool; extern var ataboot_mode: bool; pub fn init() void { interrupts.add(INTERRUPT_PAGEFAULT, isrPagefault); interrupts.add(INTERRUPT_KEYBOARD, isrKeyboard); interrupts.add(INTERRUPT_SERIAL0, isrSerial); interrupts.add(INTERRUPT_SERIAL1, isrSerial); interrupts.add(INTERRUPT_USER, isrUser); } fn isrUser(ctx: *InterruptContext) InterruptError!void { const out = Serial.writer(); switch (ctx.regs.eax) { 1 => { const status = ctx.regs.ebx; try out.print("[user] sys_exit: status {0} (0x{0x})\n", .{ status, }); ctx.regs.eax = status; }, 4 => { const fd = ctx.regs.ebx; const len = ctx.regs.edx; const msg = @intToPtr([*]const u8, ctx.regs.ecx); try out.print("[user] sys_write[{}]: {s}\n", .{ fd, msg[0..len], }); ctx.regs.eax = len; }, else => { try out.print("[user] unsupported interrupt 0x{x}\n", .{ ctx.regs.eax, }); }, } } fn isrKeyboard(ctx: *InterruptContext) InterruptError!void { const tc = @import("term_color.zig"); const out = Serial.writer(); const KBD_COMMAND = 0x64; const KBD_DATA = 0x60; const status = PortIO.in(u8, KBD_COMMAND); const scancode = if (status & 1 !=0) PortIO.in(u8, KBD_DATA) else null; try out.print(tc.WHITE, .{}); if (scancode) |_| { try out.print("Keyboard status: 0x{x:0>2}, ", .{status}); try out.print("scancode: 0x{x:0>2} ", .{scancode.?}); } else { try out.print("Keyboard status: 0x{x:0>2}", .{status}); } try out.print("\n" ++ tc.RESET, .{}); if (scancode) |_| { switch (scancode.?) { // '1' - serialboot request 0x82 => serialboot_mode = true, // '2' - ataboot request 0x83 => ataboot_mode = true, else => {}, } } // Send EOI PIC.eoi(.master); } fn isrSerial(ctx: *InterruptContext) InterruptError!void { const out = Serial.writer(); const port = switch (ctx.n) { INTERRUPT_SERIAL0 => blk: { const is_com2 = Serial.is_data_available(1) catch false; const is_com4 = Serial.is_data_available(3) catch false; if (is_com2) break :blk @as(usize, 1) else if (is_com4) break :blk @as(usize, 3) else @panic("serial_handler: IRQ#23 error"); }, INTERRUPT_SERIAL1 => blk: { const is_com1 = Serial.is_data_available(0) catch false; const is_com3 = Serial.is_data_available(2) catch false; if (is_com1) break :blk @as(usize, 0) else if (is_com3) break :blk @as(usize, 2) else @panic("serial_handler: IRQ#24 error"); }, else => @panic("serial_handler: IRQ error"), }; const data = Serial.read(port) catch unreachable; switch (data) { '1' => { try out.print("Serial port {}: serialboot request.\n", .{port}); serialboot_mode = true; }, '2' => { try out.print("Serial port {}: ataboot request.\n", .{port}); ataboot_mode = true; }, else => try out.print("Serial port {}: 0x{x:0>2}\n", .{port, data}), } // Send EOI PIC.eoi(.master); } fn isrPagefault(ctx: *InterruptContext) InterruptError!void { const out = Serial.writer(); const cr2 = Paging.readCR2(); try out.print("Pagefault at 0x{x:0>8}\n", .{cr2}); @panic("Pagefault!"); }
src/isr.zig
const std = @import("std"); pub const os = @import("../os.zig"); const stivale = @import("stivale_common.zig"); const paging = os.memory.paging; const vmm = os.memory.vmm; const platform = os.platform; const kmain = os.kernel.kmain; const mmio_serial = os.drivers.mmio_serial; const vesa_log = os.drivers.vesa_log; const vga_log = os.drivers.vga_log; const page_size = os.platform.paging.page_sizes[0]; const MemmapEntry = stivale.MemmapEntry; const arch = @import("builtin").arch; const stivale2_tag = packed struct { identifier: u64, next: ?*stivale2_tag, pub fn format(self: *const @This(), fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { try writer.print("Identifier: 0x{X:0>16}", .{self.identifier}); } }; const stivale2_info = packed struct { bootloader_brand: [64]u8, bootloader_version: [64]u8, tags: ?*stivale2_tag, }; const stivale2_memmap = packed struct { tag: stivale2_tag, entries: u64, pub fn get(self: *const @This()) []MemmapEntry { return @intToPtr([*]MemmapEntry, @ptrToInt(&self.entries) + 8)[0..self.entries]; } pub fn format(self: *const @This(), fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { try writer.print("{} entries:\n", .{self.entries}); for(self.get()) |ent| { try writer.print(" {}\n", .{ent}); } } }; const stivale2_commandline = packed struct { tag: stivale2_tag, commandline: [*:0]u8, pub fn format(self: *const @This(), fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { try writer.print("Commandline: {s}", .{self.commandline}); } }; const stivale2_framebuffer = packed struct { tag: stivale2_tag, addr: u64, width: u16, height: u16, pitch: u16, bpp: u16, pub fn format(self: *const @This(), fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { try writer.print("0x{X}, {}x{}, bpp={}, pitch={}", .{self.addr, self.width, self.height, self.bpp, self.pitch}); } }; const stivale2_rsdp = packed struct { tag: stivale2_tag, rsdp: u64, pub fn format(self: *const @This(), fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { try writer.print("0x{X}", .{self.rsdp}); } }; const stivale2_smp = packed struct { tag: stivale2_tag, flags: u64, bsp_lapic_id: u32, _: u32, entries: u64, pub fn format(self: *const @This(), fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { try writer.print("{} CPU(s): {}", .{self.entries, self.get()}); } pub fn get(self: *const @This()) []stivale2_smp_info { return @intToPtr([*]stivale2_smp_info, @ptrToInt(&self.entries) + 8)[0..self.entries]; } }; const stivale2_smp_info = extern struct { acpi_proc_uid: u32, lapic_id: u32, target_stack: u64, goto_address: u64, argument: u64, }; const stivale2_mmio32_uart = packed struct { tag: stivale2_tag, uart_addr: u64, pub fn format(self: *const @This(), fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { try writer.print("0x{X}", .{self.uart_addr}); } }; const stivale2_mmio32_status_uart = packed struct { tag: stivale2_tag, uart_addr: u64, uart_status: u64, status_mask: u32, status_value: u32, pub fn format(self: *const @This(), fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { try writer.print("0x{X}, 0x{X}, (val & 0x{X}) == 0x{X}", .{self.uart_addr, self.uart_status, self.status_mask, self.status_value}); } }; const stivale2_dtb = packed struct { tag: stivale2_tag, addr: [*]u8, size: u64, pub fn slice(self: *const @This()) []u8 { return self.addr[0..self.size]; } pub fn format(self: *const @This(), fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { try writer.print("0x{X} bytes at 0x{X}", .{self.size, @ptrToInt(self.addr)}); } }; const parsed_info = struct { memmap: ?*stivale2_memmap = null, framebuffer: ?stivale2_framebuffer = null, rsdp: ?u64 = null, smp: ?os.platform.phys_ptr(*stivale2_smp) = null, dtb: ?stivale2_dtb = null, uart: ?stivale2_mmio32_uart = null, uart_status: ?stivale2_mmio32_status_uart = null, pub fn valid(self: *const parsed_info) bool { if(self.memmap == null) return false; return true; } pub fn format(self: *const parsed_info, fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { try writer.print( \\Parsed stivale2 tags: \\ Memmap: {} \\ Framebuffer: {} \\ RSDP: {} \\ SMP: {} \\ DTB: {} \\ UART: {} \\ UART with status: {} \\ \\ , .{self.memmap, self.framebuffer, self.rsdp, self.smp, self.dtb, self.uart, self.uart_status}); } }; fn smp_entry(info_in: u64) callconv(.C) noreturn { const smp_info = os.platform.phys_ptr(*stivale2_smp_info).from_int(info_in); const core_id = smp_info.get_writeback().argument; const cpu = &os.platform.smp.cpus[core_id]; os.platform.thread.set_current_cpu(cpu); cpu.booted = true; platform.ap_init(); } export fn stivale2_main(info_in: *stivale2_info) noreturn { platform.platform_early_init(); os.log("Stivale2: Boot!\n", .{}); var info = parsed_info{}; var tag = info_in.tags; while(tag != null): (tag = tag.?.next) { switch(tag.?.identifier) { 0x2187f79e8612de07 => info.memmap = @ptrCast(*stivale2_memmap, tag), 0xe5e76a1b4597a781 => os.log("{s}\n", .{@ptrCast(*stivale2_commandline, tag)}), 0x506461d2950408fa => info.framebuffer = @ptrCast(*stivale2_framebuffer, tag).*, 0x9e1786930a375e78 => info.rsdp = @ptrCast(*stivale2_rsdp, tag).rsdp, 0x34d1d96339647025 => info.smp = os.platform.phys_ptr(*stivale2_smp).from_int(@ptrToInt(tag)), 0xabb29bd49a2833fa => info.dtb = @ptrCast(*stivale2_dtb, tag).*, 0xb813f9b8dbc78797 => info.uart = @ptrCast(*stivale2_mmio32_uart, tag).*, 0xf77485dbfeb260f9 => info.uart_status = @ptrCast(*stivale2_mmio32_status_uart, tag).*, else => { os.log("Unknown stivale2 tag identifier: 0x{X:0>16}\n", .{tag.?.identifier}); } } } stivale.detect_phys_base(); if(info.uart) |uart| { mmio_serial.register_mmio32_serial(uart.uart_addr); os.log("Stivale2: Registered UART\n", .{}); } if(info.uart_status) |u| { mmio_serial.register_mmio32_status_serial(u.uart_addr, u.uart_status, u.status_mask, u.status_value); os.log("Stivale2: Registered status UART\n", .{}); } os.memory.pmm.init(); os.log( \\Bootloader: {s} \\Bootloader version: {s} \\{} , .{info_in.bootloader_brand, info_in.bootloader_version, info} ); if(!info.valid()) { @panic("Stivale2: Info not valid!"); } if(info.dtb) |dtb| { os.vital(platform.devicetree.parse_dt(dtb.slice()), "parsing devicetree blob"); os.log("Stivale2: Parsed devicetree blob!\n", .{}); } for(info.memmap.?.get()) |*ent| { stivale.consume_physmem(ent); } const phys_high = stivale.phys_high(info.memmap.?.get()); var context = os.vital(paging.bootstrap_kernel_paging(), "bootstrapping kernel paging"); os.vital(os.memory.paging.map_physmem(.{ .context = &context, .map_limit = phys_high, }), "Mapping physmem"); os.memory.paging.kernel_context = context; platform.thread.bsp_task.paging_context = &os.memory.paging.kernel_context; context.apply(); os.log("Doing vmm\n", .{}); const heap_base = os.memory.paging.kernel_context.make_heap_base(); os.vital(vmm.init(heap_base), "initializing vmm"); os.log("Doing framebuffer\n", .{}); if(info.framebuffer) |fb| { vesa_log.register_fb(vesa_log.lfb_updater, fb.addr, fb.pitch, fb.width, fb.height, fb.bpp); } else { vga_log.register(); } os.log("Doing scheduler\n", .{}); os.thread.scheduler.init(&platform.thread.bsp_task); os.log("Doing SMP\n", .{}); if(info.smp) |smp| { const cpus = smp.get_writeback().get(); os.platform.smp.init(cpus.len); var bootstrap_stack_size = os.memory.paging.kernel_context.page_size(0, os.memory.pmm.phys_to_uncached_virt(0)); // Just a single page of stack isn't enough for debug mode :^( if(std.debug.runtime_safety) { bootstrap_stack_size *= 4; } // Allocate stacks for all CPUs var bootstrap_stack_pool_sz = bootstrap_stack_size * cpus.len; var stacks = os.vital(os.memory.pmm.alloc_phys(bootstrap_stack_pool_sz), "allocating ap stacks"); // Setup counter used for waiting @atomicStore(usize, &os.platform.smp.cpus_left, cpus.len - 1, .Release); // Initiate startup sequence for all cores in parallel for(cpus) |*cpu_info, i| { const cpu = &os.platform.smp.cpus[i]; cpu.acpi_id = cpu_info.acpi_proc_uid; if(i == 0) continue; cpu.booted = false; // Boot it! const stack = stacks + bootstrap_stack_size * i; cpu_info.argument = i; cpu_info.target_stack = os.memory.pmm.phys_to_write_back_virt(stack + bootstrap_stack_size - 16); @atomicStore(u64, &cpu_info.goto_address, @ptrToInt(smp_entry), .Release); } // Wait for the counter to become 0 while (@atomicLoad(usize, &os.platform.smp.cpus_left, .Acquire) != 0) { os.platform.spin_hint(); } // Free memory pool used for stacks. Unreachable for now os.memory.pmm.free_phys(stacks, bootstrap_stack_pool_sz); os.log("All cores are ready for tasks!\n", .{}); } if(info.rsdp) |rsdp| { os.log("Registering rsdp: 0x{X}!\n", .{rsdp}); platform.acpi.register_rsdp(rsdp); } os.vital(os.platform.platform_init(), "calling platform_init"); kmain(); }
src/boot/stivale2.zig
const std = @import("std"); const audiometa = @import("audiometa"); const AllMetadata = audiometa.metadata.AllMetadata; const MetadataEntry = audiometa.metadata.MetadataMap.Entry; const FullTextEntry = audiometa.id3v2_data.FullTextMap.Entry; const testing = std.testing; const fmtUtf8SliceEscapeUpper = audiometa.util.fmtUtf8SliceEscapeUpper; pub const log_level: std.log.Level = .debug; const induce_allocation_failures = true; fn parseExpectedMetadataImpl(allocator: std.mem.Allocator, stream_source: *std.io.StreamSource, expected_meta: ExpectedAllMetadata) !void { // need to reset the position of the stream so that this function can be called // multiple times (which happens when inducing allocation failures) try stream_source.seekTo(0); var meta = try audiometa.metadata.readAll(allocator, stream_source); defer meta.deinit(); compareAllMetadata(&expected_meta, &meta) catch |err| { std.debug.print("\nexpected:\n", .{}); expected_meta.dump(); std.debug.print("\nactual:\n", .{}); meta.dump(); return err; }; } fn parseExpectedMetadata(comptime path: []const u8, expected_meta: ExpectedAllMetadata) !void { std.log.debug("{s}\n", .{path}); const data = @embedFile(path); var stream_source = std.io.StreamSource{ .const_buffer = std.io.fixedBufferStream(data) }; if (induce_allocation_failures) { return testing.checkAllAllocationFailures(testing.allocator, parseExpectedMetadataImpl, .{ &stream_source, expected_meta }); } else { return parseExpectedMetadataImpl(testing.allocator, &stream_source, expected_meta); } } fn compareAllMetadata(all_expected: *const ExpectedAllMetadata, all_actual: *const AllMetadata) !void { try testing.expectEqual(all_expected.tags.len, all_actual.tags.len); for (all_expected.tags) |expected_tag, i| { const actual_tag = all_actual.tags[i]; try testing.expectEqual(std.meta.activeTag(expected_tag), std.meta.activeTag(actual_tag)); switch (expected_tag) { .id3v2 => { try testing.expectEqual(expected_tag.id3v2.major_version, actual_tag.id3v2.header.major_version); try compareEntrySlice(expected_tag.id3v2.user_defined, actual_tag.id3v2.user_defined.entries.items); try testing.expectEqual(expected_tag.id3v2.comments.len, actual_tag.id3v2.comments.entries.items.len); for (expected_tag.id3v2.comments) |expected_comment, comment_i| { const actual_comment = actual_tag.id3v2.comments.entries.items[comment_i]; try compareFullText(expected_comment, actual_comment); } try testing.expectEqual(expected_tag.id3v2.unsynchronized_lyrics.len, actual_tag.id3v2.unsynchronized_lyrics.entries.items.len); for (expected_tag.id3v2.unsynchronized_lyrics) |expected_lyrics, lyrics_i| { const actual_lyrics = actual_tag.id3v2.unsynchronized_lyrics.entries.items[lyrics_i]; try compareFullText(expected_lyrics, actual_lyrics); } }, .ape => { try testing.expectEqual(expected_tag.ape.version, actual_tag.ape.header_or_footer.version); }, else => {}, } try compareMetadata(expected_tag.getMetadata(), actual_tag.getMetadata()); } } fn compareEntrySlice(expected: []const MetadataEntry, actual: []const MetadataEntry) !void { try testing.expectEqual(expected.len, actual.len); expected_loop: for (expected) |field| { var found_matching_key = false; for (actual) |entry| { if (std.mem.eql(u8, field.name, entry.name)) { if (std.mem.eql(u8, field.value, entry.value)) { continue :expected_loop; } found_matching_key = true; } } std.debug.print("mismatched field: {s}\n", .{fmtUtf8SliceEscapeUpper(field.name)}); if (found_matching_key) { return error.FieldValuesDontMatch; } else { return error.MissingField; } } } fn compareFullText(expected: FullTextEntry, actual: FullTextEntry) !void { try testing.expectEqualStrings(expected.language, actual.language); try testing.expectEqualStrings(expected.description, actual.description); try testing.expectEqualStrings(expected.value, actual.value); } fn compareMetadata(expected: ExpectedMetadata, actual: audiometa.metadata.Metadata) !void { try compareEntrySlice(expected.map, actual.map.entries.items); try testing.expectEqual(expected.start_offset, actual.start_offset); try testing.expectEqual(expected.end_offset, actual.end_offset); } pub const ExpectedTypedMetadata = union(audiometa.metadata.MetadataType) { id3v1: ExpectedMetadata, id3v2: ExpectedID3v2Metadata, ape: ExpectedAPEMetadata, flac: ExpectedMetadata, vorbis: ExpectedMetadata, mp4: ExpectedMetadata, /// Convenience function to get the ExpectedMetadata for any TypedMetadata pub fn getMetadata(typed_meta: ExpectedTypedMetadata) ExpectedMetadata { return switch (typed_meta) { .id3v1, .flac, .vorbis, .mp4 => |val| val, .id3v2 => |val| val.metadata, .ape => |val| val.metadata, }; } }; const ExpectedAllMetadata = struct { tags: []const ExpectedTypedMetadata, pub fn dump(self: *const ExpectedAllMetadata) void { for (self.tags) |tag| { switch (tag) { .id3v1 => |*id3v1_meta| { std.debug.print("# ID3v1 0x{x}-0x{x}\n", .{ id3v1_meta.start_offset, id3v1_meta.end_offset }); id3v1_meta.dump(); }, .flac => |*flac_meta| { std.debug.print("# FLAC 0x{x}-0x{x}\n", .{ flac_meta.start_offset, flac_meta.end_offset }); flac_meta.dump(); }, .vorbis => |*vorbis_meta| { std.debug.print("# Vorbis 0x{x}-0x{x}\n", .{ vorbis_meta.start_offset, vorbis_meta.end_offset }); vorbis_meta.dump(); }, .id3v2 => |*id3v2_meta| { std.debug.print("# ID3v2 v2.{d} 0x{x}-0x{x}\n", .{ id3v2_meta.major_version, id3v2_meta.metadata.start_offset, id3v2_meta.metadata.end_offset }); id3v2_meta.metadata.dump(); }, .ape => |*ape_meta| { std.debug.print("# APEv{d} 0x{x}-0x{x}\n", .{ ape_meta.version, ape_meta.metadata.start_offset, ape_meta.metadata.end_offset }); ape_meta.metadata.dump(); }, .mp4 => |*mp4_meta| { std.debug.print("# MP4 0x{x}-0x{x}\n", .{ mp4_meta.start_offset, mp4_meta.end_offset }); mp4_meta.dump(); }, } } } }; const ExpectedID3v2Metadata = struct { metadata: ExpectedMetadata, user_defined: []const MetadataEntry = &[_]MetadataEntry{}, major_version: u8, comments: []const FullTextEntry = &[_]FullTextEntry{}, unsynchronized_lyrics: []const FullTextEntry = &[_]FullTextEntry{}, }; const ExpectedAPEMetadata = struct { version: u32, metadata: ExpectedMetadata, }; const ExpectedMetadata = struct { start_offset: usize, end_offset: usize, map: []const MetadataEntry, pub fn dump(metadata: *const ExpectedMetadata) void { for (metadata.map) |entry| { std.debug.print("{s}={s}\n", .{ fmtUtf8SliceEscapeUpper(entry.name), fmtUtf8SliceEscapeUpper(entry.value) }); } } }; test "standard id3v1" { try parseExpectedMetadata("data/id3v1.mp3", .{ .tags = &.{ .{ .id3v1 = .{ .start_offset = 0x0, .end_offset = 0x80, .map = &[_]MetadataEntry{ .{ .name = "title", .value = "Blind" }, .{ .name = "artist", .value = "Acme" }, .{ .name = "album", .value = "... to reduce the choir to one" }, .{ .name = "track", .value = "1" }, .{ .name = "genre", .value = "Blues" }, }, } }, } }); } test "empty (all zeros) id3v1" { try parseExpectedMetadata("data/id3v1_empty.mp3", .{ .tags = &.{ .{ .id3v1 = .{ .start_offset = 0x0, .end_offset = 0x80, .map = &[_]MetadataEntry{ .{ .name = "genre", .value = "Blues" }, }, } }, } }); } test "id3v1 with non-ASCII chars (latin1)" { try parseExpectedMetadata("data/id3v1_latin1_chars.mp3", .{ .tags = &.{ .{ .id3v1 = .{ .start_offset = 0x0, .end_offset = 0x80, .map = &[_]MetadataEntry{ .{ .name = "title", .value = "Introducción" }, .{ .name = "artist", .value = "3rdage Attack" }, .{ .name = "album", .value = "3rdage Attack" }, .{ .name = "date", .value = "2007" }, .{ .name = "track", .value = "1" }, }, } }, } }); } test "id3v2.3 with UTF-16" { try parseExpectedMetadata("data/id3v2.3.mp3", .{ .tags = &.{ .{ .id3v2 = .{ .major_version = 3, .metadata = .{ .start_offset = 0x0, .end_offset = 0x4604, .map = &[_]MetadataEntry{ .{ .name = "TPE2", .value = "Muga" }, .{ .name = "TIT2", .value = "死前解放 (Unleash Before Death)" }, .{ .name = "TALB", .value = "Muga" }, .{ .name = "TYER", .value = "2002" }, .{ .name = "TRCK", .value = "02/11" }, .{ .name = "TPOS", .value = "1/1" }, .{ .name = "TPE1", .value = "Muga" }, }, }, .user_defined = &[_]MetadataEntry{ .{ .name = "MEDIAFORMAT", .value = "CD" }, .{ .name = "PERFORMER", .value = "Muga" }, }, .comments = &.{.{ .language = "eng", .description = "", .value = "EAC V1.0 beta 2, Secure Mode, Test & Copy, AccurateRip, FLAC -8", }}, } }, .{ .id3v1 = .{ .start_offset = 0x4604, .end_offset = 0x4684, .map = &[_]MetadataEntry{ .{ .name = "title", .value = "???? (Unleash Before Death)" }, .{ .name = "artist", .value = "Muga" }, .{ .name = "album", .value = "Muga" }, .{ .name = "date", .value = "2002" }, .{ .name = "comment", .value = "EAC V1.0 beta 2, Secure Mode" }, .{ .name = "track", .value = "2" }, }, } }, } }); } test "id3v2.3 with UTF-16 big endian" { try parseExpectedMetadata("data/id3v2.3_utf16_be.mp3", .{ .tags = &.{ .{ .id3v2 = .{ .major_version = 3, .metadata = .{ .start_offset = 0x0, .end_offset = 0x120, .map = &[_]MetadataEntry{ .{ .name = "TSSE", .value = "LAME 32bits version 3.98 (http://www.mp3dev.org/)" }, .{ .name = "TIT2", .value = "No Island of Dreams" }, .{ .name = "TPE1", .value = "Conflict" }, .{ .name = "TALB", .value = "It's Time To See Who's Who Now" }, .{ .name = "TCON", .value = "Punk" }, .{ .name = "TRCK", .value = "2" }, .{ .name = "TYER", .value = "1985" }, .{ .name = "TLEN", .value = "168000" }, }, }, } }, } }); } test "id3v2.3 with user defined fields (TXXX)" { try parseExpectedMetadata("data/id3v2.3_user_defined_fields.mp3", .{ .tags = &.{ .{ .id3v2 = .{ .major_version = 3, .metadata = .{ .start_offset = 0x0, .end_offset = 0x937, .map = &[_]MetadataEntry{ .{ .name = "TLAN", .value = "eng" }, .{ .name = "TRCK", .value = "1/14" }, .{ .name = "TPE1", .value = "Acephalix" }, .{ .name = "TIT2", .value = "Immanent" }, .{ .name = "TYER", .value = "2010" }, .{ .name = "TDAT", .value = "0000" }, .{ .name = "TSSE", .value = "LAME 3.97 (-V2 --vbr-new)" }, .{ .name = "TCON", .value = "Hardcore" }, .{ .name = "TPUB", .value = "Prank Records" }, .{ .name = "TALB", .value = "Aporia" }, }, }, .user_defined = &[_]MetadataEntry{ .{ .name = "Catalog #", .value = "Prank 110" }, .{ .name = "Release type", .value = "Normal release" }, .{ .name = "Rip date", .value = "2010-09-20" }, .{ .name = "Source", .value = "CD" }, }, } }, } }); } test "id3v2.3 with full unsynch tag" { try parseExpectedMetadata("data/id3v2.3_unsynch_tag.mp3", .{ .tags = &.{ .{ .id3v2 = .{ .major_version = 3, .metadata = .{ .start_offset = 0x0, .end_offset = 0x11D3, .map = &[_]MetadataEntry{ .{ .name = "TIT2", .value = "Intro" }, .{ .name = "TPE1", .value = "Disgust" }, .{ .name = "TALB", .value = "Brutality of War" }, .{ .name = "TRCK", .value = "01/15" }, .{ .name = "TLEN", .value = "68173" }, .{ .name = "TCON", .value = "Other" }, .{ .name = "TENC", .value = "Exact Audio Copy (Secure mode)" }, .{ .name = "TSSE", .value = "flac.exe -V -8 -T \"artist=Disgust\" -T \"title=Intro\" -T \"album=Brutality of War\" -T \"date=\" -T \"tracknumber=01\" -T \"genre=Other\"" }, }, }, .comments = &.{.{ .language = "eng", .description = "", .value = "Track 1" }}, } }, } }); } test "id3v2.3 with id3v2.2 frame ids" { try parseExpectedMetadata("data/id3v2.3_with_id3v2.2_frame_ids.mp3", .{ .tags = &.{ .{ .id3v2 = .{ .major_version = 3, .metadata = .{ .start_offset = 0x0, .end_offset = 0x1154, .map = &[_]MetadataEntry{ .{ .name = "TENC", .value = "iTunes v7.6.1" }, .{ .name = "TIT2", .value = "Religion Is Fear" }, .{ .name = "TYER", .value = "2008" }, .{ .name = "TCON", .value = "Grindcore" }, .{ .name = "TALB", .value = "Trap Them & Extreme Noise Terror Split 7\"EP" }, .{ .name = "TRCK", .value = "1" }, .{ .name = "TPE1", .value = "Extreme Noise Terror" }, .{ .name = "TCP", .value = "1" }, }, }, .comments = &.{ .{ .language = "eng", .description = "", .value = "0", }, .{ .language = "eng", .description = "", .value = " 000028FD 00002EAF 000060E8 00008164 00005997 00005997 00008E2B 00008E97 000125C6 00011263", }, .{ .language = "eng", .description = "", .value = " 00000000 00000210 00000978 00000000003E6478 00000000 0021E72F 00000000 00000000 00000000 00000000 00000000 00000000", }, .{ .language = "eng", .description = "", .value = "www.deathwishinc.com", }, }, } }, } }); } test "id3v2.3 with text frame with zero size" { try parseExpectedMetadata("data/id3v2.3_text_frame_with_zero_size.mp3", .{ .tags = &.{ .{ .id3v2 = .{ .major_version = 3, .metadata = .{ .start_offset = 0x0, .end_offset = 0x183, .map = &[_]MetadataEntry{ .{ .name = "TCON", .value = "(129)Hardcore" }, .{ .name = "TRCK", .value = "1" }, .{ .name = "TYER", .value = "2004" }, .{ .name = "TALB", .value = "Italian Girls (The Best In The World)" }, .{ .name = "TPE1", .value = "A Taste For Murder" }, .{ .name = "TIT2", .value = "Rosario" }, .{ .name = "TENC", .value = "" }, .{ .name = "TCOP", .value = "" }, .{ .name = "TOPE", .value = "" }, .{ .name = "TCOM", .value = "" }, }, }, .comments = &.{.{ .language = "eng", .description = "", .value = " ", }}, } }, } }); } test "id3v2.2" { try parseExpectedMetadata("data/id3v2.2.mp3", .{ .tags = &.{ .{ .id3v2 = .{ .major_version = 2, .metadata = .{ .start_offset = 0x0, .end_offset = 0x86E, .map = &[_]MetadataEntry{ .{ .name = "TT2", .value = "side a" }, .{ .name = "TP1", .value = "a warm gun" }, .{ .name = "TAL", .value = "escape" }, .{ .name = "TRK", .value = "1" }, .{ .name = "TEN", .value = "iTunes 8.0.1.11" }, }, }, .comments = &.{ .{ .language = "eng", .description = "iTunPGAP", .value = "0", }, .{ .language = "eng", .description = "iTunNORM", .value = " 00000318 0000031C 00001032 00000A21 00014C8D 0001F4D0 00004B10 0000430B 0000E61A 00003A43", }, .{ .language = "eng", .description = "iTunSMPB", .value = " 00000000 00000210 00000726 00000000014408CA 00000000 0092E82A 00000000 00000000 00000000 00000000 00000000 00000000", }, }, } }, } }); } test "id3v2.4 utf16 frames with single u8 delimeters" { try parseExpectedMetadata("data/id3v2.4_utf16_single_u8_delimeter.mp3", .{ .tags = &.{ .{ .id3v2 = .{ .major_version = 4, .metadata = .{ .start_offset = 0x0, .end_offset = 0x980, .map = &[_]MetadataEntry{ .{ .name = "TDRC", .value = "2010" }, .{ .name = "TRCK", .value = "1/9" }, .{ .name = "TPOS", .value = "1/1" }, .{ .name = "TCOM", .value = "<NAME>" }, .{ .name = "TIT2", .value = "Starmaker" }, .{ .name = "TPE1", .value = "<NAME>" }, .{ .name = "TALB", .value = "Streams Inwards" }, .{ .name = "TCOM", .value = "" }, .{ .name = "TPE3", .value = "" }, .{ .name = "TPE2", .value = "<NAME>" }, .{ .name = "TCON", .value = "Death Metal, doom metal, atmospheric" }, }, }, .user_defined = &[_]MetadataEntry{ .{ .name = "PERFORMER", .value = "<NAME>" }, .{ .name = "ALBUM ARTIST", .value = "<NAME>" }, }, } }, } }); } test "id3v2.3 zero size frame" { try parseExpectedMetadata("data/id3v2.3_zero_size_frame.mp3", .{ .tags = &.{ .{ .id3v2 = .{ .major_version = 3, .metadata = .{ .start_offset = 0x0, .end_offset = 0x1000, .map = &[_]MetadataEntry{ .{ .name = "TFLT", .value = "audio/mp3" }, .{ .name = "TIT2", .value = "the global cannibal" }, .{ .name = "TALB", .value = "Global Cannibal, The" }, .{ .name = "TRCK", .value = "1" }, .{ .name = "TYER", .value = "2004" }, .{ .name = "TCON", .value = "Crust" }, .{ .name = "TPE1", .value = "Behind Enemy Lines" }, .{ .name = "TENC", .value = "" }, .{ .name = "TCOP", .value = "" }, .{ .name = "TCOM", .value = "" }, .{ .name = "TOPE", .value = "" }, }, }, .comments = &.{ .{ .language = "eng", .description = "", .value = "" }, .{ .language = "\x00\x00\x00", .description = "", .value = "" }, }, } }, } }); } test "id3v2.4 non-synchsafe frame size" { try parseExpectedMetadata("data/id3v2.4_non_synchsafe_frame_size.mp3", .{ .tags = &.{ .{ .id3v2 = .{ .major_version = 4, .metadata = .{ .start_offset = 0x0, .end_offset = 0xD6C, .map = &[_]MetadataEntry{ .{ .name = "TLEN", .value = "302813" }, .{ .name = "TIT2", .value = "Inevitable" }, .{ .name = "TPE1", .value = "Mushroomhead" }, .{ .name = "TALB", .value = "M3" }, .{ .name = "TRCK", .value = "4" }, .{ .name = "TDRC", .value = "1999" }, .{ .name = "TCON", .value = "(12)" }, }, }, } }, } }); } test "id3v2.4 extended header with crc" { try parseExpectedMetadata("data/id3v2.4_extended_header_crc.mp3", .{ .tags = &.{ .{ .id3v2 = .{ .major_version = 4, .metadata = .{ .start_offset = 0x0, .end_offset = 0x5F, .map = &[_]MetadataEntry{ .{ .name = "TIT2", .value = "Test" }, .{ .name = "TPE1", .value = "Test2" }, .{ .name = "TPE2", .value = "Test2" }, }, }, } }, } }); } test "id3v2.4 footer" { try parseExpectedMetadata("data/id3v2.4_footer.mp3", .{ .tags = &.{ .{ .id3v2 = .{ .major_version = 4, .metadata = .{ .start_offset = 0x0, .end_offset = 0x5D, .map = &[_]MetadataEntry{ .{ .name = "TIT2", .value = "Test" }, .{ .name = "TPE1", .value = "Test2" }, .{ .name = "TPE2", .value = "Test2" }, }, }, } }, } }); } test "id3v2.4 appended tag" { try parseExpectedMetadata("data/id3v2.4_appended.mp3", .{ .tags = &.{ .{ .id3v2 = .{ .major_version = 4, .metadata = .{ .start_offset = 0x18, .end_offset = 0x75, .map = &[_]MetadataEntry{ .{ .name = "TIT2", .value = "Test" }, .{ .name = "TPE1", .value = "Test2" }, .{ .name = "TPE2", .value = "Test2" }, }, }, } }, } }); } test "normal flac" { try parseExpectedMetadata("data/flac.flac", .{ .tags = &.{ .{ .flac = .{ .start_offset = 0x8, .end_offset = 0x14C, .map = &[_]MetadataEntry{ .{ .name = "ALBUM", .value = "Muga" }, .{ .name = "ALBUMARTIST", .value = "Muga" }, .{ .name = "ARTIST", .value = "Muga" }, .{ .name = "COMMENT", .value = "EAC V1.0 beta 2, Secure Mode, Test & Copy, AccurateRip, FLAC -8" }, .{ .name = "DATE", .value = "2002" }, .{ .name = "DISCNUMBER", .value = "1" }, .{ .name = "MEDIAFORMAT", .value = "CD" }, .{ .name = "PERFORMER", .value = "Muga" }, .{ .name = "TITLE", .value = "死前解放 (Unleash Before Death)" }, .{ .name = "DISCTOTAL", .value = "1" }, .{ .name = "TRACKTOTAL", .value = "11" }, .{ .name = "TRACKNUMBER", .value = "02" }, }, } }, } }); } test "flac with multiple date fields" { try parseExpectedMetadata("data/flac_multiple_dates.flac", .{ .tags = &.{ .{ .flac = .{ .start_offset = 0x8, .end_offset = 0x165, .map = &[_]MetadataEntry{ .{ .name = "TITLE", .value = "The Echoes Waned" }, .{ .name = "TRACKTOTAL", .value = "6" }, .{ .name = "DISCTOTAL", .value = "1" }, .{ .name = "LENGTH", .value = "389" }, .{ .name = "ISRC", .value = "USA2Z1810265" }, .{ .name = "BARCODE", .value = "647603399720" }, .{ .name = "ITUNESADVISORY", .value = "0" }, .{ .name = "COPYRIGHT", .value = "(C) 2018 The Flenser" }, .{ .name = "ALBUM", .value = "The Unraveling" }, .{ .name = "ARTIST", .value = "Ails" }, .{ .name = "GENRE", .value = "Metal" }, .{ .name = "ALBUMARTIST", .value = "Ails" }, .{ .name = "DISCNUMBER", .value = "1" }, .{ .name = "DATE", .value = "2018" }, .{ .name = "DATE", .value = "2018-04-20" }, .{ .name = "TRACKNUMBER", .value = "1" }, }, } }, } }); } test "id3v2.4 unsynch text frames" { try parseExpectedMetadata("data/id3v2.4_unsynch_text_frames.mp3", .{ .tags = &.{ .{ .id3v2 = .{ .major_version = 4, .metadata = .{ .start_offset = 0x0, .end_offset = 0x2170, .map = &[_]MetadataEntry{ .{ .name = "TCON", .value = "Alternative" }, .{ .name = "TDRC", .value = "1997" }, .{ .name = "TRCK", .value = "1" }, .{ .name = "TALB", .value = "Bruiser Queen" }, .{ .name = "TPE1", .value = "Cake Like" }, .{ .name = "TLEN", .value = "137000" }, .{ .name = "TPUB", .value = "Vapor Records" }, .{ .name = "TIT2", .value = "The New Girl" }, }, }, } }, } }); } test "id3v2.3 malformed TXXX" { try parseExpectedMetadata("data/id3v2.3_malformed_txxx.mp3", .{ .tags = &.{ .{ .id3v2 = .{ .major_version = 3, .metadata = .{ .start_offset = 0x0, .end_offset = 0x43, .map = &[_]MetadataEntry{}, }, } }, } }); } test "id3v2.4 malformed TXXX" { try parseExpectedMetadata("data/id3v2.4_malformed_txxx.mp3", .{ .tags = &.{ .{ .id3v2 = .{ .major_version = 4, .metadata = .{ .start_offset = 0x0, .end_offset = 0x3B, .map = &[_]MetadataEntry{}, }, } }, } }); } test "id3v2.3 unsynch tag edge case" { // Found via fuzzing. Has a full unsynch tag that has an end frame header with // unsynch bytes that extends to the end of the tag. This can trigger an // usize underflow if it's not protected against properly. try parseExpectedMetadata("data/id3v2.3_unsynch_tag_edge_case.mp3", .{ .tags = &.{ .{ .id3v2 = .{ .major_version = 3, .metadata = .{ .start_offset = 0x0, .end_offset = 0x43, .map = &[_]MetadataEntry{}, }, } }, } }); } test "id3v2.4 text frame with multiple terminated values" { try parseExpectedMetadata("data/id3v2.4_text_frame_with_multiple_terminated_values.mp3", .{ .tags = &.{ .{ .id3v2 = .{ .major_version = 4, .metadata = .{ .start_offset = 0x0, .end_offset = 0x1ba, .map = &[_]MetadataEntry{ .{ .name = "TCON", .value = "Hardcore" }, .{ .name = "TDRC", .value = "2006" }, .{ .name = "TRCK", .value = "2" }, .{ .name = "TCOM", .value = "<NAME>" }, .{ .name = "TCOM", .value = "<NAME>" }, }, }, .user_defined = &[_]MetadataEntry{ .{ .name = "COMMENT", .value = " 00001E45 000026CD 00006B50 00008F5A 0001AB0A 00001ED0 00008611 000087E7 0000976D 00002AC1" }, .{ .name = "COMMENT", .value = " 00000000 00000210 00000924 000000000063EC4C 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000" }, .{ .name = "COMMENT", .value = "D708EF10+171732+16+150+5249+16386+24551+36270+46625+54484+66325+79815+92681+96508+105514+119240+130979+146268+158072" }, .{ .name = "COMMENT", .value = "2" }, }, } }, } }); } test "id3v2.3 COMM as utf-16 with both BOM orderings" { try parseExpectedMetadata("data/id3v2.3_utf16_mismatched_boms.mp3", .{ .tags = &.{ .{ .id3v2 = .{ .major_version = 3, .metadata = .{ .start_offset = 0x0, .end_offset = 0x170, .map = &[_]MetadataEntry{ .{ .name = "TSSE", .value = "LAME 32bits version 3.98.4 (http://www.mp3dev.org/)" }, .{ .name = "TIT2", .value = "«‰ÂÒ¸ » —ÂȘ‡Ò / Here And Now" }, .{ .name = "TPE1", .value = "Optimus Prime" }, .{ .name = "TALB", .value = "Self-Titled" }, .{ .name = "TCON", .value = "Emocore/Screamo" }, .{ .name = "TRCK", .value = "1/7" }, .{ .name = "TYER", .value = "2010" }, .{ .name = "TLEN", .value = "246106" }, }, }, .comments = &.{.{ .language = "eng", .description = "", .value = "ExactAudioCopy v1.0b1", }}, } }, } }); } test "id3v2.4 incorrectly encoded (non-synchsafe) frame size edge cases" { // frame with non-synchsafe byte in the size try parseExpectedMetadata("data/id3v2.4_non_synchsafe_frame_size_bytes.mp3", .{ .tags = &.{ .{ .id3v2 = .{ .major_version = 4, .metadata = .{ .start_offset = 0x0, .end_offset = 0x3f8, .map = &[_]MetadataEntry{}, }, .unsynchronized_lyrics = &.{.{ .language = "eng", .description = "", .value = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque convallis ut nunc sit amet fringilla. Pellentesque tempor posuere dui, at commodo urna porttitor quis. Nunc tristique mollis lacus, ut ullamcorper odio finibus nec. Integer imperdiet orci a dolor maximus molestie. Maecenas quis faucibus odio. Donec molestie lectus magna, ac consequat ex posuere vitae. Praesent mauris diam, tempus et tempus in, dictum sit amet metus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae;\n\nUt non arcu pretium libero rutrum commodo. Mauris arcu ante, feugiat non vestibulum vitae, venenatis ac dui. Sed commodo magna vitae id.", }}, } }, } }); // incorrectly encoded frame size that runs up against padding try parseExpectedMetadata("data/id3v2.4_non_synchsafe_frame_size_padding.mp3", .{ .tags = &.{ .{ .id3v2 = .{ .major_version = 4, .metadata = .{ .start_offset = 0x0, .end_offset = 0x262, .map = &[_]MetadataEntry{}, }, .unsynchronized_lyrics = &.{.{ .language = "eng", .description = "", .value = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque convallis ut nunc sit amet fringilla. Pellentesque tempor posuere dui, at commodo urna porttitor quis. Nunc tristique mollis lacus, ut ullamcorper odio finibus nec. Integer imperdiet orci", }}, } }, } }); // incorrectly encoded frame size that runs up against EOF exactly try parseExpectedMetadata("data/id3v2.4_non_synchsafe_frame_size_eof.mp3", .{ .tags = &.{ .{ .id3v2 = .{ .major_version = 4, .metadata = .{ .start_offset = 0x0, .end_offset = 0x115, .map = &[_]MetadataEntry{}, }, .unsynchronized_lyrics = &.{.{ .language = "eng", .description = "", .value = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque convallis ut nunc sit amet fringilla. Pellentesque tempor posuere dui, at commodo urna porttitor quis. Nunc tristique mollis lacus, ut ullamcorper odio finibus nec. Integer imperdiet orci", }}, } }, } }); } test "id3v2.4 correctly encoded frame size edge cases" { // correctly encoded frame that runs up against padding try parseExpectedMetadata("data/id3v2.4_synchsafe_frame_size_padding.mp3", .{ .tags = &.{ .{ .id3v2 = .{ .major_version = 4, .metadata = .{ .start_offset = 0x0, .end_offset = 0x262, .map = &[_]MetadataEntry{}, }, .unsynchronized_lyrics = &.{.{ .language = "eng", .description = "", .value = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque convallis ut nunc sit amet fringilla. Pellentesque tempor posuere dui, at commodo urna porttitor quis. Nunc tristique mollis lacus, ut ullamcorper odio finibus nec. Integer imperdiet orci", }}, } }, } }); // correctly encoded frame that runs up against EOF exactly try parseExpectedMetadata("data/id3v2.4_synchsafe_frame_size_eof.mp3", .{ .tags = &.{ .{ .id3v2 = .{ .major_version = 4, .metadata = .{ .start_offset = 0x0, .end_offset = 0x115, .map = &[_]MetadataEntry{}, }, .unsynchronized_lyrics = &.{.{ .language = "eng", .description = "", .value = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque convallis ut nunc sit amet fringilla. Pellentesque tempor posuere dui, at commodo urna porttitor quis. Nunc tristique mollis lacus, ut ullamcorper odio finibus nec. Integer imperdiet orci", }}, } }, } }); } test "ogg" { try parseExpectedMetadata("data/vorbis.ogg", .{ .tags = &.{ .{ .vorbis = .{ .start_offset = 0x6d, .end_offset = 0x10e, .map = &[_]MetadataEntry{ .{ .name = "ALBUM", .value = "PIRATE" }, .{ .name = "ARTIST", .value = "TROMATISM" }, .{ .name = "GENRE", .value = "PUNK" }, .{ .name = "TITLE", .value = "Paria" }, .{ .name = "TRACKNUMBER", .value = "20" }, .{ .name = "COMMENT", .value = "http://www.sauve-qui-punk.org" }, }, } }, } }); } test "ogg with vorbis comment data spanning multiple pages" { try parseExpectedMetadata("data/vorbis_comment_spanning_pages.ogg", .{ .tags = &.{ .{ .vorbis = .{ .start_offset = 0x5d, .end_offset = 0x11a, .map = &[_]MetadataEntry{ .{ .name = "ALBUM", .value = "PIRATE" }, .{ .name = "ARTIST", .value = "TROMATISM" }, .{ .name = "GENRE", .value = "PUNK" }, .{ .name = "TITLE", .value = "Paria" }, .{ .name = "TRACKNUMBER", .value = "20" }, .{ .name = "COMMENT", .value = "http://www.sauve-qui-punk.org" }, }, } }, } }); } test "ape" { try parseExpectedMetadata("data/ape.mp3", .{ .tags = &.{ .{ .ape = .{ .version = 2000, .metadata = .{ .start_offset = 0x0, .end_offset = 0xce, .map = &[_]MetadataEntry{ .{ .name = "MP3GAIN_MINMAX", .value = "151,190" }, .{ .name = "MP3GAIN_UNDO", .value = "-006,-006,N" }, .{ .name = "REPLAYGAIN_TRACK_GAIN", .value = "-11.27000 dB" }, .{ .name = "REPLAYGAIN_TRACK_PEAK", .value = "2.003078" }, }, }, } }, } }); } test "ape with id3v2 and id3v1 tags" { try parseExpectedMetadata("data/ape_and_id3.mp3", .{ .tags = &.{ .{ .id3v2 = .{ .major_version = 3, .metadata = .{ .start_offset = 0x0, .end_offset = 0x998, .map = &[_]MetadataEntry{ .{ .name = "TLAN", .value = "rus" }, .{ .name = "TRCK", .value = "1/7" }, .{ .name = "TPE1", .value = "Axidance" }, .{ .name = "TYER", .value = "2012" }, .{ .name = "TDAT", .value = "0000" }, .{ .name = "TSSE", .value = "LAME v3.98.4 with preset -V0" }, .{ .name = "TCON", .value = "Hardcore" }, .{ .name = "TPUB", .value = "pure heart" }, .{ .name = "TALB", .value = "Gattaca" }, .{ .name = "TIT2", .value = "Aeon I - The Great Enemy" }, }, }, .user_defined = &[_]MetadataEntry{ .{ .name = "VA Artist", .value = "Axidance" }, .{ .name = "Language 2-letter", .value = "RU" }, .{ .name = "Ripping tool", .value = "Sony Sound Forge Pro v10.0a" }, .{ .name = "Release type", .value = "Split 12inch" }, .{ .name = "Source", .value = "Vinyl" }, .{ .name = "Rip date", .value = "2012-08-10" }, }, } }, .{ .ape = .{ .version = 2000, .metadata = .{ .start_offset = 0x998, .end_offset = 0xba4, .map = &[_]MetadataEntry{ .{ .name = "Language", .value = "Russian" }, .{ .name = "Disc", .value = "1" }, .{ .name = "Track", .value = "1" }, .{ .name = "Artist", .value = "Axidance" }, .{ .name = "Rip Date", .value = "2012-08-10" }, .{ .name = "Year", .value = "2012" }, .{ .name = "Retail Date", .value = "2012-00-00" }, .{ .name = "Media", .value = "Vinyl" }, .{ .name = "Encoder", .value = "LAME v3.98.4 with preset -V0" }, .{ .name = "Ripping Tool", .value = "Sony Sound Forge Pro v10.0a" }, .{ .name = "Release Type", .value = "Split 12inch" }, .{ .name = "Genre", .value = "Hardcore" }, .{ .name = "Language 2-letter", .value = "RU" }, .{ .name = "Publisher", .value = "pure heart" }, .{ .name = "Album Artist", .value = "Axidance" }, .{ .name = "Album", .value = "Gattaca" }, .{ .name = "Title", .value = "Aeon I - The Great Enemy" }, }, }, } }, .{ .id3v1 = .{ .start_offset = 0xba4, .end_offset = 0xc24, .map = &[_]MetadataEntry{ .{ .name = "title", .value = "Aeon I - The Great Enemy" }, .{ .name = "artist", .value = "Axidance" }, .{ .name = "album", .value = "Gattaca" }, .{ .name = "date", .value = "2012" }, .{ .name = "track", .value = "1" }, .{ .name = "genre", .value = "Hardcore Techno" }, }, } }, } }); } test "mp4" { try parseExpectedMetadata("data/test.mp4", .{ .tags = &.{ .{ .mp4 = .{ .start_offset = 0x18, .end_offset = 0x44d, .map = &[_]MetadataEntry{ .{ .name = "aART", .value = "Test album artist" }, .{ .name = "\xA9ART", .value = "Test artist" }, .{ .name = "\xA9alb", .value = "Test album" }, .{ .name = "\xA9cmt", .value = "no comment" }, .{ .name = "\xA9day", .value = "2022" }, .{ .name = "\xA9gen", .value = "Metal" }, .{ .name = "\xA9nam", .value = "Test title" }, .{ .name = "\xA9too", .value = "Lavf58.76.100" }, .{ .name = "\xA9wrt", .value = "Test composer" }, .{ .name = "cprt", .value = "Test copyright" }, }, } }, } }); } test "m4a with ----" { try parseExpectedMetadata("data/m4a_with_----.m4a", .{ .tags = &.{ .{ .mp4 = .{ .start_offset = 0x18, .end_offset = 0xab3, .map = &[_]MetadataEntry{ .{ .name = "\xA9ART", .value = "Momentum" }, .{ .name = "\xA9alb", .value = "Herbivore" }, .{ .name = "\xA9day", .value = "2012" }, .{ .name = "\xA9gen", .value = "Hardcore Punk" }, .{ .name = "\xA9nam", .value = "Barbarity" }, .{ .name = "\xA9too", .value = "iTunes 11.0" }, .{ .name = "trkn", .value = "1/8" }, .{ .name = "cpil", .value = "0" }, .{ .name = "pgap", .value = "0" }, .{ .name = "tmpo", .value = "0" }, .{ .name = "com.apple.iTunes.iTunSMPB", .value = " 00000000 00000840 00000134 00000000003CFA8C 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000" }, .{ .name = "com.apple.iTunes.iTunNORM", .value = " 00004FAE 00004D7E 0001ECE0 0001267D 00015D4C 000111BD 00007BB3 00007BAD 00015C63 00007C71" }, }, } }, } }); }
test/parse_tests.zig
// This code was generated by a tool. // IUP Metadata Code Generator // https://github.com/batiati/IUPMetadata // // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. 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; {{ElementDocumentation}} pub const {{Name}} = opaque { pub const CLASS_NAME = "{{ClassName}}"; pub const NATIVE_TYPE = iup.NativeType.{{NativeType}}; const Self = @This(); {{CallbacksDecl}} {{EnumsDecl}} 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.*; } {{InitializerTraits}} {{InitializerBlock}} }; 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); } {{BodyTraits}} {{BodyBlock}} }; {{TestsBlock}}
src/IupMetadata/CodeGenerators/Zig/templates/element.zig
const std = @import("std"); const real_input = @embedFile("day-12_real-input"); const test_input_1 = @embedFile("day-12_test-input-1"); const test_input_2 = @embedFile("day-12_test-input-2"); const test_input_3 = @embedFile("day-12_test-input-3"); pub fn main() !void { std.debug.print("--- Day 12 ---\n", .{}); var result = try execute(real_input); std.debug.print("there are {} distinct paths\n", .{ result }); } fn execute(input: []const u8) !u32 { var alloc_buffer: [1024 * 1024]u8 = undefined; var alloc = std.heap.FixedBufferAllocator.init(alloc_buffer[0..]); var small_caves = std.ArrayList([]const u8).init(alloc.allocator()); var large_caves = std.ArrayList([]const u8).init(alloc.allocator()); var connections = std.ArrayList(Connection).init(alloc.allocator()); var line_it = std.mem.tokenize(u8, input, "\r\n"); while (line_it.next()) |line| { if (line.len == 0) break; var cave_it = std.mem.split(u8, line, "-"); const from_cave = cave_it.next() orelse unreachable; switch (getCaveType(from_cave)) { .Small => try addUnique(&small_caves, from_cave), .Large => try addUnique(&large_caves, from_cave), else => { } } const to_cave = cave_it.next() orelse unreachable; switch (getCaveType(to_cave)) { .Small => try addUnique(&small_caves, to_cave), .Large => try addUnique(&large_caves, to_cave), else => { } } const connection = Connection { .from = from_cave, .to = to_cave, }; try connections.append(connection); const reverse = Connection { .from = to_cave, .to = from_cave, }; try connections.append(reverse); } var initial_path = std.ArrayList(Cave).init(alloc.allocator()); try initial_path.append("start"); const path_count = try continuePath(.{ .path = initial_path, .connections = connections.items, }); return path_count; } fn addUnique(list: *std.ArrayList(Cave), cave: Cave) !void { if (contains(list.items, cave)) return; try list.append(cave); } fn getCaveType(cave: []const u8) CaveType { if (equals(cave, "start")) return .Start; if (equals(cave, "end")) return .End; if (cave[0] >= 'A' and cave[0] <= 'Z') return .Large; if (cave[0] >= 'a' and cave[0] <= 'z') return .Small; unreachable; } fn continuePath(in: struct { path: std.ArrayList(Cave), double_small_cave_chosen: bool = false, connections: []Connection }) PathError!u32 { const pos = in.path.items[in.path.items.len - 1]; if (getCaveType(pos) == .End) return 1; var sub_paths: u32 = 0; for (in.connections) |connection| { if (!equals(connection.from, pos)) continue; var is_small = false; var num_visits: u32 = 0; switch (getCaveType(connection.to)) { .Start => continue, .Small => { is_small = true; num_visits = count(in.path.items, connection.to); switch (num_visits) { 0 => { }, 1 => if (in.double_small_cave_chosen) continue, 2 => continue, else => unreachable } }, else => { } } var sub_path = try std.ArrayList(Cave).initCapacity(in.path.allocator, in.path.items.len + 1); try sub_path.appendSlice(in.path.items); try sub_path.append(connection.to); sub_paths += try continuePath(.{ .path = sub_path, .double_small_cave_chosen = in.double_small_cave_chosen or (is_small and num_visits == 1), .connections = in.connections }); sub_path.deinit(); } return sub_paths; } const PathError = @typeInfo(@typeInfo(@TypeOf(std.ArrayListAligned([]const u8,null).initCapacity)).Fn.return_type.?).ErrorUnion.error_set; fn contains(haystack: []Cave, needle: Cave) bool { return for (haystack) |cave| { if (equals(cave, needle)) break true; } else false; } fn count(haystack: []Cave, needle: Cave) u32 { var result: u32 = 0; for (haystack) |cave| { if (equals(cave, needle)) result += 1; } return result; } fn equals(lhs: Cave, rhs: Cave) bool { return std.mem.eql(u8, lhs, rhs); } const Cave = []const u8; const CaveType = enum { Start, End, Small, Large, }; const Connection = struct { from: Cave, to: Cave, }; test "test-input-1" { const result = try execute(test_input_1); const expected: u32 = 36; try std.testing.expectEqual(expected, result); } test "test-input-2" { const result = try execute(test_input_2); const expected: u32 = 103; try std.testing.expectEqual(expected, result); } test "test-input-3" { const result = try execute(test_input_3); const expected: u32 = 3509; try std.testing.expectEqual(expected, result); }
day-12.zig
const std = @import("std"); const libxml2 = @import("libs/zig-libxml2/libxml2.zig"); const Builder = std.build.Builder; const LibExeObjStep = std.build.LibExeObjStep; const Step = std.build.Step; const GeneratedFile = std.build.GeneratedFile; fn root() []const u8 { return (std.fs.path.dirname(@src().file) orelse unreachable) ++ "/"; } pub const Regz = struct { builder: *Builder, exe: *LibExeObjStep, build_options: *std.build.OptionsStep, xml: libxml2.Library, pub const Options = struct { target: ?std.zig.CrossTarget = null, mode: ?std.builtin.Mode = null, }; pub fn create(builder: *Builder, opts: Options) *Regz { const target = opts.target orelse std.zig.CrossTarget{}; const mode = opts.mode orelse .Debug; const xml = libxml2.create(builder, target, mode, .{ .iconv = false, .lzma = false, .zlib = false, }) catch unreachable; xml.step.install(); const commit_result = std.ChildProcess.exec(.{ .allocator = builder.allocator, .argv = &.{ "git", "rev-parse", "HEAD" }, .cwd = root(), }) catch unreachable; const build_options = builder.addOptions(); build_options.addOption([]const u8, "commit", commit_result.stdout); const exe = builder.addExecutable("regz", root() ++ "src/main.zig"); exe.setTarget(target); exe.setBuildMode(mode); exe.addOptions("build_options", build_options); exe.addPackagePath("clap", root() ++ "libs/zig-clap/clap.zig"); xml.link(exe); var regz = builder.allocator.create(Regz) catch unreachable; regz.* = Regz{ .builder = builder, .exe = exe, .build_options = build_options, .xml = xml, }; return regz; } pub fn addGeneratedChipFile(regz: *Regz, schema_path: []const u8) GeneratedFile { // generate path where the schema will go // TODO: improve collision resistance const basename = std.fs.path.basename(schema_path); const extension = std.fs.path.extension(basename); const destination_path = std.fs.path.join(regz.builder.allocator, &.{ regz.builder.cache_root, "regz", std.mem.join(regz.builder.allocator, "", &.{ basename[0 .. basename.len - extension.len], ".zig", }) catch unreachable, }) catch unreachable; const run_step = regz.exe.run(); run_step.addArgs(&.{ schema_path, "-o", destination_path, }); return GeneratedFile{ .step = &run_step.step, .path = destination_path, }; } }; pub fn build(b: *std.build.Builder) !void { const target = b.standardTargetOptions(.{}); const mode = b.standardReleaseOptions(); const regz = Regz.create(b, .{ .target = target, .mode = mode, }); regz.exe.install(); const run_cmd = regz.exe.run(); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); const test_chip_file = regz.addGeneratedChipFile("tests/svd/cmsis-example.svd"); const tests = b.addTest("tests/main.zig"); tests.setTarget(target); tests.setBuildMode(mode); tests.addOptions("build_options", regz.build_options); tests.addPackagePath("xml", "src/xml.zig"); tests.addPackagePath("Database", "src/Database.zig"); regz.xml.link(tests); const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&tests.step); test_step.dependOn(test_chip_file.step); }
build.zig
const std = @import("std"); const stdx = @import("stdx"); const t = stdx.testing; const log = stdx.log.scoped(.color); pub const Color = struct { const Self = @This(); channels: struct { r: u8, g: u8, b: u8, a: u8, }, // Standard colors. pub const StdRed = init(255, 0, 0, 255); pub const StdYellow = init(255, 255, 0, 255); pub const StdGreen = init(0, 255, 0, 255); pub const StdCyan = init(0, 255, 255, 255); pub const StdBlue = init(0, 0, 255, 255); pub const StdMagenta = init(255, 0, 255, 255); // Prettier default colors from raylib + extras. pub const LightGray = init(200, 200, 200, 255); pub const Gray = init(130, 130, 130, 255); pub const DarkGray = init(80, 80, 80, 255); pub const Yellow = init(253, 249, 0, 255); pub const Gold = init(255, 203, 0, 255); pub const Orange = init(255, 161, 0, 255); pub const Pink = init(255, 109, 194, 255); pub const Red = init(230, 41, 55, 255); pub const Maroon = init(190, 33, 55, 255); pub const Green = init(0, 228, 48, 255); pub const Lime = init(0, 158, 47, 255); pub const DarkGreen = init(0, 117, 44, 255); pub const SkyBlue = init(102, 191, 255, 255); pub const Blue = init(0, 121, 241, 255); pub const RoyalBlue = init(65, 105, 225, 255); pub const DarkBlue = init(0, 82, 172, 255); pub const Purple = init(200, 122, 255, 255); pub const Violet = init(135, 60, 190, 255); pub const DarkPurple = init(112, 31, 126, 255); pub const Beige = init(211, 176, 131, 255); pub const Brown = init(127, 106, 79, 255); pub const DarkBrown = init(76, 63, 47, 255); pub const White = init(255, 255, 255, 255); pub const Black = init(0, 0, 0, 255); pub const Transparent = init(0, 0, 0, 0); pub const Magenta = init(255, 0, 255, 255); pub fn init(r: u8, g: u8, b: u8, a: u8) Self { return @This(){ .channels = .{ .r = r, .g = g, .b = b, .a = a }, }; } pub fn initFloat(r: f32, g: f32, b: f32, a: f32) Self { return init(@floatToInt(u8, r * 255), @floatToInt(u8, g * 255), @floatToInt(u8, b * 255), @floatToInt(u8, a * 255)); } pub fn withAlpha(self: Self, a: u8) Self { return init(self.channels.r, self.channels.g, self.channels.b, a); } pub fn lighter(self: Self) Self { return self.tint(0.25); } pub fn darker(self: Self) Self { return self.shade(0.25); } // Increase darkness, amt range: [0,1] pub fn shade(self: Self, amt: f32) Self { const factor = 1 - amt; return init(@floatToInt(u8, @intToFloat(f32, self.channels.r) * factor), @floatToInt(u8, @intToFloat(f32, self.channels.g) * factor), @floatToInt(u8, @intToFloat(f32, self.channels.b) * factor), self.channels.a); } // Increase lightness, amt range: [0,1] pub fn tint(self: Self, amt: f32) Self { return init(@floatToInt(u8, @intToFloat(f32, 255 - self.channels.r) * amt) + self.channels.r, @floatToInt(u8, @intToFloat(f32, 255 - self.channels.g) * amt) + self.channels.g, @floatToInt(u8, @intToFloat(f32, 255 - self.channels.b) * amt) + self.channels.b, self.channels.a); } pub fn parse(str: []const u8) !@This() { switch (str.len) { 3 => { // RGB const r = try std.fmt.parseInt(u8, str[0..1], 16); const g = try std.fmt.parseInt(u8, str[1..2], 16); const b = try std.fmt.parseInt(u8, str[2..3], 16); return init(r << 4 | r, g << 4 | g, b << 4 | b, 255); }, 4 => { // #RGB if (str[0] == '#') { return parse(str[1..]); } else { // log.debug("{s}", .{str}); return error.UnknownFormat; } }, 6 => { // RRGGBB const r = try std.fmt.parseInt(u8, str[0..2], 16); const g = try std.fmt.parseInt(u8, str[2..4], 16); const b = try std.fmt.parseInt(u8, str[4..6], 16); return init(r, g, b, 255); }, 7 => { // #RRGGBB if (str[0] == '#') { return parse(str[1..]); } else { return error.UnknownFormat; } }, else => return error.UnknownFormat, } } pub fn toHsv(self: Self) [3]f32 { const r = @intToFloat(f32, self.channels.r) / 255; const g = @intToFloat(f32, self.channels.g) / 255; const b = @intToFloat(f32, self.channels.b) / 255; const cmax = std.math.max(r, std.math.max(g, b)); const cmin = std.math.min(r, std.math.min(g, b)); const diff = cmax - cmin; var h = @as(f32, -1); var s = @as(f32, -1); if (cmax == cmin) { h = 0; } else if (cmax == r) { h = @mod(60 * ((g - b) / diff) + 360, 360); } else if (cmax == g) { h = @mod(60 * ((b - r) / diff) + 120, 360); } else if (cmax == b) { h = @mod(60 * ((r - g) / diff) + 240, 360); } if (cmax == 0) { s = 0; } else { s = (diff / cmax); } const v = cmax; return [_]f32{ h, s, v }; } /// hue is in degrees [0,360] /// assumes sat/val are clamped to: [0,1] pub fn fromHsv(hue: f32, sat: f32, val: f32) Self { var res = Color.init(0, 0, 0, 255); // red var k = std.math.mod(f32, 5 + hue/60.0, 6) catch unreachable; var t_ = 4.0 - k; k = if (t_ < k) t_ else k; k = if (k < 1) k else 1; k = if (k > 0) k else 0; res.channels.r = @floatToInt(u8, (val - val*sat*k)*255.0); // green k = std.math.mod(f32, 3.0 + hue/60.0, 6) catch unreachable; t_ = 4.0 - k; k = if (t_ < k) t_ else k; k = if (k < 1) k else 1; k = if (k > 0) k else 0; res.channels.g = @floatToInt(u8, (val - val*sat*k)*255.0); // blue k = std.math.mod(f32, 1.0 + hue/60.0, 6) catch unreachable; t_ = 4.0 - k; k = if (t_ < k) t_ else k; k = if (k < 1) k else 1; k = if (k > 0) k else 0; res.channels.b = @floatToInt(u8, (val - val*sat*k)*255.0); return res; } test "hsv to rgb" { try t.eq(Color.fromHsv(270, 0.6, 0.7), Color.init(124, 71, 178, 255)); } pub fn fromU32(c: u32) Color { return init( @intCast(u8, c >> 24), @intCast(u8, c >> 16 & 0xFF), @intCast(u8, c >> 8 & 0xFF), @intCast(u8, c & 0xFF), ); } pub fn toU32(self: Self) u32 { return @as(u32, self.channels.r) << 24 | @as(u24, self.channels.g) << 16 | @as(u16, self.channels.b) << 8 | self.channels.a; } pub fn toFloatArray(self: Self) [4]f32 { return .{ @intToFloat(f32, self.channels.r) / 255, @intToFloat(f32, self.channels.g) / 255, @intToFloat(f32, self.channels.b) / 255, @intToFloat(f32, self.channels.a) / 255, }; } }; test "Color struct size" { try t.eq(@sizeOf(Color), 4); } test "toU32 fromU32" { const i = Color.Red.toU32(); try t.eq(Color.fromU32(i), Color.Red); } test "from 3 digit hex" { try t.eq(Color.parse("#ABC"), Color.init(170, 187, 204, 255)); }
graphics/src/color.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const bindings = @import("bindings.zig"); const Sdl = bindings.Sdl; // TODO: make alternative that syncs video to audio instead of // trying to sync audio to video pub const Context = struct { device: bindings.c.SDL_AudioDeviceID, buffer: SampleBuffer, previous_sample: f32 = 0, pub const sample_rate = 44100 / 2; pub const sdl_buffer_size = 1024; const SampleBuffer = struct { samples: []f32, start: usize = 0, index: usize, preferred_size: usize, pub fn init(samples: []f32, preferred_size: usize) SampleBuffer { std.debug.assert(preferred_size < samples.len); std.mem.set(f32, samples[0..], 0); return SampleBuffer{ .samples = samples, .index = preferred_size, .preferred_size = preferred_size, }; } pub fn convertIndex(self: SampleBuffer, index: usize) usize { return (self.start + index) % self.samples.len; } pub fn length(self: SampleBuffer) usize { return ((self.index + self.samples.len) - self.start) % self.samples.len; } pub fn get(self: SampleBuffer, index: usize) f32 { return self.samples[self.convertIndex(index)]; } pub fn append(self: *SampleBuffer, val: f32) void { self.samples[self.index] = val; self.index = (self.index + 1) % self.samples.len; } pub fn truncateStart(self: *SampleBuffer, count: usize) void { const prev_order = self.index > self.start; self.start = (self.start + count) % self.samples.len; if (prev_order and (self.index < self.start)) { std.log.warn("Audio sample buffer ate its own tail", .{}); self.index = self.start; } } }; pub fn alloc(allocator: *Allocator) !Context { const buffer = try allocator.alloc(f32, Context.sample_rate); return Context{ .device = undefined, .buffer = SampleBuffer.init(buffer, (Context.sample_rate / 6) - 1024), }; } pub fn init(self: *Context) !void { var want = bindings.c.SDL_AudioSpec{ .freq = sample_rate, .format = bindings.c.AUDIO_F32SYS, .channels = 1, .samples = sdl_buffer_size, .callback = audioCallback, .userdata = self, // readback variables .silence = 0, .padding = 0, .size = 0, }; var have = std.mem.zeroes(bindings.c.SDL_AudioSpec); self.device = Sdl.openAudioDevice(.{ null, 0, &want, &have, 0 }); if (self.device == 0) { return bindings.CError.SdlError; } self.pause(); } pub fn deinit(self: *Context, allocator: *Allocator) void { Sdl.closeAudioDevice(.{self.device}); allocator.free(self.buffer.samples); } pub fn pause(self: Context) void { Sdl.pauseAudioDevice(.{ self.device, 1 }); } pub fn unpause(self: Context) void { Sdl.pauseAudioDevice(.{ self.device, 0 }); } pub fn addSample(self: *Context, val: f32) !void { const pi = std.math.pi; const high_pass1_a = (90 * pi) / (Context.sample_rate + 90 * pi); const high_pass2_a = (440 * pi) / (Context.sample_rate + 440 * pi); const low_pass_a = (14000 * pi) / (Context.sample_rate + 14000 * pi); const high_pass1 = high_pass1_a * val + (1 - high_pass1_a) * self.previous_sample; const high_pass2 = high_pass2_a * val + (1 - high_pass2_a) * high_pass1; const low_pass = low_pass_a * val + (1 - low_pass_a) * high_pass2; self.buffer.append(low_pass); self.previous_sample = low_pass; } fn audioCallback(user_data: ?*c_void, raw_buffer: [*c]u8, samples: c_int) callconv(.C) void { var context = @ptrCast(*Context, @alignCast(@sizeOf(@TypeOf(user_data)), user_data.?)); var buffer = @ptrCast([*]f32, @alignCast(4, raw_buffer))[0..@intCast(usize, @divExact(samples, 4))]; const ps = @intToFloat(f64, context.buffer.preferred_size); const length = @intToFloat(f64, context.buffer.length()); //const copy_rate: f64 = 0.25 * (1 + length / ps); //const copy_rate: f64 = 0.25 * (length / ps - 1) + 1; const copy_rate: f64 = blk: { const temp = (length / ps) - 1; break :blk temp * temp * temp + 1; }; //const copy_rate: f64 = (std.math.tanh(16 * (length - ps) / sample_rate) + 1) / 2; var copy_rem: f64 = 0; var i: usize = 0; if (copy_rate >= 1) { for (buffer) |*b| { b.* = context.buffer.get(i); const inc = copy_rate + copy_rem; i += @floatToInt(usize, @trunc(inc)); copy_rem = @mod(inc, 1); } } else { for (buffer) |*b| { b.* = context.buffer.get(i); copy_rem += copy_rate; if (copy_rem > 1) { i += 1; copy_rem -= 1; } } } context.buffer.truncateStart(i); } };
src/sdl/audio.zig
const std = @import("std"); const net = std.net; const os = std.os; const linux = os.linux; const io_uring_sqe = linux.io_uring_sqe; const io_uring_cqe = linux.io_uring_cqe; const assert = std.debug.assert; const Conn = struct { // TODO std.x.os.Socket addr: os.sockaddr = undefined, addr_len: os.socklen_t = @sizeOf(os.sockaddr), }; const Op = union(enum) { accept: struct { addr: os.sockaddr = undefined, addr_len: os.socklen_t = @sizeOf(os.sockaddr), }, epoll: struct { fd: os.fd_t }, close: struct { fd: os.fd_t, }, connect: struct { sock: os.socket_t, address: std.net.Address, }, fsync: struct { fd: os.fd_t, }, read: struct { fd: os.fd_t, buffer: []u8, offset: u64, }, recv: struct { sock: os.socket_t, buffer: []u8, }, send: struct { sock: os.socket_t, buffer: []const u8, }, timeout: struct { timespec: os.linux.kernel_timespec, }, write: struct { fd: os.fd_t, buffer: []const u8, offset: u64, }, }; const Completion = struct { op: Op, }; const Server = struct { ring: linux.IO_Uring, listen_fd: os.socket_t, epoll_fd: os.fd_t, fn q_accept(self: *Server, completion: *Completion) !*io_uring_sqe { completion.op = .{ .accept = .{ .sock = self.listen_fd } }; return try self.ring.accept(@ptrToInt(completion), self.listen_fd, &completion.op.accept.addr, &completion.op.accept.addr_len, os.SOCK.NONBLOCK | os.SOCK.CLOEXEC); } }; pub fn main() !void { const LISTEN_BACKLOG = 1; const address = try net.Address.parseIp4("127.0.0.1", 3131); const listen_socket = try os.socket(address.any.family, os.SOCK.STREAM | os.SOCK.CLOEXEC, 0); defer os.closeSocket(listen_socket); // try os.setsockopt(listen_socket, os.SOL.SOCKET, os.SO.REUSEADDR, &std.mem.toBytes(@as(c_int, 1))); try os.bind(listen_socket, &address.any, address.getOsSockLen()); try os.listen(listen_socket, LISTEN_BACKLOG); var ring = try std.os.linux.IO_Uring.init(256, 0); defer ring.deinit(); var epoll_fd = try os.epoll_create1(os.linux.EPOLL.CLOEXEC); defer os.close(epoll_fd); // var server = Server{ // .ring = ring, // .listen_fd = listen_socket, // .epoll_fd = epoll_fd, // }; var completions = [_]Completion{ .{ .op = .{ .accept = .{} } }, .{ .op = .{ .epoll = .{ .fd = epoll_fd } } }, }; var accept_completion = &completions[0]; var epoll_completion = &completions[1]; // // notify when we need accept. var epoll_event = linux.epoll_event{ .events = linux.EPOLL.IN | linux.EPOLL.ONESHOT, .data = linux.epoll_data{ .ptr = 0 }, }; // os.epoll_ctl(epfd: i32, op: u32, fd: i32, event: ?*linux.epoll_event) _ = try ring.epoll_ctl(@ptrToInt(epoll_completion), epoll_fd, listen_socket, os.linux.EPOLL.CTL_ADD, &epoll_event); var events: [128]linux.epoll_event = undefined; var cqes: [128]io_uring_cqe = undefined; while (true) { const nsubmit = try ring.submit_and_wait(1); // consume epoll events: non-blocking const nevents = os.epoll_wait(epoll_fd, &events, 10); for (events[0..nevents]) |ev| { const is_error = ev.events & linux.EPOLL.ERR != 0; const is_hup = ev.events & (linux.EPOLL.HUP | linux.EPOLL.RDHUP) != 0; const is_readable = ev.events & linux.EPOLL.IN != 0; const is_writable = ev.events & linux.EPOLL.OUT != 0; std.log.info("is_error={} is_readable={} is_writable={} is_hup={} \n", .{ is_error, is_readable, is_writable, is_hup }); // accept new connections. if (ev.data.fd == listen_socket) { // CTL_MOD to re-arm the listen_socket for new accepts. // _ = try ring.epoll_ctl(@ptrToInt(epoll_completion), epoll_fd, listen_socket, os.linux.EPOLL.CTL_MOD, &epoll_event); _ = try ring.accept( @ptrToInt(accept_completion), listen_socket, &accept_completion.op.accept.addr, &accept_completion.op.accept.addr_len, os.SOCK.NONBLOCK | os.SOCK.CLOEXEC, ); } } // submit: non-blocking std.log.info("loop: nsubmit={} nevents={}\n", .{ nsubmit, nevents }); const nr = try ring.copy_cqes(&cqes, 0); for (cqes[0..nr]) |cqe, i| { switch (cqe.err()) { .SUCCESS => {}, else => |errno| std.debug.panic("unhandled errno: {}", .{errno}), } const c = @intToPtr(*Completion, cqe.user_data); switch (c.op) { .epoll => {}, .accept => { std.log.info("accept: {}", .{c.op.accept.addr}); }, else => |op| std.log.warn("unhandled op: {}", .{op}), } std.log.info("cqe: {} {} {}\n", .{ cqe, c.op, i }); // on_epoll: oneshot re-arm // on_accept: add fd to epoll, on epoll read everything. } } }
src/v1-epoll/main.zig
const std = @import("std"); const debug = std.debug; const mem = std.mem; const math = std.math; const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; // A single inclusive range (a, b) and a <= b pub fn Range(comptime T: type) type { return struct { min: T, max: T, pub fn new(min: T, max: T) Range(T) { debug.assert(min <= max); return Range(T){ .min = min, .max = max }; } pub fn single(item: T) Range(T) { return Range(T){ .min = item, .max = item }; } }; } // A contiguous set of ranges which manages merging of sub-ranges and negation of the entire class. pub fn RangeSet(comptime T: type) type { return struct { const Self = @This(); const RangeType = Range(T); // for any consecutive x, y in ranges, the following hold: // - x.min <= x.max // - x.max < y.min ranges: ArrayList(RangeType), pub fn init(a: *Allocator) Self { return Self{ .ranges = ArrayList(RangeType).init(a) }; } pub fn deinit(self: *Self) void { self.ranges.deinit(); } // Add a range into the current class, preserving the structure invariants. pub fn addRange(self: *Self, range: RangeType) !void { var ranges = &self.ranges; if (ranges.items.len == 0) { try ranges.append(range); return; } // Insert range. for (ranges.items) |r, i| { if (range.min <= r.min) { try ranges.insert(i, range); break; } } else { try ranges.append(range); } // Merge overlapping runs. var index: usize = 0; var merge = ranges.items[0]; for (ranges.items[1..]) |r| { // Overlap (or directly adjacent) const upper = math.add(T, merge.max, 1) catch math.maxInt(T); if (r.min <= upper) { merge.max = math.max(merge.max, r.max); } // No overlap else { ranges.items[index] = merge; merge = r; index += 1; } } ranges.items[index] = merge; index += 1; ranges.shrinkRetainingCapacity(index); } // Merge two classes into one. pub fn mergeClass(self: *Self, other: Self) !void { for (other.ranges.items) |r| { try self.addRange(r); } } // Inverting a class means the resulting class the contains method will match // the inverted set. i.e. contains(a, byte) == !contains(b, byte) if a == b.negated(). // // The negation is performed in place. pub fn negate(self: *Self) !void { var ranges = &self.ranges; // NOTE: Append to end of array then copy and shrink. var negated = ArrayList(RangeType).init(self.ranges.allocator); if (ranges.items.len == 0) { try negated.append(RangeType.new(math.minInt(T), math.maxInt(T))); mem.swap(ArrayList(RangeType), ranges, &negated); negated.deinit(); return; } var low: T = math.minInt(T); for (ranges.items) |r| { // NOTE: Can only occur on first element. if (r.min != math.minInt(T)) { try negated.append(RangeType.new(low, r.min - 1)); } low = math.add(T, r.max, 1) catch math.maxInt(T); } // Highest segment will be remaining. const lastRange = ranges.items[ranges.items.len - 1]; if (lastRange.max != math.maxInt(T)) { try negated.append(RangeType.new(low, math.maxInt(T))); } mem.swap(ArrayList(RangeType), ranges, &negated); negated.deinit(); } pub fn contains(self: Self, value: T) bool { // TODO: Binary search required for large unicode sets. for (self.ranges.items) |range| { if (range.min <= value and value <= range.max) { return true; } } return false; } }; } pub const ByteClassTemplates = struct { const ByteRange = Range(u8); const ByteClass = RangeSet(u8); pub fn Whitespace(a: *Allocator) !ByteClass { var rs = ByteClass.init(a); errdefer rs.deinit(); // \t, \n, \v, \f, \r try rs.addRange(ByteRange.new('\x09', '\x0D')); // ' ' try rs.addRange(ByteRange.single(' ')); return rs; } pub fn NonWhitespace(a: *Allocator) !ByteClass { var rs = try Whitespace(a); errdefer rs.deinit(); try rs.negate(); return rs; } pub fn AlphaNumeric(a: *Allocator) !ByteClass { var rs = ByteClass.init(a); errdefer rs.deinit(); try rs.addRange(ByteRange.new('0', '9')); try rs.addRange(ByteRange.new('A', 'Z')); try rs.addRange(ByteRange.new('a', 'z')); return rs; } pub fn NonAlphaNumeric(a: *Allocator) !ByteClass { var rs = try AlphaNumeric(a); errdefer rs.deinit(); try rs.negate(); return rs; } pub fn Digits(a: *Allocator) !ByteClass { var rs = ByteClass.init(a); errdefer rs.deinit(); try rs.addRange(ByteRange.new('0', '9')); return rs; } pub fn NonDigits(a: *Allocator) !ByteClass { var rs = try Digits(a); errdefer rs.deinit(); try rs.negate(); return rs; } }; test "class simple" { const alloc = std.testing.allocator; var a = RangeSet(u8).init(alloc); try a.addRange(Range(u8).new(0, 54)); debug.assert(a.contains(0)); debug.assert(a.contains(23)); debug.assert(a.contains(54)); debug.assert(!a.contains(58)); } test "class simple negate" { const alloc = std.testing.allocator; var a = RangeSet(u8).init(alloc); try a.addRange(Range(u8).new(0, 54)); debug.assert(a.contains(0)); debug.assert(a.contains(23)); debug.assert(a.contains(54)); debug.assert(!a.contains(58)); try a.negate(); // Match the negation debug.assert(!a.contains(0)); debug.assert(!a.contains(23)); debug.assert(!a.contains(54)); debug.assert(a.contains(55)); debug.assert(a.contains(58)); try a.negate(); // negate is idempotent debug.assert(a.contains(0)); debug.assert(a.contains(23)); debug.assert(a.contains(54)); debug.assert(!a.contains(58)); } test "class multiple" { const alloc = std.testing.allocator; var a = RangeSet(u8).init(alloc); try a.addRange(Range(u8).new(0, 20)); try a.addRange(Range(u8).new(80, 100)); try a.addRange(Range(u8).new(230, 255)); debug.assert(a.contains(20)); debug.assert(!a.contains(21)); debug.assert(!a.contains(79)); debug.assert(a.contains(80)); debug.assert(!a.contains(229)); debug.assert(a.contains(230)); debug.assert(a.contains(255)); } test "class multiple negated" { const alloc = std.testing.allocator; var a = RangeSet(u8).init(alloc); try a.addRange(Range(u8).new(0, 20)); try a.addRange(Range(u8).new(80, 100)); try a.addRange(Range(u8).new(230, 255)); debug.assert(a.contains(20)); debug.assert(!a.contains(21)); debug.assert(!a.contains(79)); debug.assert(a.contains(80)); debug.assert(!a.contains(229)); debug.assert(a.contains(230)); debug.assert(a.contains(255)); try a.negate(); debug.assert(!a.contains(20)); debug.assert(a.contains(21)); debug.assert(a.contains(79)); debug.assert(!a.contains(80)); debug.assert(a.contains(229)); debug.assert(!a.contains(230)); debug.assert(!a.contains(255)); try a.negate(); debug.assert(a.contains(20)); debug.assert(!a.contains(21)); debug.assert(!a.contains(79)); debug.assert(a.contains(80)); debug.assert(!a.contains(229)); debug.assert(a.contains(230)); debug.assert(a.contains(255)); } test "class out of order" { const alloc = std.testing.allocator; var a = RangeSet(u8).init(alloc); try a.addRange(Range(u8).new(80, 100)); try a.addRange(Range(u8).new(20, 30)); debug.assert(a.contains(80)); debug.assert(!a.contains(79)); debug.assert(!a.contains(101)); debug.assert(!a.contains(45)); debug.assert(!a.contains(19)); } test "class merging" { const alloc = std.testing.allocator; var a = RangeSet(u8).init(alloc); try a.addRange(Range(u8).new(20, 100)); try a.addRange(Range(u8).new(50, 80)); try a.addRange(Range(u8).new(50, 140)); debug.assert(!a.contains(19)); debug.assert(a.contains(20)); debug.assert(a.contains(80)); debug.assert(a.contains(140)); debug.assert(!a.contains(141)); } test "class merging boundary" { const alloc = std.testing.allocator; var a = RangeSet(u8).init(alloc); try a.addRange(Range(u8).new(20, 40)); try a.addRange(Range(u8).new(40, 60)); debug.assert(a.ranges.items.len == 1); } test "class merging adjacent" { const alloc = std.testing.allocator; var a = RangeSet(u8).init(alloc); try a.addRange(Range(u8).new(56, 56)); try a.addRange(Range(u8).new(57, 57)); try a.addRange(Range(u8).new(58, 58)); debug.assert(a.ranges.items.len == 1); }
src/range_set.zig
const builtin = @import("builtin"); const std = @import("std"); const Mutex = std.Thread.Mutex; const expect = std.testing.expect; extern fn cbtAlignedAllocSetCustomAligned( alloc: fn (size: usize, alignment: i32) callconv(.C) ?*anyopaque, free: fn (memblock: ?*anyopaque) callconv(.C) void, ) void; var gpa = std.heap.GeneralPurposeAllocator(.{ .thread_safe = false }){}; var allocator: ?std.mem.Allocator = null; var allocations: ?std.AutoHashMap(usize, usize) = null; var mutex: Mutex = .{}; export fn allocFunc(size: usize, alignment: i32) callconv(.C) ?*anyopaque { mutex.lock(); defer mutex.unlock(); var memblock = allocator.?.allocBytes( @intCast(u29, alignment), size, 0, @returnAddress(), ) catch return null; allocations.?.put(@ptrToInt(memblock.ptr), size) catch unreachable; return memblock.ptr; } export fn freeFunc(memblock: ?*anyopaque) callconv(.C) void { if (memblock != null) { mutex.lock(); defer mutex.unlock(); const size = allocations.?.fetchRemove(@ptrToInt(memblock.?)).?.value; const slice = @ptrCast([*]u8, memblock.?)[0..size]; allocator.?.free(slice); } } pub fn init() void { std.debug.assert(allocator == null and allocations == null); allocator = gpa.allocator(); allocations = std.AutoHashMap(usize, usize).init(allocator.?); allocations.?.ensureTotalCapacity(1024) catch unreachable; cbtAlignedAllocSetCustomAligned(allocFunc, freeFunc); } pub fn deinit() void { allocations.?.deinit(); allocations = null; allocator = null; if (gpa.deinit()) { if (builtin.mode == .Debug) @panic("zbullet: Memory leak detected."); } gpa = .{}; } pub const World = opaque { pub fn init(params: struct {}) Error!*const World { _ = params; std.debug.assert(allocator != null and allocations != null); const ptr = cbtWorldCreate(); if (ptr == null) { return error.OutOfMemory; } return ptr.?; } extern fn cbtWorldCreate() ?*const World; pub fn deinit(world: *const World) void { std.debug.assert(world.getNumBodies() == 0); cbtWorldDestroy(world); } extern fn cbtWorldDestroy(world: *const World) void; pub const setGravity = cbtWorldSetGravity; extern fn cbtWorldSetGravity(world: *const World, gravity: *const [3]f32) void; pub const getGravity = cbtWorldGetGravity; extern fn cbtWorldGetGravity(world: *const World, gravity: *[3]f32) void; pub fn stepSimulation(world: *const World, time_step: f32, params: struct { max_sub_steps: u32 = 1, fixed_time_step: f32 = 1.0 / 60.0, }) u32 { return cbtWorldStepSimulation(world, time_step, params.max_sub_steps, params.fixed_time_step); } extern fn cbtWorldStepSimulation( world: *const World, time_step: f32, max_sub_steps: u32, fixed_time_step: f32, ) u32; pub const addBody = cbtWorldAddBody; extern fn cbtWorldAddBody(world: *const World, body: *const Body) void; pub const removeBody = cbtWorldRemoveBody; extern fn cbtWorldRemoveBody(world: *const World, body: *const Body) void; pub const getBody = cbtWorldGetBody; extern fn cbtWorldGetBody(world: *const World, index: i32) *const Body; pub const getNumBodies = cbtWorldGetNumBodies; extern fn cbtWorldGetNumBodies(world: *const World) i32; pub const setDebugDrawer = cbtWorldDebugSetDrawer; extern fn cbtWorldDebugSetDrawer(world: *const World, debug: *const DebugDraw) void; pub const setDebugMode = cbtWorldDebugSetMode; extern fn cbtWorldDebugSetMode(world: *const World, mode: DebugMode) void; pub const debugDrawAll = cbtWorldDebugDrawAll; extern fn cbtWorldDebugDrawAll(world: *const World) void; pub const debugDrawLine1 = cbtWorldDebugDrawLine1; extern fn cbtWorldDebugDrawLine1( world: *const World, p0: *const [3]f32, p1: *const [3]f32, color: *const [3]f32, ) void; pub const debugDrawLine2 = cbtWorldDebugDrawLine2; extern fn cbtWorldDebugDrawLine2( world: *const World, p0: *const [3]f32, p1: *const [3]f32, color0: *const [3]f32, color1: *const [3]f32, ) void; pub const debugDrawSphere = cbtWorldDebugDrawSphere; extern fn cbtWorldDebugDrawSphere( world: *const World, position: *const [3]f32, radius: f32, color: *const [3]f32, ) void; }; pub const ShapeType = enum(c_int) { box = 0, sphere = 8, capsule = 10, cylinder = 13, compound = 31, trimesh = 21, }; pub const Axis = enum(c_int) { x = 0, y = 1, z = 2, }; pub const Error = error{OutOfMemory}; pub const Shape = opaque { pub fn allocate(stype: ShapeType) Error!*const Shape { const ptr = cbtShapeAllocate(stype); if (ptr == null) { return error.OutOfMemory; } return ptr.?; } extern fn cbtShapeAllocate(stype: ShapeType) ?*const Shape; pub const deallocate = cbtShapeDeallocate; extern fn cbtShapeDeallocate(shape: *const Shape) void; pub fn deinit(shape: *const Shape) void { shape.destroy(); shape.deallocate(); } pub fn destroy(shape: *const Shape) void { switch (shape.getType()) { .box, .sphere, .capsule, .cylinder, .compound, => cbtShapeDestroy(shape), .trimesh => cbtShapeTriMeshDestroy(shape), } } extern fn cbtShapeDestroy(shape: *const Shape) void; extern fn cbtShapeTriMeshDestroy(shape: *const Shape) void; pub const isCreated = cbtShapeIsCreated; extern fn cbtShapeIsCreated(shape: *const Shape) bool; pub const getType = cbtShapeGetType; extern fn cbtShapeGetType(shape: *const Shape) ShapeType; pub const setMargin = cbtShapeSetMargin; extern fn cbtShapeSetMargin(shape: *const Shape, margin: f32) void; pub const getMargin = cbtShapeGetMargin; extern fn cbtShapeGetMargin(shape: *const Shape) f32; pub const isPolyhedral = cbtShapeIsPolyhedral; extern fn cbtShapeIsPolyhedral(shape: *const Shape) bool; pub const isConvex2d = cbtShapeIsConvex2d; extern fn cbtShapeIsConvex2d(shape: *const Shape) bool; pub const isConvex = cbtShapeIsConvex; extern fn cbtShapeIsConvex(shape: *const Shape) bool; pub const isNonMoving = cbtShapeIsNonMoving; extern fn cbtShapeIsNonMoving(shape: *const Shape) bool; pub const isConcave = cbtShapeIsConcave; extern fn cbtShapeIsConcave(shape: *const Shape) bool; pub const isCompound = cbtShapeIsCompound; extern fn cbtShapeIsCompound(shape: *const Shape) bool; pub const calculateLocalInertia = cbtShapeCalculateLocalInertia; extern fn cbtShapeCalculateLocalInertia(shape: *const Shape, mass: f32, inertia: *[3]f32) void; pub const setUserPointer = cbtShapeSetUserPointer; extern fn cbtShapeSetUserPointer(shape: *const Shape, ptr: ?*anyopaque) void; pub const getUserPointer = cbtShapeGetUserPointer; extern fn cbtShapeGetUserPointer(shape: *const Shape) ?*anyopaque; pub const setUserIndex = cbtShapeSetUserIndex; extern fn cbtShapeSetUserIndex(shape: *const Shape, slot: u32, index: i32) void; pub const getUserIndex = cbtShapeGetUserIndex; extern fn cbtShapeGetUserIndex(shape: *const Shape, slot: u32) i32; }; fn ShapeFunctions(comptime T: type) type { return struct { pub fn asShape(shape: *const T) *const Shape { return @ptrCast(*const Shape, shape); } pub fn deallocate(shape: *const T) void { shape.asShape().deallocate(); } pub fn destroy(shape: *const T) void { shape.asShape().destroy(); } pub fn deinit(shape: *const T) void { shape.asShape().deinit(); } pub fn isCreated(shape: *const T) bool { return shape.asShape().isCreated(); } pub fn getType(shape: *const T) ShapeType { return shape.asShape().getType(); } pub fn setMargin(shape: *const T, margin: f32) void { shape.asShape().setMargin(margin); } pub fn getMargin(shape: *const T) f32 { return shape.asShape().getMargin(); } pub fn isPolyhedral(shape: *const T) bool { return shape.asShape().isPolyhedral(); } pub fn isConvex2d(shape: *const T) bool { return shape.asShape().isConvex2d(); } pub fn isConvex(shape: *const T) bool { return shape.asShape().isConvex(); } pub fn isNonMoving(shape: *const T) bool { return shape.asShape().isNonMoving(); } pub fn isConcave(shape: *const T) bool { return shape.asShape().isConcave(); } pub fn isCompound(shape: *const T) bool { return shape.asShape().isCompound(); } pub fn calculateLocalInertia(shape: *const Shape, mass: f32, inertia: *[3]f32) void { shape.asShape().calculateLocalInertia(shape, mass, inertia); } pub fn setUserPointer(shape: *const T, ptr: ?*anyopaque) void { shape.asShape().setUserPointer(ptr); } pub fn getUserPointer(shape: *const T) ?*anyopaque { return shape.asShape().getUserPointer(); } pub fn setUserIndex(shape: *const T, slot: u32, index: i32) void { shape.asShape().setUserIndex(slot, index); } pub fn getUserIndex(shape: *const T, slot: u32) i32 { return shape.asShape().getUserIndex(slot); } }; } pub const BoxShape = opaque { pub fn init(half_extents: *const [3]f32) Error!*const BoxShape { const box = try allocate(); box.create(half_extents); return box; } pub fn allocate() Error!*const BoxShape { return @ptrCast(*const BoxShape, try Shape.allocate(.box)); } pub const create = cbtShapeBoxCreate; extern fn cbtShapeBoxCreate(box: *const BoxShape, half_extents: *const [3]f32) void; pub const getHalfExtentsWithoutMargin = cbtShapeBoxGetHalfExtentsWithoutMargin; extern fn cbtShapeBoxGetHalfExtentsWithoutMargin(box: *const BoxShape, half_extents: *[3]f32) void; pub const getHalfExtentsWithMargin = cbtShapeBoxGetHalfExtentsWithMargin; extern fn cbtShapeBoxGetHalfExtentsWithMargin(box: *const BoxShape, half_extents: *[3]f32) void; usingnamespace ShapeFunctions(@This()); }; pub const SphereShape = opaque { pub fn init(radius: f32) Error!*const SphereShape { const sphere = try allocate(); sphere.create(radius); return sphere; } pub fn allocate() Error!*const SphereShape { return @ptrCast(*const SphereShape, try Shape.allocate(.sphere)); } pub const create = cbtShapeSphereCreate; extern fn cbtShapeSphereCreate(sphere: *const SphereShape, radius: f32) void; pub const getRadius = cbtShapeSphereGetRadius; extern fn cbtShapeSphereGetRadius(sphere: *const SphereShape) f32; pub const setUnscaledRadius = cbtShapeSphereSetUnscaledRadius; extern fn cbtShapeSphereSetUnscaledRadius(sphere: *const SphereShape, radius: f32) void; usingnamespace ShapeFunctions(@This()); }; pub const CapsuleShape = opaque { pub fn init(radius: f32, height: f32, upaxis: Axis) Error!*const CapsuleShape { const capsule = try allocate(); capsule.create(radius, height, upaxis); return capsule; } pub fn allocate() Error!*const CapsuleShape { return @ptrCast(*const CapsuleShape, try Shape.allocate(.capsule)); } pub const create = cbtShapeCapsuleCreate; extern fn cbtShapeCapsuleCreate(capsule: *const CapsuleShape, radius: f32, height: f32, upaxis: Axis) void; pub const getUpAxis = cbtShapeCapsuleGetUpAxis; extern fn cbtShapeCapsuleGetUpAxis(capsule: *const CapsuleShape) Axis; pub const getHalfHeight = cbtShapeCapsuleGetHalfHeight; extern fn cbtShapeCapsuleGetHalfHeight(capsule: *const CapsuleShape) f32; pub const getRadius = cbtShapeCapsuleGetRadius; extern fn cbtShapeCapsuleGetRadius(capsule: *const CapsuleShape) f32; usingnamespace ShapeFunctions(@This()); }; pub const CylinderShape = opaque { pub fn init(half_extents: *const [3]f32, upaxis: Axis) Error!*const CylinderShape { const cylinder = try allocate(); cylinder.create(half_extents, upaxis); return cylinder; } pub fn allocate() Error!*const CylinderShape { return @ptrCast(*const CylinderShape, try Shape.allocate(.cylinder)); } pub const create = cbtShapeCylinderCreate; extern fn cbtShapeCylinderCreate(cylinder: *const CylinderShape, half_extents: *const [3]f32, upaxis: Axis) void; pub const getHalfExtentsWithoutMargin = cbtShapeCylinderGetHalfExtentsWithoutMargin; extern fn cbtShapeCylinderGetHalfExtentsWithoutMargin(cylinder: *const CylinderShape, half_extents: *[3]f32) void; pub const getHalfExtentsWithMargin = cbtShapeCylinderGetHalfExtentsWithMargin; extern fn cbtShapeCylinderGetHalfExtentsWithMargin(cylinder: *const CylinderShape, half_extents: *[3]f32) void; pub const getUpAxis = cbtShapeCylinderGetUpAxis; extern fn cbtShapeCylinderGetUpAxis(capsule: *const CylinderShape) Axis; usingnamespace ShapeFunctions(@This()); }; pub const CompoundShape = opaque { pub fn init( params: struct { enable_dynamic_aabb_tree: bool = true, initial_child_capacity: u32 = 0, }, ) Error!*const CompoundShape { const cshape = try allocate(); cshape.create(params.enable_dynamic_aabb_tree, params.initial_child_capacity); return cshape; } pub fn allocate() Error!*const CompoundShape { return @ptrCast(*const CompoundShape, try Shape.allocate(.compound)); } pub const create = cbtShapeCompoundCreate; extern fn cbtShapeCompoundCreate( cshape: *const CompoundShape, enable_dynamic_aabb_tree: bool, initial_child_capacity: u32, ) void; pub const addChild = cbtShapeCompoundAddChild; extern fn cbtShapeCompoundAddChild( cshape: *const CompoundShape, local_transform: *[12]f32, child_shape: *const Shape, ) void; pub const removeChild = cbtShapeCompoundRemoveChild; extern fn cbtShapeCompoundRemoveChild(cshape: *const CompoundShape, child_shape: *const Shape) void; pub const removeChildByIndex = cbtShapeCompoundRemoveChildByIndex; extern fn cbtShapeCompoundRemoveChildByIndex(cshape: *const CompoundShape, index: i32) void; pub const getNumChilds = cbtShapeCompoundGetNumChilds; extern fn cbtShapeCompoundGetNumChilds(cshape: *const CompoundShape) i32; pub const getChild = cbtShapeCompoundGetChild; extern fn cbtShapeCompoundGetChild(cshape: *const CompoundShape, index: i32) *const Shape; pub const getChildTransform = cbtShapeCompoundGetChildTransform; extern fn cbtShapeCompoundGetChildTransform( cshape: *const CompoundShape, index: i32, local_transform: *[12]f32, ) void; usingnamespace ShapeFunctions(@This()); }; pub const TriangleMeshShape = opaque { pub fn init() Error!*const TriangleMeshShape { const trimesh = try allocate(); trimesh.createBegin(); return trimesh; } pub fn finalize(trimesh: *const TriangleMeshShape) void { trimesh.createEnd(); } pub fn allocate() Error!*const TriangleMeshShape { return @ptrCast(*const TriangleMeshShape, try Shape.allocate(.trimesh)); } pub const addIndexVertexArray = cbtShapeTriMeshAddIndexVertexArray; extern fn cbtShapeTriMeshAddIndexVertexArray( trimesh: *const TriangleMeshShape, num_triangles: u32, triangles_base: *const anyopaque, triangle_stride: u32, num_vertices: u32, vertices_base: *const anyopaque, vertex_stride: u32, ) void; pub const createBegin = cbtShapeTriMeshCreateBegin; extern fn cbtShapeTriMeshCreateBegin(trimesh: *const TriangleMeshShape) void; pub const createEnd = cbtShapeTriMeshCreateEnd; extern fn cbtShapeTriMeshCreateEnd(trimesh: *const TriangleMeshShape) void; usingnamespace ShapeFunctions(@This()); }; pub const Body = opaque { pub fn init(mass: f32, transform: *const [12]f32, shape: *const Shape) Error!*const Body { const body = try allocate(); body.create(mass, transform, shape); return body; } pub fn deinit(body: *const Body) void { body.destroy(); body.deallocate(); } pub fn allocate() Error!*const Body { const ptr = cbtBodyAllocate(); if (ptr == null) { return error.OutOfMemory; } return ptr.?; } extern fn cbtBodyAllocate() ?*const Body; pub const deallocate = cbtBodyDeallocate; extern fn cbtBodyDeallocate(body: *const Body) void; pub const create = cbtBodyCreate; extern fn cbtBodyCreate(body: *const Body, mass: f32, transform: *const [12]f32, shape: *const Shape) void; pub const destroy = cbtBodyDestroy; extern fn cbtBodyDestroy(body: *const Body) void; pub const isCreated = cbtBodyIsCreated; extern fn cbtBodyIsCreated(body: *const Body) bool; pub const setShape = cbtBodySetShape; extern fn cbtBodySetShape(body: *const Body, shape: *const Shape) void; pub const getShape = cbtBodyGetShape; extern fn cbtBodyGetShape(body: *const Body) *const Shape; pub const setRestitution = cbtBodySetRestitution; extern fn cbtBodySetRestitution(body: *const Body, restitution: f32) void; pub const getRestitution = cbtBodyGetRestitution; extern fn cbtBodyGetRestitution(body: *const Body) f32; pub const getGraphicsWorldTransform = cbtBodyGetGraphicsWorldTransform; extern fn cbtBodyGetGraphicsWorldTransform(body: *const Body, transform: *[12]f32) void; }; pub const DebugMode = i32; pub const dbgmode_disabled: DebugMode = -1; pub const dbgmode_no_debug: DebugMode = 0; pub const dbgmode_draw_wireframe: DebugMode = 1; pub const dbgmode_draw_aabb: DebugMode = 2; pub const DebugDraw = extern struct { drawLine1: fn (?*anyopaque, *const [3]f32, *const [3]f32, *const [3]f32) callconv(.C) void, drawLine2: ?fn (?*anyopaque, *const [3]f32, *const [3]f32, *const [3]f32, *const [3]f32) callconv(.C) void, drawContactPoint: ?fn (?*anyopaque, *const [3]f32, *const [3]f32, f32, *const [3]f32) callconv(.C) void, context: ?*anyopaque, }; pub const DebugDrawer = struct { lines: std.ArrayList(Vertex), pub const Vertex = struct { position: [3]f32, color: u32, }; pub fn init(alloc: std.mem.Allocator) DebugDrawer { return .{ .lines = std.ArrayList(Vertex).init(alloc) }; } pub fn deinit(debug: *DebugDrawer) void { debug.lines.deinit(); debug.* = undefined; } pub fn getDebugDraw(debug: *DebugDrawer) DebugDraw { return .{ .drawLine1 = drawLine1, .drawLine2 = drawLine2, .drawContactPoint = null, .context = debug, }; } fn drawLine1( context: ?*anyopaque, p0: *const [3]f32, p1: *const [3]f32, color: *const [3]f32, ) callconv(.C) void { const debug = @ptrCast(*DebugDrawer, @alignCast(@alignOf(DebugDrawer), context.?)); const r = @floatToInt(u32, color[0] * 255.0); const g = @floatToInt(u32, color[1] * 255.0) << 8; const b = @floatToInt(u32, color[2] * 255.0) << 16; const rgb = r | g | b; debug.lines.append(.{ .position = .{ p0[0], p0[1], p0[2] }, .color = rgb }) catch unreachable; debug.lines.append(.{ .position = .{ p1[0], p1[1], p1[2] }, .color = rgb }) catch unreachable; } fn drawLine2( context: ?*anyopaque, p0: *const [3]f32, p1: *const [3]f32, color0: *const [3]f32, color1: *const [3]f32, ) callconv(.C) void { const debug = @ptrCast(*DebugDrawer, @alignCast(@alignOf(DebugDrawer), context.?)); const r0 = @floatToInt(u32, color0[0] * 255.0); const g0 = @floatToInt(u32, color0[1] * 255.0) << 8; const b0 = @floatToInt(u32, color0[2] * 255.0) << 16; const rgb0 = r0 | g0 | b0; const r1 = @floatToInt(u32, color1[0] * 255.0); const g1 = @floatToInt(u32, color1[1] * 255.0) << 8; const b1 = @floatToInt(u32, color1[2] * 255.0) << 16; const rgb1 = r1 | g1 | b1; debug.lines.append(.{ .position = .{ p0[0], p0[1], p0[2] }, .color = rgb0 }) catch unreachable; debug.lines.append(.{ .position = .{ p1[0], p1[1], p1[2] }, .color = rgb1 }) catch unreachable; } }; test "zbullet.world.gravity" { const zm = @import("zmath"); init(); defer deinit(); const world = try World.init(.{}); defer world.deinit(); world.setGravity(&.{ 0.0, -10.0, 0.0 }); const num_substeps = world.stepSimulation(1.0 / 60.0, .{}); try expect(num_substeps == 1); var gravity: [3]f32 = undefined; world.getGravity(&gravity); try expect(gravity[0] == 0.0 and gravity[1] == -10.0 and gravity[2] == 0.0); world.setGravity(&zm.vec3ToArray(zm.f32x4(1.0, 2.0, 3.0, 0.0))); world.getGravity(&gravity); try expect(gravity[0] == 1.0 and gravity[1] == 2.0 and gravity[2] == 3.0); } test "zbullet.shape.box" { init(); defer deinit(); { const box = try BoxShape.init(&.{ 4.0, 4.0, 4.0 }); defer box.deinit(); try expect(box.isCreated()); try expect(box.getType() == .box); box.setMargin(0.1); try expect(box.getMargin() == 0.1); var half_extents: [3]f32 = undefined; box.getHalfExtentsWithoutMargin(&half_extents); try expect(half_extents[0] == 3.9 and half_extents[1] == 3.9 and half_extents[2] == 3.9); box.getHalfExtentsWithMargin(&half_extents); try expect(half_extents[0] == 4.0 and half_extents[1] == 4.0 and half_extents[2] == 4.0); try expect(box.isPolyhedral() == true); try expect(box.isConvex() == true); box.setUserIndex(0, 123); try expect(box.getUserIndex(0) == 123); box.setUserPointer(null); try expect(box.getUserPointer() == null); box.setUserPointer(&half_extents); try expect(box.getUserPointer() == @ptrCast(*anyopaque, &half_extents)); const shape = box.asShape(); try expect(shape.getType() == .box); try expect(shape.isCreated()); } { const box = try BoxShape.allocate(); defer box.deallocate(); try expect(box.isCreated() == false); box.create(&.{ 1.0, 2.0, 3.0 }); defer box.destroy(); try expect(box.getType() == .box); try expect(box.isCreated() == true); } } test "zbullet.shape.sphere" { init(); defer deinit(); { const sphere = try SphereShape.init(3.0); defer sphere.deinit(); try expect(sphere.isCreated()); try expect(sphere.getType() == .sphere); sphere.setMargin(0.1); try expect(sphere.getMargin() == 3.0); // For spheres margin == radius. try expect(sphere.getRadius() == 3.0); sphere.setUnscaledRadius(1.0); try expect(sphere.getRadius() == 1.0); const shape = sphere.asShape(); try expect(shape.getType() == .sphere); try expect(shape.isCreated()); } { const sphere = try SphereShape.allocate(); errdefer sphere.deallocate(); try expect(sphere.isCreated() == false); sphere.create(1.0); try expect(sphere.getType() == .sphere); try expect(sphere.isCreated() == true); try expect(sphere.getRadius() == 1.0); sphere.destroy(); try expect(sphere.isCreated() == false); sphere.create(2.0); try expect(sphere.getType() == .sphere); try expect(sphere.isCreated() == true); try expect(sphere.getRadius() == 2.0); sphere.destroy(); try expect(sphere.isCreated() == false); sphere.deallocate(); } } test "zbullet.shape.capsule" { init(); defer deinit(); const capsule = try CapsuleShape.init(2.0, 1.0, .y); defer capsule.deinit(); try expect(capsule.isCreated()); try expect(capsule.getType() == .capsule); capsule.setMargin(0.1); try expect(capsule.getMargin() == 2.0); // For capsules margin == radius. try expect(capsule.getRadius() == 2.0); try expect(capsule.getHalfHeight() == 0.5); try expect(capsule.getUpAxis() == .y); } test "zbullet.shape.cylinder" { init(); defer deinit(); const cylinder = try CylinderShape.init(&.{ 1.0, 2.0, 3.0 }, .y); defer cylinder.deinit(); try expect(cylinder.isCreated()); try expect(cylinder.getType() == .cylinder); cylinder.setMargin(0.1); try expect(cylinder.getMargin() == 0.1); try expect(cylinder.getUpAxis() == .y); try expect(cylinder.isPolyhedral() == false); try expect(cylinder.isConvex() == true); var half_extents: [3]f32 = undefined; cylinder.getHalfExtentsWithoutMargin(&half_extents); try expect(half_extents[0] == 0.9 and half_extents[1] == 1.9 and half_extents[2] == 2.9); cylinder.getHalfExtentsWithMargin(&half_extents); try expect(half_extents[0] == 1.0 and half_extents[1] == 2.0 and half_extents[2] == 3.0); } test "zbullet.shape.compound" { const zm = @import("zmath"); init(); defer deinit(); const cshape = try CompoundShape.init(.{}); defer cshape.deinit(); try expect(cshape.isCreated()); try expect(cshape.getType() == .compound); try expect(cshape.isPolyhedral() == false); try expect(cshape.isConvex() == false); try expect(cshape.isCompound() == true); const sphere = try SphereShape.init(3.0); defer sphere.deinit(); const box = try BoxShape.init(&.{ 1.0, 2.0, 3.0 }); defer box.deinit(); cshape.addChild(&zm.mat43ToArray(zm.translation(1.0, 2.0, 3.0)), sphere.asShape()); cshape.addChild(&zm.mat43ToArray(zm.translation(-1.0, -2.0, -3.0)), box.asShape()); try expect(cshape.getNumChilds() == 2); try expect(cshape.getChild(0) == sphere.asShape()); try expect(cshape.getChild(1) == box.asShape()); var transform: [12]f32 = undefined; cshape.getChildTransform(1, &transform); const m = zm.loadMat43(transform[0..]); try expect(zm.approxEqAbs(m[0], zm.f32x4(1.0, 0.0, 0.0, 0.0), 0.0001)); try expect(zm.approxEqAbs(m[1], zm.f32x4(0.0, 1.0, 0.0, 0.0), 0.0001)); try expect(zm.approxEqAbs(m[2], zm.f32x4(0.0, 0.0, 1.0, 0.0), 0.0001)); try expect(zm.approxEqAbs(m[3], zm.f32x4(-1.0, -2.0, -3.0, 1.0), 0.0001)); cshape.removeChild(sphere.asShape()); try expect(cshape.getNumChilds() == 1); try expect(cshape.getChild(0) == box.asShape()); cshape.removeChildByIndex(0); try expect(cshape.getNumChilds() == 0); } test "zbullet.shape.trimesh" { init(); defer deinit(); const trimesh = try TriangleMeshShape.init(); const triangles = [3]u32{ 0, 1, 2 }; const vertices = [_]f32{0.0} ** 9; trimesh.addIndexVertexArray( 1, // num_triangles &triangles, // triangles_base 12, // triangle_stride 3, // num_vertices &vertices, // vertices_base 12, // vertex_stride ); trimesh.finalize(); defer trimesh.deinit(); try expect(trimesh.isCreated()); try expect(trimesh.isNonMoving()); try expect(trimesh.getType() == .trimesh); } test "zbullet.body.basic" { init(); defer deinit(); { const world = try World.init(.{}); defer world.deinit(); const sphere = try SphereShape.init(3.0); defer sphere.deinit(); const transform = [12]f32{ 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 2.0, 2.0, 2.0, }; const body = try Body.init(1.0, &transform, sphere.asShape()); defer body.deinit(); try expect(body.isCreated() == true); try expect(body.getShape() == sphere.asShape()); world.addBody(body); try expect(world.getNumBodies() == 1); try expect(world.getBody(0) == body); world.removeBody(body); try expect(world.getNumBodies() == 0); } { const zm = @import("zmath"); const sphere = try SphereShape.init(3.0); defer sphere.deinit(); var transform: [12]f32 = undefined; zm.storeMat43(transform[0..], zm.translation(2.0, 3.0, 4.0)); const body = try Body.init(1.0, &transform, sphere.asShape()); errdefer body.deinit(); try expect(body.isCreated() == true); try expect(body.getShape() == sphere.asShape()); body.destroy(); try expect(body.isCreated() == false); body.deallocate(); } { const zm = @import("zmath"); const sphere = try SphereShape.init(3.0); defer sphere.deinit(); const body = try Body.init( 0.0, // static body &zm.mat43ToArray(zm.translation(2.0, 3.0, 4.0)), sphere.asShape(), ); defer body.deinit(); var transform: [12]f32 = undefined; body.getGraphicsWorldTransform(&transform); const m = zm.loadMat43(transform[0..]); try expect(zm.approxEqAbs(m[0], zm.f32x4(1.0, 0.0, 0.0, 0.0), 0.0001)); try expect(zm.approxEqAbs(m[1], zm.f32x4(0.0, 1.0, 0.0, 0.0), 0.0001)); try expect(zm.approxEqAbs(m[2], zm.f32x4(0.0, 0.0, 1.0, 0.0), 0.0001)); try expect(zm.approxEqAbs(m[3], zm.f32x4(2.0, 3.0, 4.0, 1.0), 0.0001)); } }
libs/zbullet/src/zbullet.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); } const Arg = union(enum) { reg: u2, imm: i32, }; pub fn match_insn(comptime pattern: []const u8, text: []const u8) ?[2]Arg { comptime const argcount = blk: { var it = std.mem.split(u8, pattern, "{}"); var c: usize = 0; while (it.next()) |part| { c += 1; } break :blk c - 1; }; if (tools.match_pattern(pattern, text)) |vals| { var count: usize = 0; var values: [2]Arg = undefined; for (values[0..argcount]) |*v, i| { switch (vals[i]) { .imm => |imm| v.* = .{ .imm = @intCast(i32, imm) }, .name => |name| v.* = .{ .reg = @intCast(u2, name[0] - 'a') }, } } return values; } return null; } 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 limit = 1 * 1024 * 1024 * 1024; const text = try std.fs.cwd().readFileAlloc(allocator, "day23.txt", limit); defer allocator.free(text); const Opcode = enum { cpy, add, jnz, tgl, }; const Insn = struct { opcode: Opcode, arg: [2]Arg, }; var program: [500]Insn = undefined; var program_len: usize = 0; var it = std.mem.tokenize(u8, text, "\n"); while (it.next()) |line| { if (match_insn("cpy {} {}", line)) |vals| { trace("cpy {} {}\n", .{ vals[0], vals[1] }); program[program_len].opcode = .cpy; program[program_len].arg[0] = vals[0]; program[program_len].arg[1] = vals[1]; program_len += 1; } else if (match_insn("inc {}", line)) |vals| { trace("inc {}\n", .{vals[0]}); program[program_len].opcode = .add; program[program_len].arg[0] = Arg{ .imm = 1 }; program[program_len].arg[1] = vals[0]; program_len += 1; } else if (match_insn("dec {}", line)) |vals| { trace("dec {}\n", .{vals[0]}); program[program_len].opcode = .add; program[program_len].arg[0] = Arg{ .imm = -1 }; program[program_len].arg[1] = vals[0]; program_len += 1; } else if (match_insn("jnz {} {}", line)) |vals| { trace("jnz {} {}\n", .{ vals[0], vals[1] }); program[program_len].opcode = .jnz; program[program_len].arg[0] = vals[0]; program[program_len].arg[1] = vals[1]; program_len += 1; } else if (match_insn("tgl {}", line)) |vals| { trace("tgl {}\n", .{vals[0]}); program[program_len].opcode = .tgl; program[program_len].arg[0] = Arg{ .imm = 1 }; program[program_len].arg[1] = vals[0]; program_len += 1; } else { trace("skipping {}\n", .{line}); } } const Computer = struct { pc: usize, regs: [4]i32, }; var c = Computer{ .pc = 0, .regs = [_]i32{ 12, 0, 0, 0 } }; while (c.pc < program_len) { const insn = &program[c.pc]; //trace("executing {} {} {}\n", .{ insn.opcode, insn.arg[0], insn.arg[1] }); switch (insn.opcode) { .cpy => { if (insn.arg[1] == .reg) { c.regs[insn.arg[1].reg] = switch (insn.arg[0]) { .imm => |imm| imm, .reg => |reg| c.regs[reg], }; } c.pc += 1; }, .add => { if (insn.arg[1] == .reg) { c.regs[insn.arg[1].reg] += switch (insn.arg[0]) { .imm => |imm| imm, .reg => |reg| c.regs[reg], }; } c.pc += 1; }, .jnz => { const val = switch (insn.arg[0]) { .imm => |imm| imm, .reg => |reg| c.regs[reg], }; const offset = switch (insn.arg[1]) { .imm => |imm| imm, .reg => |reg| c.regs[reg], }; if (val != 0) { c.pc = @intCast(usize, @intCast(i32, c.pc) + offset); } else { c.pc += 1; } }, .tgl => { const val = switch (insn.arg[1]) { .imm => |imm| imm, .reg => |reg| c.regs[reg], }; if (@intCast(i32, c.pc) + val >= 0 and @intCast(i32, c.pc) + val < program_len) { const mod_insn = &program[@intCast(usize, @intCast(i32, c.pc) + val)]; switch (mod_insn.opcode) { .cpy => { mod_insn.opcode = .jnz; }, .add => { mod_insn.arg[0].imm *= -1; }, .jnz => { mod_insn.opcode = .cpy; }, .tgl => { mod_insn.opcode = .add; }, } } c.pc += 1; }, } } try stdout.print("a = {}\n", .{c.regs[0]}); }
2016/day23.zig
const std = @import("std"); const assert = std.debug.assert; const warn = std.debug.warn; const Allocator = std.mem.Allocator; const system = @import("../core/system.zig"); const entity = @import("../core/entity.zig"); usingnamespace @import("../main/util.zig"); const math3d = @import("math3d"); const SystemSetupContext = struct { max_entity_count: u16, allocator: *Allocator, entity_manager: *entity.EntityManager, }; const SystemTearDownContext = struct {}; const SystemUpdateContext = struct {}; const EntityCreateContext = struct { transform_components: []math3d.Mat4, transform_entities: []Entity, }; pub const TransformComponentInitData = struct { pos: math3d.Vec3, rot: math3d.Quaternion, }; pub const TransformSystem = struct { allocator: *Allocator = undefined, positions: []math3d.Vec3 = undefined, transforms: []math3d.Mat4 = undefined, fn setup(self: *TransformSystem, context: SystemSetupContext) void { self.allocator = context.allocator; self.positions = context.allocator.alloc(math3d.Vec3, context.max_entity_count) catch unreachable; for (self.positions) |*pos| pos.* = math3d.Vec3.zero; std.debug.warn("setup"); context.entity_manager.registerComponent(math3d.Vec3, "transform_position_comp"); } fn tearDown(self: *TransformSystem, context: SystemTearDownContext) void { self.allocator.free(self.positions); std.debug.warn("freeee"); } fn update(self: *TransformSystem, context: SystemUpdateContext) void {} fn entityCreate(self: *TransformSystem, context: EntityCreateContext) void { for (context.transform_position_comp.entities) |ent, index| { self.transforms[ent] = context.transform_position_comp.components[index]; } } fn entityDestroy(self: *TransformSystem, context: EntityDestroyContext) void { if (std.builtin.mode != .Debug) { return; } for (context.transform_position_comp.entities) |ent, index| { self.transforms[ent] = math3d.Mat4.zero; } } }; const funcWrap = system.systemFunctionWrap; const funcs = [_]system.SystemFuncDef{ system.SystemFuncDef{ .pass = "setup", .phase = 0, .func = funcWrap(TransformSystem, TransformSystem.setup, Context), }, system.SystemFuncDef{ .pass = "teardown", .phase = 0, .func = funcWrap(TransformSystem, TransformSystem.tearDown, Context), }, system.SystemFuncDef{ .pass = "update", .phase = 0, .func = funcWrap(TransformSystem, TransformSystem.update, Context), }, system.SystemFuncDef{ .pass = "entity_create", .phase = 0, .func = funcWrap(TransformSystem, TransformSystem.entityCreate, EntityCreateContext), }, }; pub fn init(name: []const u8, allocator: *Allocator) system.System { var ts = allocator.create(TransformSystem) catch unreachable; var sys = system.System.init(name, funcs, @ptrCast(*system.SystemSelf, ts)); return sys; } pub fn deinit(sys: *System, allocator: *Allocator) void { allocator.destroy(sys.*.self); }
code/systems/transform_system.zig
const std = @import("std"); const argsParser = @import("args"); const ihex = @import("ihex"); const spu = @import("spu-mk2"); const Instruction = spu.Instruction; const FileFormat = enum { ihex, binary }; pub fn main() !u8 { const cli_args = argsParser.parseForCurrentProcess(struct { help: bool = false, format: FileFormat = .ihex, output: []const u8 = "a.out", map: bool = false, pub const shorthands = .{ .h = "help", .f = "format", .o = "output", .m = "map", }; }, std.heap.page_allocator, .print) catch return 1; defer cli_args.deinit(); if (cli_args.options.help or cli_args.positionals.len == 0) { try std.io.getStdOut().writer().writeAll( \\assembler --help [--format ihex|binary] [--output file] fileA fileB … \\Assembles code for the SPU Mark II platform. \\ \\-h, --help Displays this help text. \\-f, --format Selects the output format (binary or ihex). \\ If not given, the assembler will emit raw binaries. \\-o, --output Defines the name of the output file. If not given, \\ the assembler will chose a.out as the output file name. \\-m, --map Output all global symbols to stdout \\ ); return if (cli_args.options.help) @as(u8, 0) else @as(u8, 1); } var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); var assembler = try Assembler.init(arena.allocator()); defer assembler.deinit(); var root_dir = try std.fs.cwd().openDir(".", .{ .access_sub_paths = true, .iterate = false }); defer root_dir.close(); for (cli_args.positionals) |path| { var file = try root_dir.openFile(path, .{ .read = true, .write = false }); defer file.close(); var dir = try root_dir.openDir(std.fs.path.dirname(path) orelse ".", .{ .access_sub_paths = true, .iterate = false }); defer dir.close(); try assembler.assemble(path, dir, file.reader()); } try assembler.finalize(); if (assembler.errors.items.len > 0) { const stdout = std.io.getStdOut().writer(); try stdout.writeAll("Errors appeared while assembling:\n"); for (assembler.errors.items) |err| { const file_name = if (err.location) |loc| loc.file orelse "unknown" else "unknown"; if (err.location) |loc| { try stdout.print("{s}: {s}:{}:{}: {s}\n", .{ @tagName(err.type), file_name, loc.line, loc.column, err.message, }); } else { try stdout.print("{s}: {s}:{}:{}: {s}\n", .{ @tagName(err.type), file_name, 0, 0, err.message, }); } } return 1; } if (cli_args.options.map) { var stdout = std.io.getStdOut().writer(); var it = assembler.symbols.iterator(); while (it.next()) |entry| { try stdout.print("{s}\t0x{X:0>4}\n", .{ entry.key_ptr.*, @bitCast(u64, try entry.value_ptr.getValue()), }); } } { var file = try root_dir.createFile(cli_args.options.output, .{ .truncate = true, .exclusive = false }); defer file.close(); var outstream = file.writer(); switch (cli_args.options.format) { .binary => { var iter = assembler.sections.first; while (iter) |section_node| : (iter = section_node.next) { const section = &section_node.data; try file.seekTo(section.phys_offset); try file.writeAll(section.bytes.items); } }, .ihex => { var iter = assembler.sections.first; while (iter) |section_node| : (iter = section_node.next) { const section = &section_node.data; var i: usize = 0; while (i < section.bytes.items.len) : (i += 16) { const length = std.math.min(section.bytes.items.len - i, 16); const source = section.bytes.items[i..][0..length]; var buffer: [256 + 5]u8 = undefined; std.mem.writeIntBig(u8, buffer[0..][0..1], @intCast(u8, length)); std.mem.writeIntBig(u16, buffer[1..][0..2], @intCast(u16, section.phys_offset + i)); std.mem.writeIntBig(u8, buffer[3..][0..1], 0x00); // data record std.mem.copy(u8, buffer[4..], source); var checksum: u8 = 0; for (buffer[0 .. 4 + length]) |b| { checksum -%= b; } std.mem.writeIntBig(u8, buffer[4 + length ..][0..1], checksum); // data record // data records try outstream.print( ":{}\n", .{std.fmt.fmtSliceHexUpper(buffer[0 .. length + 5])}, ); } } // file/stream terminator try outstream.writeAll(":00000001FF\n"); }, } } return 0; } pub const Patch = struct { offset: u16, value: Expression, locals: *std.StringHashMap(Symbol), }; pub const Section = struct { const Self = @This(); load_offset: u16, phys_offset: u32, bytes: std.ArrayList(u8), patches: std.ArrayList(Patch), dot_offset: u16, fn deinit(self: *Self) void { self.bytes.deinit(); for (self.patches.items) |*patch| { patch.value.deinit(); } self.patches.deinit(); self.* = undefined; } fn getLocalOffset(sect: Self) u16 { return @intCast(u16, sect.bytes.items.len); } fn getGlobalOffset(sect: Self) u16 { return @intCast(u16, sect.load_offset + sect.bytes.items.len); } fn getDotOffset(sect: Self) u16 { return sect.dot_offset; } }; pub const CompileError = struct { pub const Type = enum { @"error", warning }; location: ?Location, message: []const u8, type: Type, pub fn format(err: CompileError, comptime fmt: []const u8, options: std.fmt.FormatOptions, stream: anytype) !void { _ = fmt; _ = options; try stream.print("{}: {s}: {s}", .{ err.location, @tagName(err.type), err.message, }); } }; pub const Symbol = struct { /// The value of the symbol. If a section is given, this is the relative offset inside the /// section. Otherwise, it's a global offset. value: i64, section: ?*Section, pub fn getPhysicalAddress(self: Symbol) !u32 { const sect = self.section orelse return error.InvalidSymbol; return try std.math.cast(u32, sect.phys_offset + self.value); } pub fn getValue(self: Symbol) !i64 { return if (self.section) |sect| sect.load_offset + self.value else self.value; } }; pub const Assembler = struct { const Self = @This(); const SectionNode = std.TailQueue(Section).Node; // utilities allocator: std.mem.Allocator, string_cache: StringCache, arena: std.heap.ArenaAllocator, // assembling result sections: std.TailQueue(Section), symbols: std.StringHashMap(Symbol), local_symbols: *std.StringHashMap(Symbol), errors: std.ArrayList(CompileError), // in-flight symbols fileName: []const u8, directory: ?std.fs.Dir, fn appendSection(assembler: *Assembler, load_offset: u16, phys_offset: u32) !*Section { var node = try assembler.allocator.create(SectionNode); errdefer assembler.allocator.destroy(node); node.* = SectionNode{ .data = Section{ .load_offset = load_offset, .phys_offset = phys_offset, .bytes = std.ArrayList(u8).init(assembler.allocator), .patches = std.ArrayList(Patch).init(assembler.allocator), .dot_offset = load_offset, }, }; assembler.sections.append(node); return &node.data; } fn currentSection(assembler: *Assembler) *Section { return &(assembler.sections.last orelse unreachable).data; } pub fn init(allocator: std.mem.Allocator) !Assembler { var a = Self{ .allocator = allocator, .sections = std.TailQueue(Section){}, .symbols = std.StringHashMap(Symbol).init(allocator), .local_symbols = undefined, .errors = std.ArrayList(CompileError).init(allocator), .fileName = undefined, .directory = undefined, .string_cache = StringCache.init(allocator), .arena = std.heap.ArenaAllocator.init(allocator), }; errdefer a.arena.deinit(); errdefer a.string_cache.deinit(); a.local_symbols = try a.arena.allocator().create(std.StringHashMap(Symbol)); a.local_symbols.* = std.StringHashMap(Symbol).init(a.arena.allocator()); _ = try a.appendSection(0x0000, 0x0000_0000); return a; } pub fn deinit(self: *Self) void { while (self.sections.pop()) |sect| { sect.data.deinit(); self.allocator.destroy(sect); } self.string_cache.deinit(); self.arena.deinit(); self.symbols.deinit(); self.* = undefined; } pub fn finalize(self: *Self) !void { var iter = self.sections.first; while (iter) |section_node| : (iter = section_node.next) { const section = &section_node.data; for (section.patches.items) |patch| { self.local_symbols = patch.locals; // hacky const value = self.evaluate(patch.value, true) catch |err| switch (err) { error.MissingIdentifiers => continue, else => return err, }; const patch_value = value.toWord(self) catch 0xAAAA; std.mem.writeIntLittle(u16, section.bytes.items[patch.offset..][0..2], patch_value); } for (section.patches.items) |*patch| { patch.value.deinit(); } section.patches.shrinkRetainingCapacity(0); } } fn emitError(self: *Self, kind: CompileError.Type, location: ?Location, comptime fmt: []const u8, args: anytype) !void { const msg = try std.fmt.allocPrint(self.string_cache.string_arena.allocator(), fmt, args); errdefer self.allocator.free(msg); var location_clone = location; if (location_clone) |*l| { l.file = try self.string_cache.internString(self.fileName); } try self.errors.append(CompileError{ .location = location_clone, .type = kind, .message = msg, }); } const AssembleError = std.fs.File.OpenError || std.fs.File.ReadError || std.fs.File.SeekError || EvaluationError || Parser.ParseError || error{ UnexpectedEndOfFile, UnrecognizedCharacter, IncompleteStringLiteral, UnexpectedToken, OutOfMemory, UnknownMnemonic, UnexpectedOperand, DuplicateModifier, InvalidModifier, OutOfRange, UnknownDirective, DuplicateSymbol, EndOfStream, StreamTooLong, ParensImbalance, }; pub fn assemble(self: *Assembler, fileName: []const u8, directory: ?std.fs.Dir, stream: anytype) AssembleError!void { var parser = try Parser.fromStream(&self.string_cache, self.allocator, stream); defer parser.deinit(); self.fileName = fileName; self.directory = directory; while (true) { const token = try parser.peek(); if (token == null) // end of file break; // Update the dot offset to the start of the next *thing*. self.currentSection().dot_offset = self.currentSection().getGlobalOffset(); switch (token.?.type) { // process directive .dot_identifier => try parseDirective(self, &parser), // label, .label => { const label = try parser.expect(.label); const name = try self.string_cache.internString(label.text[0 .. label.text.len - 1]); const section = self.currentSection(); const offset = section.getLocalOffset(); const symbol = Symbol{ .value = offset, .section = section, }; if (name[0] == '.') { // local label try self.local_symbols.put(name, symbol); } else { // global label self.local_symbols = try self.arena.allocator().create(std.StringHashMap(Symbol)); self.local_symbols.* = std.StringHashMap(Symbol).init(self.arena.allocator()); try self.symbols.put(name, symbol); } }, // modifier .identifier, .opening_brackets => try parseInstruction(self, &parser), // empty line, skip those .line_break => _ = try parser.expect(.line_break), else => return error.UnexpectedToken, } } self.fileName = undefined; self.directory = null; } fn getInstructionForMnemonic(name: []const u8, argc: usize) ?Instruction { const mnemonics = @import("mnemonics.zig").mnemonics; for (mnemonics) |mnemonic| { if (mnemonic.argc == argc and std.mem.eql(u8, mnemonic.name, name)) return mnemonic.instruction; } return null; } fn parseInstruction(assembler: *Assembler, parser: *Parser) !void { var modifiers = Modifiers{}; var instruction_token: ?Token = null; // parse modifiers and while (true) { var tok = try parser.expectAny(.{ .identifier, // label or equ .opening_brackets, // modifier }); switch (tok.type) { .identifier => { instruction_token = tok; break; }, .opening_brackets => try modifiers.parse(assembler, parser), else => unreachable, // parse expression } } var operands: [2]Expression = undefined; var operand_count: usize = 0; var end_of_operands = false; // parse modifiers and operands while (true) { var tok = try parser.peek(); if (tok == null) break; switch (tok.?.type) { .line_break => { _ = parser.expect(.line_break) catch unreachable; break; }, .opening_brackets => { _ = parser.expect(.opening_brackets) catch unreachable; try modifiers.parse(assembler, parser); }, else => { if (operand_count >= operands.len or end_of_operands) { return error.UnexpectedOperand; } const expr_result = try parser.parseExpression(assembler.allocator, .{ .line_break, .comma, .opening_brackets }); operands[operand_count] = expr_result.expression; operand_count += 1; switch (expr_result.terminator.type) { .line_break => break, .opening_brackets => { try modifiers.parse(assembler, parser); end_of_operands = true; }, .comma => {}, else => unreachable, } }, } } // search for instruction template var instruction = getInstructionForMnemonic(instruction_token.?.text, operand_count) orelse { return try assembler.emitError(.@"error", instruction_token.?.location, "Unknown mnemonic: {s}", .{instruction_token.?.text}); }; // apply modifiers inline for (std.meta.fields(Modifiers)) |fld| { if (@field(modifiers, fld.name)) |mod| { @field(instruction, fld.name) = mod; } } // emit results try assembler.emitU16(@bitCast(u16, instruction)); { var i: usize = 0; while (i < operand_count) : (i += 1) { try assembler.emitExpr(operands[i]); } } } fn parseDirective(assembler: *Self, parser: *Parser) !void { var token = try parser.expect(.dot_identifier); inline for (std.meta.declarations(Directives)) |decl| { if (decl.data != .Fn) continue; if (decl.name[0] != '.') continue; if (std.mem.eql(u8, decl.name, token.text)) { try @field(Directives, decl.name)(assembler, parser); return; } } if (@import("builtin").mode == .Debug) { std.log.warn("unknown directive: {s}\n", .{token.text}); } return error.UnknownDirective; } const FunctionCallError = error{ OutOfMemory, TypeMismatch, InvalidArgument, WrongArgumentCount }; const Functions = struct { fn substr(assembler: *Assembler, argv: []const Value) FunctionCallError!Value { switch (argv.len) { 2 => { const str = try argv[0].toString(assembler); const start = try argv[1].toLong(assembler); return if (start < str.len) Value{ .string = str[start..] } else Value{ .string = "" }; }, 3 => { const str = try argv[0].toString(assembler); const start = try argv[1].toLong(assembler); const length = try argv[2].toLong(assembler); const offset_str = if (start < str.len) str[start..] else ""; const len = std.math.min(offset_str.len, length); return Value{ .string = offset_str[0..len] }; }, else => return error.WrongArgumentCount, } } fn physicalAddress(assembler: *Assembler, argv: []const Value) FunctionCallError!Value { if (argv.len != 1) return error.WrongArgumentCount; const symbol_name = try argv[0].toString(assembler); const lut = if (std.mem.startsWith(u8, symbol_name, ".")) assembler.local_symbols.* else assembler.symbols; if (lut.get(symbol_name)) |sym| { const value = sym.getPhysicalAddress() catch |err| { err catch {}; return error.InvalidArgument; }; return Value{ .number = value, }; } else { return error.InvalidArgument; } } }; const Directives = struct { fn @".org"(assembler: *Assembler, parser: *Parser) !void { const offset_expr = try parser.parseExpression(assembler.allocator, .{ .line_break, .comma }); const physical_expr = if (offset_expr.terminator.type == .comma) // parse the physical offset expr here try parser.parseExpression(assembler.allocator, .{.line_break}) else null; const load_offset_val = try assembler.evaluate(offset_expr.expression, true); const phys_offset_val = if (physical_expr) |expr| try assembler.evaluate(expr.expression, true) else null; const load_offset = load_offset_val.toWord(assembler) catch return; const phys_offset = if (phys_offset_val) |val| val.toLong(assembler) catch return else null; const sect = if (assembler.currentSection().bytes.items.len == 0) assembler.currentSection() else try assembler.appendSection(load_offset, phys_offset orelse load_offset); sect.load_offset = load_offset; sect.phys_offset = phys_offset orelse load_offset; } fn @".ascii"(assembler: *Assembler, parser: *Parser) !void { var string_expr = try parser.parseExpression(assembler.allocator, .{.line_break}); defer string_expr.expression.deinit(); const string_val = try assembler.evaluate(string_expr.expression, true); const string = string_val.toString(assembler) catch return; try assembler.emit(string); } fn @".asciiz"(assembler: *Assembler, parser: *Parser) !void { var string_expr = try parser.parseExpression(assembler.allocator, .{.line_break}); defer string_expr.expression.deinit(); const string_val = try assembler.evaluate(string_expr.expression, true); const string = string_val.toString(assembler) catch return; try assembler.emit(string); try assembler.emitU8(0x00); // null terminator } fn @".align"(assembler: *Assembler, parser: *Parser) !void { const alignment_expr = try parser.parseExpression(assembler.allocator, .{.line_break}); const alignment_val = try assembler.evaluate(alignment_expr.expression, true); const alignment = alignment_val.toWord(assembler) catch return; const sect = assembler.currentSection(); const newSize = std.mem.alignForward(sect.bytes.items.len, alignment); if (newSize != sect.bytes.items.len) { try sect.bytes.appendNTimes(0x00, newSize - sect.bytes.items.len); } std.debug.assert(sect.bytes.items.len == newSize); } fn @".space"(assembler: *Assembler, parser: *Parser) !void { const size_expr = try parser.parseExpression(assembler.allocator, .{.line_break}); const size_val = try assembler.evaluate(size_expr.expression, true); const size = size_val.toWord(assembler) catch return; const sect = assembler.currentSection(); try sect.bytes.appendNTimes(0x00, size); } fn @".dw"(assembler: *Assembler, parser: *Parser) !void { while (true) { const value_expr = try parser.parseExpression(assembler.allocator, .{ .line_break, .comma }); try assembler.emitExpr(value_expr.expression); if (value_expr.terminator.type == .line_break) break; } } fn @".db"(assembler: *Assembler, parser: *Parser) !void { while (true) { var value_expr = try parser.parseExpression(assembler.allocator, .{ .line_break, .comma }); defer value_expr.expression.deinit(); const byte_val = try assembler.evaluate(value_expr.expression, true); try assembler.emitU8(if (byte_val.toByte(assembler)) |byte| byte else |_| 0xAA); if (value_expr.terminator.type == .line_break) break; } } fn @".equ"(assembler: *Assembler, parser: *Parser) !void { const name_tok = try parser.expect(.identifier); _ = try parser.expect(.comma); const name = try assembler.string_cache.internString(name_tok.text); var value_expr = try parser.parseExpression(assembler.allocator, .{.line_break}); defer value_expr.expression.deinit(); const equ_val = try assembler.evaluate(value_expr.expression, true); // TODO: Decide whether unreferenced symbol or invalid value is better! const equ = equ_val.toNumber(assembler) catch 0xAAAA; // TODO: reinclude duplicatesymbol try assembler.symbols.put(name, Symbol{ .value = equ, .section = null }); } fn @".incbin"(assembler: *Assembler, parser: *Parser) !void { const filename_expr = try parser.parseExpression(assembler.allocator, .{.line_break}); const filename = try assembler.evaluate(filename_expr.expression, true); if (filename != .string) return error.TypeMismatch; if (assembler.directory) |dir| { var blob = try dir.readFileAlloc(assembler.allocator, filename.string, 65536); defer assembler.allocator.free(blob); try assembler.currentSection().bytes.writer().writeAll(blob); } else { try assembler.emitError(.@"error", filename_expr.expression.location, "Cannot open file {s}: No filesystem available", .{filename.string}); } } fn @".include"(assembler: *Assembler, parser: *Parser) !void { const filename_expr = try parser.parseExpression(assembler.allocator, .{.line_break}); const filename = try assembler.evaluate(filename_expr.expression, true); if (filename != .string) return error.TypeMismatch; if (assembler.directory) |dir| { var file = dir.openFile(filename.string, .{ .read = true, .write = false }) catch |err| switch (err) { error.FileNotFound => { try assembler.emitError(.@"error", filename_expr.expression.location, "Cannot open file {s}: File not found.", .{filename.string}); return; }, else => |e| return e, }; defer file.close(); const old_file_name = assembler.fileName; defer assembler.fileName = old_file_name; defer assembler.directory = dir; var new_dir = try dir.openDir(std.fs.path.dirname(filename.string) orelse ".", .{ .access_sub_paths = true, .iterate = false }); defer new_dir.close(); try assembler.assemble(filename.string, new_dir, file.reader()); } else { try assembler.emitError(.@"error", filename_expr.expression.location, "Cannot open file {s}: No filesystem available", .{filename}); } } }; // Output handling: fn emit(assembler: *Assembler, bytes: []const u8) !void { const sect = assembler.currentSection(); try sect.bytes.writer().writeAll(bytes); } fn emitU8(assembler: *Assembler, value: u8) !void { const bytes = [1]u8{value}; try assembler.emit(&bytes); } fn emitU16(assembler: *Assembler, value: u16) !void { var bytes: [2]u8 = undefined; std.mem.writeIntLittle(u16, &bytes, value); try assembler.emit(&bytes); } // Consumes a expression and takes ownership of its resources fn emitExpr(assembler: *Assembler, expression: Expression) !void { var copy = expression; errdefer copy.deinit(); if (assembler.evaluate(copy, false)) |value| { const int_val = value.toWord(assembler) catch 0xAAAA; try assembler.emitU16(int_val); copy.deinit(); } else |err| switch (err) { error.MissingIdentifiers => { const sect = assembler.currentSection(); const ptr = sect.getLocalOffset(); // Defer evaluation to end of assembling, // store label context (for locals) and expr for later, write dummy value try assembler.emitU16(0x5555); try sect.patches.append(Patch{ .offset = ptr, .value = copy, .locals = assembler.local_symbols, }); }, else => return err, } } // Expression handling const EvaluationError = FunctionCallError || error{ InvalidExpression, UnknownFunction, MissingIdentifiers, OutOfMemory, TypeMismatch, Overflow, InvalidCharacter }; fn evaluate(assembler: *Assembler, expression: Expression, emitErrorOnMissing: bool) EvaluationError!Value { return try expression.evaluate(assembler, emitErrorOnMissing); // .operator_plus => { // const rhs = stack.popOrNull() orelse return error.InvalidExpression; // const lhs = stack.popOrNull() orelse return error.InvalidExpression; // if (@as(ValueType, lhs) != @as(ValueType, rhs)) // return error.TypeMismatch; // try stack.append(switch (lhs) { // .number => Value{ .number = lhs.number +% rhs.number }, // .string => Value{ // .string = try std.mem.concat(assembler.allocator, u8, &[_][]const u8{ // lhs.string, // rhs.string, // }), // }, // }); // }, // } // } } }; const StringCache = struct { const Self = @This(); string_arena: std.heap.ArenaAllocator, interned_strings: std.StringHashMap(void), scratch_buffer: std.ArrayList(u8), pub fn init(allocator: std.mem.Allocator) Self { return .{ .string_arena = std.heap.ArenaAllocator.init(allocator), .interned_strings = std.StringHashMap(void).init(allocator), .scratch_buffer = std.ArrayList(u8).init(allocator), }; } pub fn deinit(self: *Self) void { self.interned_strings.deinit(); self.string_arena.deinit(); self.scratch_buffer.deinit(); self.* = undefined; } const EscapingResult = struct { char: u8, length: usize, }; fn translateEscapedChar(pattern: []const u8) !EscapingResult { if (pattern[0] != '\\') return EscapingResult{ .char = pattern[0], .length = 1 }; return EscapingResult{ .length = 2, .char = switch (pattern[1]) { 'a' => 0x07, 'b' => 0x08, 'e' => 0x1B, 'n' => 0x0A, 'r' => 0x0D, 't' => 0x0B, '\\' => 0x5C, '\'' => 0x27, '\"' => 0x22, 'x' => { return EscapingResult{ .length = 4, .char = std.fmt.parseInt(u8, pattern[2..4], 16) catch |err| switch (err) { error.Overflow => unreachable, // 2 hex chars can never overflow a byte! else => |e| return e, }, }; }, else => |c| c, }, }; } pub fn escapeAndInternString(self: *Self, raw_string: []const u8) ![]const u8 { self.scratch_buffer.shrinkRetainingCapacity(0); // we can safely resize the buffer here to the source string length, as // in the worst case, we will not change the size and in the best case we will // be left with 1/4th of the char count (\x??) try self.scratch_buffer.ensureTotalCapacity(raw_string.len); var offset: usize = 0; while (offset < raw_string.len) { const c = try translateEscapedChar(raw_string[offset..]); offset += c.length; self.scratch_buffer.append(c.char) catch unreachable; } return try self.internString(self.scratch_buffer.items); } pub fn internString(self: *Self, string: []const u8) ![]const u8 { const gop = try self.interned_strings.getOrPut(string); if (!gop.found_existing) { gop.key_ptr.* = try self.string_arena.allocator().dupe(u8, string); } return gop.key_ptr.*; } }; pub const TokenType = enum { const Self = @This(); whitespace, comment, // ; … line_break, // "\n" identifier, // fooas2_3 dot_identifier, // .fooas2_3 label, //foobar:, .foobar: function, // #symbol bin_number, // 0b0000 oct_number, // 0o0000 dec_number, // 0000 hex_number, // 0x0000 char_literal, // 'A', '\n' string_literal, // "Abc", "a\nc" dot, // . colon, // : comma, // , opening_parens, // ( closing_parens, // ) opening_brackets, // [ closing_brackets, // ] operator_plus, // + operator_minus, // - operator_multiply, // * operator_divide, // / operator_modulo, // % operator_bitand, // & operator_bitor, // | operator_bitxor, // ^ operator_shl, // << operator_shr, // >> operator_asr, // >>> operator_bitnot, // ~ fn isOperator(self: Self) bool { return switch (self) { .operator_plus, .operator_minus, .operator_multiply, .operator_divide, .operator_modulo, .operator_bitand, .operator_bitor, .operator_bitxor, .operator_shl, .operator_shr, .operator_asr, .operator_bitnot => true, else => false, }; } }; pub const Location = struct { file: ?[]const u8, line: u32, column: u32, fn merge(a: Location, b: Location) Location { std.debug.assert(std.meta.eql(a.file, b.file)); return if (a.line < b.line) a else if (a.line > b.line) b else if (a.column < b.column) a else b; } }; pub const Token = struct { const Self = @This(); text: []const u8, type: TokenType, location: Location, fn duplicate(self: Self, allocator: std.mem.Allocator) !Self { return Self{ .type = self.type, .text = try std.mem.dupe(allocator, u8, self.text), .location = self.location, }; } }; pub const Parser = struct { allocator: ?std.mem.Allocator, string_cache: *StringCache, source: []u8, offset: usize, peeked_token: ?Token, current_location: Location, const Self = @This(); fn fromStream(string_cache: *StringCache, allocator: std.mem.Allocator, stream: anytype) !Self { return Self{ .string_cache = string_cache, .allocator = allocator, .source = try stream.readAllAlloc(allocator, 16 << 20), // 16 MB .offset = 0, .peeked_token = null, .current_location = Location{ .line = 1, .column = 1, .file = null, }, }; } fn fromSlice(string_cache: *StringCache, text: []const u8) Self { return Self{ .string_cache = string_cache, .allocator = null, .source = text, .offset = 0, .peeked_token = null, .current_location = Location{ .line = 1, .column = 1, .file = null, }, }; } fn deinit(self: *Self) void { if (self.allocator) |a| a.free(self.source); self.* = undefined; } fn expect(parser: *Self, t: TokenType) !Token { var state = parser.saveState(); errdefer parser.restoreState(state); const tok = (try parser.parse()) orelse return error.UnexpectedEndOfFile; if (tok.type == t) return tok; if (@import("builtin").mode == .Debug) { // std.debug.warn("Unexpected token: {}\nexpected: {}\n", .{ // tok, // t, // }); } return error.UnexpectedToken; } fn expectAny(parser: *Self, types: anytype) !Token { var state = parser.saveState(); errdefer parser.restoreState(state); const tok = (try parser.parse()) orelse return error.UnexpectedEndOfFile; inline for (types) |t| { if (tok.type == @as(TokenType, t)) return tok; } // if (std.builtin.mode == .Debug) { // std.debug.warn("Unexpected token: {}\nexpected one of: {}\n", .{ // tok, // types, // }); // } return error.UnexpectedToken; } fn peek(parser: *Self) !?Token { if (parser.peeked_token) |tok| { return tok; } parser.peeked_token = try parser.parse(); return parser.peeked_token; } fn parse(parser: *Self) !?Token { if (parser.peeked_token) |tok| { parser.peeked_token = null; return tok; } while (true) { var token = try parser.parseRaw(); if (token) |tok| { switch (tok.type) { .whitespace => continue, .comment => continue, else => return tok, } } else { return null; } } } fn singleCharToken(parser: *Self, t: TokenType) Token { return Token{ .text = parser.source[parser.offset..][0..1], .type = t, .location = parser.current_location, }; } fn isWordCharacter(c: u8) bool { return switch (c) { 'a'...'z' => true, 'A'...'Z' => true, '0'...'9' => true, '_' => true, '.' => true, else => false, }; } fn isDigit(c: u8, number_format: TokenType) bool { return switch (number_format) { .dec_number => switch (c) { '0'...'9' => true, else => false, }, .oct_number => switch (c) { '0'...'7' => true, else => false, }, .bin_number => switch (c) { '0', '1' => true, else => false, }, .hex_number => switch (c) { '0'...'9' => true, 'a'...'f' => true, 'A'...'F' => true, else => false, }, else => unreachable, }; } fn parseRaw(parser: *Self) !?Token { // Return a .line_break when we reached the end of the file // Prevents a whole class of errors in the rest of the code :) if (parser.offset == parser.source.len) { parser.offset += 1; return Token{ .text = "\n", .type = .line_break, .location = parser.current_location, }; } else if (parser.offset >= parser.source.len) { return null; } var token = switch (parser.source[parser.offset]) { '\n' => parser.singleCharToken(.line_break), ' ', '\t', '\r' => parser.singleCharToken(.whitespace), ';' => blk: { var off = parser.offset; while (off < parser.source.len and parser.source[off] != '\n') { off += 1; } break :blk Token{ .type = .comment, .text = parser.source[parser.offset..off], .location = parser.current_location, }; }, ':' => parser.singleCharToken(.colon), ',' => parser.singleCharToken(.comma), '(' => parser.singleCharToken(.opening_parens), ')' => parser.singleCharToken(.closing_parens), '[' => parser.singleCharToken(.opening_brackets), ']' => parser.singleCharToken(.closing_brackets), '+' => parser.singleCharToken(.operator_plus), '-' => parser.singleCharToken(.operator_minus), '*' => parser.singleCharToken(.operator_multiply), '/' => parser.singleCharToken(.operator_divide), '%' => parser.singleCharToken(.operator_modulo), '&' => parser.singleCharToken(.operator_bitand), '|' => parser.singleCharToken(.operator_bitor), '^' => parser.singleCharToken(.operator_bitxor), '~' => parser.singleCharToken(.operator_bitnot), '.' => if (parser.offset + 1 >= parser.source.len or !isWordCharacter(parser.source[parser.offset + 1])) parser.singleCharToken(.dot) else blk: { var off = parser.offset + 1; while (off < parser.source.len and isWordCharacter(parser.source[off])) { off += 1; } if (off < parser.source.len and parser.source[off] == ':') { off += 1; break :blk Token{ .type = .label, .text = parser.source[parser.offset..off], .location = parser.current_location, }; } else { break :blk Token{ .type = .dot_identifier, .text = parser.source[parser.offset..off], .location = parser.current_location, }; } }, // operator_shr, // >> // operator_asr, // >>> '>' => blk: { if (parser.offset + 1 >= parser.source.len) return error.UnexpectedEndOfFile; if (parser.source[parser.offset + 1] != '>') return error.UnrecognizedCharacter; if (parser.offset + 2 < parser.source.len and parser.source[parser.offset + 2] == '>') { break :blk Token{ .type = .operator_asr, .text = parser.source[parser.offset..][0..3], .location = parser.current_location, }; } else { break :blk Token{ .type = .operator_shr, .text = parser.source[parser.offset..][0..2], .location = parser.current_location, }; } }, '<' => blk: { if (parser.offset + 1 >= parser.source.len) return error.UnexpectedEndOfFile; if (parser.source[parser.offset + 1] != '<') return error.UnrecognizedCharacter; break :blk Token{ .type = .operator_shl, .text = parser.source[parser.offset..][0..2], .location = parser.current_location, }; }, // '<<' => parser.singleCharToken(.operator_shl), // bin_number: 0b0000 // oct_number: 0o0000 // dec_number: 0000 // hex_number: 0x0000 '0'...'9' => blk: { if (parser.offset + 1 < parser.source.len) { const spec = parser.source[parser.offset + 1]; switch (spec) { 'x', 'o', 'b' => { var num_type: TokenType = switch (spec) { 'x' => .hex_number, 'b' => .bin_number, 'o' => .oct_number, else => unreachable, }; var off = parser.offset + 2; while (off < parser.source.len and isDigit(parser.source[off], num_type)) { off += 1; } // .dotword break :blk Token{ .type = num_type, .text = parser.source[parser.offset..off], .location = parser.current_location, }; }, '0'...'9' => { var off = parser.offset + 1; while (off < parser.source.len and isDigit(parser.source[off], .dec_number)) { off += 1; } // .dotword break :blk Token{ .type = .dec_number, .text = parser.source[parser.offset..off], .location = parser.current_location, }; }, else => break :blk Token{ .type = .dec_number, .text = parser.source[parser.offset .. parser.offset + 1], .location = parser.current_location, }, } } else { break :blk Token{ .type = .dec_number, .text = parser.source[parser.offset .. parser.offset + 1], .location = parser.current_location, }; } }, // identifier 'a'...'z', 'A'...'Z', '_' => blk: { var off = parser.offset; while (off < parser.source.len and isWordCharacter(parser.source[off])) { off += 1; } if (off < parser.source.len and parser.source[off] == ':') { off += 1; break :blk Token{ .type = .label, .text = parser.source[parser.offset..off], .location = parser.current_location, }; } else { break :blk Token{ .type = .identifier, .text = parser.source[parser.offset..off], .location = parser.current_location, }; } }, // string_literal, char_literal '\'', '\"' => blk: { var off = parser.offset + 1; if (off == parser.source.len) return error.IncompleteStringLiteral; const delimiter = parser.source[parser.offset]; while (parser.source[off] != delimiter) { if (parser.source[off] == '\n') return error.IncompleteStringLiteral; if (parser.source[off] == '\\') { off += 1; } off += 1; if (off >= parser.source.len) return error.IncompleteStringLiteral; } off += 1; break :blk Token{ .type = if (delimiter == '\'') .char_literal else .string_literal, .text = parser.source[parser.offset..off], .location = parser.current_location, }; }, else => |c| { if (@import("builtin").mode == .Debug) { std.log.warn("unrecognized character: {c}", .{c}); } return error.UnrecognizedCharacter; }, }; parser.offset += token.text.len; for (token.text) |c| { if (c == '\n') { parser.current_location.line += 1; parser.current_location.column = 1; } else { parser.current_location.column += 1; } } return token; } fn lastOfSlice(slice: anytype) @TypeOf(slice[0]) { return slice[slice.len - 1]; } const ParserState = struct { source: []u8, offset: usize, peeked_token: ?Token, current_location: Location, }; fn saveState(parser: Parser) ParserState { return ParserState{ .source = parser.source, .offset = parser.offset, .peeked_token = parser.peeked_token, .current_location = parser.current_location, }; } fn restoreState(parser: *Parser, state: ParserState) void { parser.source = state.source; parser.offset = state.offset; parser.peeked_token = state.peeked_token; parser.current_location = state.current_location; } // parses an expression from the token stream const ParseExpressionResult = struct { expression: Expression, terminator: Token, }; fn parseExpression(parser: *Parser, allocator: std.mem.Allocator, terminators: anytype) !ParseExpressionResult { _ = terminators; const state = parser.saveState(); errdefer parser.restoreState(state); var expr = Expression{ .arena = std.heap.ArenaAllocator.init(allocator), .root = undefined, .location = undefined, }; errdefer expr.arena.deinit(); expr.root = try parser.acceptExpression(expr.arena.allocator()); expr.location = expr.root.location; return ParseExpressionResult{ .expression = expr, .terminator = try parser.expectAny(terminators), }; } fn moveToHeap(allocator: std.mem.Allocator, value: anytype) !*@TypeOf(value) { const T = @TypeOf(value); std.debug.assert(@typeInfo(T) != .Pointer); const ptr = try allocator.create(T); ptr.* = value; std.debug.assert(std.meta.eql(ptr.*, value)); return ptr; } const ParseError = error{ OutOfMemory, UnexpectedEndOfFile, UnrecognizedCharacter, IncompleteStringLiteral, UnexpectedToken, InvalidNumber, InvalidCharacter, }; const acceptExpression = acceptSumExpression; fn acceptSumExpression(self: *Parser, allocator: std.mem.Allocator) ParseError!ExpressionNode { const state = self.saveState(); errdefer self.restoreState(state); var expr = try self.acceptMulExpression(allocator); while (true) { var and_or = self.expectAny(.{ .operator_plus, .operator_minus, }) catch break; var rhs = try self.acceptMulExpression(allocator); var new_expr = ExpressionNode{ .location = expr.location.merge(and_or.location).merge(rhs.location), .type = .{ .binary_op = .{ .operator = switch (and_or.type) { .operator_plus => .add, .operator_minus => .sub, else => unreachable, }, .lhs = try moveToHeap(allocator, expr), .rhs = try moveToHeap(allocator, rhs), }, }, }; expr = new_expr; } return expr; } fn acceptMulExpression(self: *Parser, allocator: std.mem.Allocator) ParseError!ExpressionNode { const state = self.saveState(); errdefer self.restoreState(state); var expr = try self.acceptBitwiseExpression(allocator); while (true) { var and_or = self.expectAny(.{ .operator_multiply, .operator_divide, .operator_modulo, }) catch break; var rhs = try self.acceptBitwiseExpression(allocator); var new_expr = ExpressionNode{ .location = expr.location.merge(and_or.location).merge(rhs.location), .type = .{ .binary_op = .{ .operator = switch (and_or.type) { .operator_multiply => .mul, .operator_divide => .div, .operator_modulo => .mod, else => unreachable, }, .lhs = try moveToHeap(allocator, expr), .rhs = try moveToHeap(allocator, rhs), }, }, }; expr = new_expr; } return expr; } fn acceptBitwiseExpression(self: *Parser, allocator: std.mem.Allocator) ParseError!ExpressionNode { const state = self.saveState(); errdefer self.restoreState(state); var expr = try self.acceptShiftExpression(allocator); while (true) { var and_or = self.expectAny(.{ .operator_bitand, .operator_bitor, .operator_bitxor, }) catch break; var rhs = try self.acceptShiftExpression(allocator); var new_expr = ExpressionNode{ .location = expr.location.merge(and_or.location).merge(rhs.location), .type = .{ .binary_op = .{ .operator = switch (and_or.type) { .operator_bitand => .bit_and, .operator_bitor => .bit_or, .operator_bitxor => .bit_xor, else => unreachable, }, .lhs = try moveToHeap(allocator, expr), .rhs = try moveToHeap(allocator, rhs), }, }, }; expr = new_expr; } return expr; } fn acceptShiftExpression(self: *Parser, allocator: std.mem.Allocator) ParseError!ExpressionNode { const state = self.saveState(); errdefer self.restoreState(state); var expr = try self.acceptUnaryPrefixOperatorExpression(allocator); while (true) { var and_or = self.expectAny(.{ .operator_shl, .operator_shr, .operator_asr, }) catch break; var rhs = try self.acceptUnaryPrefixOperatorExpression(allocator); var new_expr = ExpressionNode{ .location = expr.location.merge(and_or.location).merge(rhs.location), .type = .{ .binary_op = .{ .operator = switch (and_or.type) { .operator_shl => .lsl, .operator_shr => .lsr, .operator_asr => .asr, else => unreachable, }, .lhs = try moveToHeap(allocator, expr), .rhs = try moveToHeap(allocator, rhs), }, }, }; expr = new_expr; } return expr; } fn acceptUnaryPrefixOperatorExpression(self: *Parser, allocator: std.mem.Allocator) ParseError!ExpressionNode { const state = self.saveState(); errdefer self.restoreState(state); if (self.expectAny(.{ .operator_bitnot, .operator_minus })) |prefix| { // this must directly recurse as we can write `not not x` const value = try self.acceptUnaryPrefixOperatorExpression(allocator); return ExpressionNode{ .location = prefix.location.merge(value.location), .type = .{ .unary_op = .{ .operator = switch (prefix.type) { .operator_bitnot => .bit_invert, .operator_minus => .negate, else => unreachable, }, .value = try moveToHeap(allocator, value), }, }, }; } else |_| { return try self.acceptCallExpression(allocator); } } fn acceptCallExpression(self: *Parser, allocator: std.mem.Allocator) ParseError!ExpressionNode { const state = self.saveState(); errdefer self.restoreState(state); var value = try self.acceptValueExpression(allocator); if (value.type == .symbol_reference) { if (self.expect(.opening_parens)) |_| { var args = std.ArrayList(ExpressionNode).init(allocator); defer args.deinit(); var loc = value.location; if (self.expect(.closing_parens)) |_| { // this is the end of the argument list } else |_| { while (true) { const arg = try self.acceptExpression(allocator); try args.append(arg); const terminator = try self.expectAny(.{ .closing_parens, .comma }); loc = terminator.location.merge(loc); if (terminator.type == .closing_parens) break; } } const name = value.type.symbol_reference; value = ExpressionNode{ .location = loc, .type = .{ .fn_call = .{ .function = name, .arguments = args.toOwnedSlice(), }, }, }; } else |_| {} } return value; } fn acceptValueExpression(self: *Parser, allocator: std.mem.Allocator) ParseError!ExpressionNode { const state = self.saveState(); errdefer self.restoreState(state); const token = try self.expectAny(.{ .opening_parens, .bin_number, .oct_number, .dec_number, .hex_number, .string_literal, .char_literal, .identifier, .dot_identifier, .dot, }); switch (token.type) { .opening_parens => { const value = try self.acceptExpression(allocator); _ = try self.expect(.closing_parens); return value; }, .bin_number => return ExpressionNode{ .location = token.location, .type = .{ .numeric_literal = std.fmt.parseInt(i64, token.text[2..], 2) catch return error.InvalidNumber, }, }, .oct_number => return ExpressionNode{ .location = token.location, .type = .{ .numeric_literal = std.fmt.parseInt(i64, token.text[2..], 8) catch return error.InvalidNumber, }, }, .dec_number => return ExpressionNode{ .location = token.location, .type = .{ .numeric_literal = std.fmt.parseInt(i64, token.text, 10) catch return error.InvalidNumber, }, }, .hex_number => return ExpressionNode{ .location = token.location, .type = .{ .numeric_literal = std.fmt.parseInt(i64, token.text[2..], 16) catch return error.InvalidNumber, }, }, .string_literal => { std.debug.assert(token.text.len >= 2); return ExpressionNode{ .location = token.location, .type = .{ .string_literal = try self.string_cache.escapeAndInternString(token.text[1 .. token.text.len - 1]), }, }; }, .char_literal => return ExpressionNode{ .location = token.location, .type = .{ .numeric_literal = (StringCache.translateEscapedChar(token.text[1..]) catch return error.InvalidCharacter).char, }, }, .identifier => return ExpressionNode{ .location = token.location, .type = .{ .symbol_reference = try self.string_cache.internString(token.text), }, }, .dot_identifier => return ExpressionNode{ .location = token.location, .type = .{ .local_symbol_reference = try self.string_cache.internString(token.text), }, }, .dot => return ExpressionNode{ .location = token.location, .type = .current_location, }, else => unreachable, } } }; const ExpressionNode = struct { location: Location, type: ExpressionType, const ExpressionType = union(enum) { const Self = @This(); string_literal: []const u8, numeric_literal: i64, symbol_reference: []const u8, local_symbol_reference: []const u8, current_location, binary_op: BinaryExpr, unary_op: UnaryExpr, fn_call: FunctionCall, const BinaryExpr = struct { operator: BinaryOperator, lhs: *ExpressionNode, rhs: *ExpressionNode, }; const UnaryExpr = struct { operator: UnaryOperator, value: *ExpressionNode, }; const FunctionCall = struct { function: []const u8, arguments: []ExpressionNode, }; const BinaryOperator = enum { add, sub, mul, div, mod, bit_and, bit_or, bit_xor, lsl, lsr, asr, }; const UnaryOperator = enum { negate, bit_invert, }; }; }; const Value = union(enum) { string: []const u8, // does not need to be freed, will be string-pooled number: i64, // TODO: Decide how to enable truncation warnings pub const warn_truncation = false; fn toInteger(self: Value, assembler: ?*Assembler, comptime T: type) !T { if (comptime !std.meta.trait.isIntegral(T)) @compileError("T must be a integer type!"); switch (self) { .number => |src| { const result = switch (@typeInfo(T).Int.signedness) { .signed => @truncate(T, src), .unsigned => @truncate(T, @bitCast(u64, src)), }; if (warn_truncation) { if (src < std.math.minInt(T) or src > std.math.maxInt(T)) { if (assembler) |as| { try as.emitError(.warning, null, "Truncating number {} to {}-bit value {}", .{ src, @bitSizeOf(T), result }); } } } return result; }, else => { if (assembler) |as| { try as.emitError(.warning, null, "Type mismatch: Expected number, found {s}", .{std.meta.tagName(self)}); } return error.TypeMismatch; }, } } pub fn toByte(self: Value, assembler: ?*Assembler) !u8 { return try self.toInteger(assembler, u8); } pub fn toWord(self: Value, assembler: ?*Assembler) !u16 { return try self.toInteger(assembler, u16); } pub fn toLong(self: Value, assembler: ?*Assembler) !u32 { return try self.toInteger(assembler, u32); } pub fn toNumber(self: Value, assembler: ?*Assembler) !i64 { return try self.toInteger(assembler, i64); } pub fn toString(self: Value, assembler: ?*Assembler) ![]const u8 { return switch (self) { .string => |v| v, else => { if (assembler) |as| { try as.emitError(.warning, null, "Type mismatch: Expected string, found {s}", .{std.meta.tagName(self)}); } return error.TypeMismatch; }, }; } }; const ValueType = std.meta.Tag(Value); /// A sequence of tokens created with a shunting yard algorithm. /// Can be parsed/executed left-to-right const Expression = struct { const Self = @This(); arena: std.heap.ArenaAllocator, location: Location, root: ExpressionNode, fn deinit(expr: *Expression) void { expr.arena.deinit(); expr.* = undefined; } pub const EvalError = Assembler.FunctionCallError || error{ MissingIdentifiers, UnknownFunction, OutOfMemory, TypeMismatch, Overflow }; pub fn evaluate(self: *const Self, context: *Assembler, emitErrorOnMissing: bool) EvalError!Value { const errors = ErrorEmitter{ .context = context, .emitErrorOnMissing = emitErrorOnMissing, }; return try self.evaluateRecursive(context, errors, &self.root); } const EvalValue = Value; const ErrorEmitter = struct { context: *Assembler, emitErrorOnMissing: bool, pub fn emit(self: @This(), err: EvalError, location: ?Location, comptime fmt: []const u8, args: anytype) EvalError { if (self.emitErrorOnMissing) { try self.context.emitError(.@"error", location, fmt, args); } return err; } fn requireValueType(errors: ErrorEmitter, comptime valtype: std.meta.Tag(EvalValue), value: EvalValue) !switch (valtype) { .number => i64, .string => []const u8, } { return switch (value) { valtype => |v| v, else => errors.emit(error.TypeMismatch, null, "Expected {s}, got {s}", .{ std.meta.tagName(valtype), std.meta.tagName(value) }), }; } fn requireNumber(errors: ErrorEmitter, value: EvalValue) !i64 { return requireValueType(errors, .number, value); } fn requireString(errors: ErrorEmitter, value: EvalValue) ![]const u8 { return requireValueType(errors, .string, value); } fn truncateTo(errors: ErrorEmitter, src: i64) !u16 { const result = @truncate(u16, @bitCast(u64, src)); if (src < 0 or src > 0xFFFF) { if (errors.emitErrorOnMissing) { try errors.context.emitError(.warning, null, "Truncating numeric {} to 16-bit value {}", .{ src, result }); } } return result; } }; fn evaluateRecursive(self: *const Self, context: *Assembler, errors: ErrorEmitter, node: *const ExpressionNode) EvalError!EvalValue { return switch (node.type) { .numeric_literal => |number| EvalValue{ .number = number }, .string_literal => |str| EvalValue{ .string = try context.string_cache.internString(str), }, .current_location => EvalValue{ .number = @intCast(u16, context.currentSection().getDotOffset()), }, .symbol_reference => |symbol_name| if (context.symbols.get(symbol_name)) |sym| EvalValue{ .number = try sym.getValue() } else return errors.emit(error.MissingIdentifiers, null, "Missing identifier: {s}", .{symbol_name}), // TODO: Store locations of symbol refs .local_symbol_reference => |symbol_name| if (context.local_symbols.get(symbol_name)) |sym| EvalValue{ .number = try sym.getValue() } else return errors.emit(error.MissingIdentifiers, null, "Missing identifier: {s}", .{symbol_name}), // TODO: Store locations of symbol refs .binary_op => |op| blk: { const lhs = try self.evaluateRecursive(context, errors, op.lhs); const rhs = try self.evaluateRecursive(context, errors, op.rhs); break :blk switch (op.operator) { .add => EvalValue{ .number = (try errors.requireNumber(lhs)) +% (try errors.requireNumber(rhs)), }, .sub => EvalValue{ .number = (try errors.requireNumber(lhs)) -% (try errors.requireNumber(rhs)), }, .mul => EvalValue{ .number = (try errors.requireNumber(lhs)) *% (try errors.requireNumber(rhs)), }, .div => EvalValue{ .number = @divTrunc(try errors.requireNumber(lhs), try errors.requireNumber(rhs)), }, .mod => EvalValue{ .number = @mod(try errors.requireNumber(lhs), try errors.requireNumber(rhs)), }, .bit_and => EvalValue{ .number = (try errors.requireNumber(lhs)) & (try errors.requireNumber(rhs)), }, .bit_or => EvalValue{ .number = (try errors.requireNumber(lhs)) | (try errors.requireNumber(rhs)), }, .bit_xor => EvalValue{ .number = (try errors.requireNumber(lhs)) ^ (try errors.requireNumber(rhs)), }, .lsl => EvalValue{ .number = @truncate(u16, @bitCast(u64, try errors.requireNumber(lhs))) << @truncate(u4, @bitCast(u64, try errors.requireNumber(rhs))), }, .lsr => EvalValue{ .number = @truncate(u16, @bitCast(u64, try errors.requireNumber(lhs))) >> @truncate(u4, @bitCast(u64, try errors.requireNumber(rhs))), }, .asr => asr_res: { const lhs_n = try errors.truncateTo(try errors.requireNumber(lhs)); const rhs_n = try errors.truncateTo(try errors.requireNumber(rhs)); const bits = @truncate(u4, rhs_n); const shifted = (lhs_n >> bits); if (lhs_n >= 0x8000) { const mask_mask: u16 = @as(u16, 0xFFFF) >> bits; const mask: u16 = @as(u16, 0xFFFF) & ~mask_mask; break :asr_res EvalValue{ .number = shifted | mask, }; } break :asr_res EvalValue{ .number = shifted, }; // } else { // break :asr_res (lhs_n >> bits); // } }, }; }, .unary_op => |op| blk: { const value = try errors.requireNumber(try self.evaluateRecursive(context, errors, op.value)); break :blk switch (op.operator) { .bit_invert => EvalValue{ .number = ~value, }, .negate => EvalValue{ .number = 0 -% value, }, }; }, .fn_call => |fun| { const argv = try context.allocator.alloc(Value, fun.arguments.len); defer context.allocator.free(argv); for (fun.arguments) |*src_node, i| { argv[i] = try self.evaluateRecursive(context, errors, src_node); } inline for (std.meta.declarations(Assembler.Functions)) |decl| { if (std.mem.eql(u8, fun.function, decl.name)) { const result: Assembler.FunctionCallError!Value = @field(Assembler.Functions, decl.name)(context, argv); if (result) |val| { return val; } else |err| { return errors.emit(err, null, "Failed to invoke the function {s}: {s}", .{ fun, @errorName(err) }); } } } return errors.emit(error.UnknownFunction, null, "The function {s} does not exist!", .{fun}); }, }; } pub fn format(value: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, stream: anytype) !void { _ = fmt; _ = options; for (value.sequence) |item, i| { if (i > 0) try stream.writeAll(" "); try stream.writeAll(item.text); } } }; const Modifiers = struct { const Self = @This(); condition: ?spu.ExecutionCondition = null, input0: ?spu.InputBehaviour = null, input1: ?spu.InputBehaviour = null, modify_flags: ?bool = null, output: ?spu.OutputBehaviour = null, command: ?spu.Command = null, /// will start at identifier, not `[`! fn parse(mods: *Self, assembler: *Assembler, parser: *Parser) !void { const mod_type = try parser.expect(.label); // type + ':' const mod_value = try parser.expect(.identifier); // value _ = try parser.expect(.closing_brackets); if (std.mem.eql(u8, mod_type.text, "ex:")) { if (mods.condition != null) return error.DuplicateModifier; inline for (condition_items) |item| { if (std.mem.eql(u8, item[0], mod_value.text)) { mods.condition = item[1]; return; } } } else if (std.mem.eql(u8, mod_type.text, "i0:")) { if (mods.input0 != null) return error.DuplicateModifier; inline for (input_items) |item| { if (std.mem.eql(u8, item[0], mod_value.text)) { mods.input0 = item[1]; return; } } } else if (std.mem.eql(u8, mod_type.text, "i1:")) { if (mods.input1 != null) return error.DuplicateModifier; inline for (input_items) |item| { if (std.mem.eql(u8, item[0], mod_value.text)) { mods.input1 = item[1]; return; } } } else if (std.mem.eql(u8, mod_type.text, "f:")) { if (mods.modify_flags != null) return error.DuplicateModifier; inline for (flag_items) |item| { if (std.mem.eql(u8, item[0], mod_value.text)) { mods.modify_flags = item[1]; return; } } } else if (std.mem.eql(u8, mod_type.text, "out:")) { if (mods.output != null) return error.DuplicateModifier; inline for (output_items) |item| { if (std.mem.eql(u8, item[0], mod_value.text)) { mods.output = item[1]; return; } } } else if (std.mem.eql(u8, mod_type.text, "cmd:")) { if (mods.command != null) return error.DuplicateModifier; inline for (command_items) |item| { if (std.mem.eql(u8, item[0], mod_value.text)) { mods.command = item[1]; return; } } } try assembler.emitError(.@"error", mod_type.location, "Unknown modifier: {s}{s}", .{ mod_type.text, mod_value.text }); } const condition_items = .{ .{ "always", .always }, .{ "zero", .when_zero }, .{ "nonzero", .not_zero }, .{ "greater", .greater_zero }, .{ "less", .less_than_zero }, .{ "gequal", .greater_or_equal_zero }, .{ "lequal", .less_or_equal_zero }, .{ "ovfl", .overflow }, }; const flag_items = .{ .{ "no", false }, .{ "yes", true }, }; const input_items = .{ .{ "zero", .zero }, .{ "immediate", .immediate }, .{ "peek", .peek }, .{ "pop", .pop }, .{ "arg", .immediate }, .{ "imm", .immediate }, }; const output_items = .{ .{ "discard", .discard }, .{ "push", .push }, }; const command_items = .{ .{ "copy", .copy }, .{ "get", .get }, .{ "set", .set }, .{ "store8", .store8 }, .{ "store16", .store16 }, .{ "load8", .load8 }, .{ "load16", .load16 }, .{ "frget", .frget }, .{ "frset", .frset }, .{ "bpget", .bpget }, .{ "bpset", .bpset }, .{ "spget", .spget }, .{ "spset", .spset }, .{ "add", .add }, .{ "sub", .sub }, .{ "mul", .mul }, .{ "div", .div }, .{ "mod", .mod }, .{ "and", .@"and" }, .{ "or", .@"or" }, .{ "xor", .xor }, .{ "not", .not }, .{ "signext", .signext }, .{ "rol", .rol }, .{ "ror", .ror }, .{ "bswap", .bswap }, .{ "asr", .asr }, .{ "lsl", .lsl }, .{ "lsr", .lsr }, .{ "setip", .setip }, .{ "addip", .addip }, .{ "intr", .intr }, }; }; test { _ = main; } const TestSectionDesc = struct { load_offset: u16, phys_offset: u32, contents: []const u8, fn initZeroOffset(content: []const u8) TestSectionDesc { return .{ .load_offset = 0, .phys_offset = 0, .contents = content, }; } fn initOffset(offset: u16, content: []const u8) TestSectionDesc { return .{ .load_offset = offset, .phys_offset = offset, .contents = content, }; } }; fn testCodeGenerationGeneratesOutput(expected: []const TestSectionDesc, comptime source: []const u8) !void { var as = try Assembler.init(std.testing.allocator); defer as.deinit(); { var source_cpy = source[0..source.len].*; var stream = std.io.fixedBufferStream(source); try as.assemble("memory", std.fs.cwd(), stream.reader()); // destroy all evidence std.mem.set(u8, &source_cpy, 0x55); try as.finalize(); } for (as.errors.items) |err| { std.log.err("compile error: {}", .{err}); } try std.testing.expectEqual(@as(usize, 0), as.errors.items.len); var section = as.sections.first; for (expected) |output| { try std.testing.expect(section != null); try std.testing.expectEqual(output.load_offset, section.?.data.load_offset); try std.testing.expectEqual(output.phys_offset, section.?.data.phys_offset); try std.testing.expectEqualSlices(u8, output.contents, section.?.data.bytes.items); section = section.?.next; } } fn testCodeGenerationEqual(expected: []const u8, comptime source: []const u8) !void { try testCodeGenerationGeneratesOutput(&[_]TestSectionDesc{TestSectionDesc.initZeroOffset(expected)}, source); } test "empty file" { try testCodeGenerationGeneratesOutput(&[_]TestSectionDesc{TestSectionDesc.initZeroOffset("")}, ""); } test "section deduplication" { try testCodeGenerationGeneratesOutput(&[_]TestSectionDesc{TestSectionDesc.initOffset(0x8000, "hello")}, \\.org 0x0000 \\.org 0x8000 \\.ascii "hello" ); } test "section physical offset setup" { try testCodeGenerationGeneratesOutput(&[_]TestSectionDesc{ .{ .load_offset = 0x0000, .phys_offset = 0x8000, .contents = "hello", }, .{ .load_offset = 0x2000, .phys_offset = 0x10_0000, .contents = "bye", }, }, \\.org 0x0000, 0x8000 \\.ascii "hello" \\.org 0x2000, 0x100000 \\.ascii "bye" ); } test "emit raw word" { try testCodeGenerationEqual(&[_]u8{ 0x34, 0x12, 0x78, 0x56, 0xBC, 0x9A }, \\.dw 0x1234 \\.dw 0x5678, 0x9ABC ); } test "emit raw byte" { try testCodeGenerationEqual(&[_]u8{ 0x12, 0x34, 0x56, 0x78 }, \\.db 0x12 \\.db 0x34, 0x56, 0x78 ); } fn testExpressionEvaluation(expected: u16, comptime source: []const u8) !void { var buf: [2]u8 = undefined; std.mem.writeIntLittle(u16, &buf, expected); return try testCodeGenerationEqual(&buf, source); } test "parsing integer literals" { try testExpressionEvaluation(100, \\.dw 100 ; decimal ); try testExpressionEvaluation(0b100, \\.dw 0b100 ; binary ); try testExpressionEvaluation(0o100, \\.dw 0o100 ; octal ); try testExpressionEvaluation(0x100, \\.dw 0x100 ; hexadecimal ); } test "basic (non-nested) basic arithmetic" { try testExpressionEvaluation(30, \\.dw 20+10 ); try testExpressionEvaluation(10, \\.dw 20-10 ); try testExpressionEvaluation(200, \\.dw 20*10 ); try testExpressionEvaluation(2, \\.dw 20/10 ); } test "basic (non-nested) bitwise arithmetic" { try testExpressionEvaluation(3, \\.dw 7&3 ); try testExpressionEvaluation(12, \\.dw 8|12 ); try testExpressionEvaluation(4, \\.dw 13^9 ); } test "basic (non-nested) shift arithmetic" { try testExpressionEvaluation(256, \\.dw 16<<4 ); try testExpressionEvaluation(4, \\.dw 16>>2 ); try testExpressionEvaluation(0xFFFF, \\.dw 0x8000>>>15 ); try testExpressionEvaluation(0x0000, \\.dw 0x7FFF>>>15 ); } test "basic unary operators" { try testExpressionEvaluation(0x00FF, \\.dw ~0xFF00 ); try testExpressionEvaluation(65526, \\.dw -10 ); } test "operator precedence" { try testExpressionEvaluation(610, \\.dw 10+20*30 ); try testExpressionEvaluation(900, \\.dw (10+20)*30 ); } test "backward references" { try testExpressionEvaluation(0, \\backward: \\.dw backward ); } test "forward references" { try testExpressionEvaluation(2, \\.dw forward \\forward: ); } test "basic string generation" { try testCodeGenerationEqual("abc", \\.db 'a', 'b' \\.db 'c' ); try testCodeGenerationEqual("abc", \\.ascii "abc" ); try testCodeGenerationEqual("abc", \\.ascii "ab" \\.ascii "c" ); try testCodeGenerationEqual("abc", \\.ascii "abc" ); try testCodeGenerationEqual("ab\x00c\x00", \\.asciiz "ab" \\.asciiz "c" ); } test "string escaping" { try testCodeGenerationEqual(&[_]u8{ 0x07, 0x08, 0x1B, 0x0A, 0x0D, 0x0B, 0x5C, 0x27, 0x22, 0x12, 0xFF, 0x00 }, \\.db '\a', '\b', '\e', '\n', '\r', '\t', '\\', '\'', '\"', '\x12', '\xFF', '\x00' ); try testCodeGenerationEqual(&[_]u8{ 0x07, 0x08, 0x1B, 0x0A, 0x0D, 0x0B, 0x5C, 0x27, 0x22, 0x12, 0xFF, 0x00 }, \\.ascii "\a\b\e\n\r\t\\\'\"\x12\xFF\x00" ); } test ".equ" { try testExpressionEvaluation(42, \\.equ constant, 40 \\.equ forward, constant \\.equ result, forward + 2 \\.dw result ); } test ".equ with big numbers" { try testExpressionEvaluation(1, \\.equ big_a, 0x1000000000 \\.equ big_b, 0x0FFFFFFFFF \\.dw big_a - big_b ); } test ".space" { try testCodeGenerationEqual(&[_]u8{ 1, 0, 0, 0, 2 }, \\.db 1 \\.space 3 \\.db 2 ); } test ".incbin" { try testCodeGenerationEqual(".ascii \"include\"", \\.incbin "test/include.inc" ); } test ".include" { try testCodeGenerationEqual("[include]", \\.db '[' \\.include "test/include.inc" \\.db ']' ); } fn testInstructionGeneration(expected: Instruction, operands: []const u16, comptime source: []const u8) !void { var buf: [6]u8 = undefined; std.mem.copy(u8, buf[0..2], std.mem.asBytes(&expected)); for (operands) |o, i| { std.mem.writeIntLittle(u16, buf[2 * (i + 1) ..][0..2], o); } const slice = buf[0 .. 2 * operands.len + 2]; try testCodeGenerationEqual(slice, source); } test "nop generation" { try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy, }, &[_]u16{}, \\nop , ); } test "[ex:] modifier application" { try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [ex:always] , ); try testInstructionGeneration( Instruction{ .condition = .when_zero, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [ex:zero] , ); try testInstructionGeneration( Instruction{ .condition = .not_zero, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [ex:nonzero] , ); try testInstructionGeneration( Instruction{ .condition = .greater_zero, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [ex:greater] , ); try testInstructionGeneration( Instruction{ .condition = .less_than_zero, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [ex:less] , ); try testInstructionGeneration( Instruction{ .condition = .greater_or_equal_zero, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [ex:gequal] , ); try testInstructionGeneration( Instruction{ .condition = .less_or_equal_zero, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [ex:lequal] , ); try testInstructionGeneration( Instruction{ .condition = .overflow, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [ex:ovfl] , ); } test "[f:] modifier application" { try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [f:no] , ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .zero, .modify_flags = true, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [f:yes] , ); } test "[i0:] modifier application" { try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [i0:zero] , ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .immediate, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [i0:immediate] , ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .peek, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [i0:peek] , ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .pop, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [i0:pop] , ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .immediate, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [i0:arg] , ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .immediate, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [i0:imm] , ); } test "[i1:] modifier application" { try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [i1:zero] , ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .immediate, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [i1:immediate] , ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .peek, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [i1:peek] , ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .pop, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [i1:pop] , ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .immediate, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [i1:arg] , ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .immediate, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [i1:imm] , ); } test "[out:] modifier application" { try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [out:discard] , ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .push, .command = .copy }, &[_]u16{}, \\nop [out:push] , ); } test "[cmd:] modifier application" { inline for (Modifiers.command_items) |cmd| { try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = cmd[1] }, &[_]u16{}, "nop [cmd:" ++ cmd[0] ++ "]", ); } } test "input count selection" { try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .pop, .input1 = .pop, .command = .store16, .output = .discard, .modify_flags = false }, &[_]u16{}, "st", ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .pop, .input1 = .immediate, .command = .store16, .output = .discard, .modify_flags = false }, &[_]u16{0x1234}, "st 0x1234", ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .immediate, .input1 = .immediate, .command = .store16, .output = .discard, .modify_flags = false }, &[_]u16{ 0x1234, 0x4567 }, "st 0x1234, 0x4567", ); } test "function 'substr'" { try testCodeGenerationEqual("ll", \\.ascii substr("hello", 2, 2) ); try testCodeGenerationEqual("o", \\.ascii substr("hello", 4, 100) ); try testCodeGenerationEqual("", \\.ascii substr("hello", 5, 1) ); try testCodeGenerationEqual("", \\.ascii substr("hello", 1000, 1000) ); try testCodeGenerationEqual("llo", \\.ascii substr("hello", 2) ); try testCodeGenerationEqual("", \\.ascii substr("hello", 7) ); } test "function 'physicalAddress'" { try testCodeGenerationGeneratesOutput(&[_]TestSectionDesc{ .{ .contents = "\x00\x00\x00\x10", .load_offset = 0x0000, .phys_offset = 0x1000 }, }, \\.org 0x0000, 0x1000 \\this: \\.dw 0 \\.dw physicalAddress("this") ); } test "offset address emission" { try testCodeGenerationGeneratesOutput(&[_]TestSectionDesc{ .{ .contents = "\x00\x00\x02\x80", .load_offset = 0x8000, .phys_offset = 0x8000, }, }, \\.org 0x8000 \\.dw 0 \\this: \\.dw this ); }
tools/assembler/main.zig
usingnamespace @import("root").preamble; const log = lib.output.log.scoped(.{ .prefix = "XHCI", .filter = .info, }).write; const CapRegs = extern struct { capabilites_length: u8, _res_01: u8, version: u16, hcs_params_1: u32, hcs_params_2: u32, hcs_params_3: u32, hcc_params_1: u32, db_regs_bar_offset: u32, run_regs_bar_offset: u32, gccparams2: u32, }; const PortRegs = extern struct { portsc: u32, portpmsc: u32, portli: u32, reserved: u32, }; const OpRegs = extern struct { usbcmd: u32, usbsts: u32, page_size: u32, _res_0C: [0x14 - 0x0C]u8, dnctrl: u32, crcr: u64, _res_20: [0x30 - 0x20]u8, dcbaap: u64, config: u32, _res_3C: [0x400 - 0x3C]u8, ports: [256]PortRegs, }; const InterruptRegs = extern struct { iman: u32, imod: u32, erstsz: u32, res_0C: u32, erstba: u32, erdp: u32, }; const RunRegs = extern struct { microframe_idx: u32, _res_04: [0x20 - 0x4]u8, interrupt_regs: [1024]InterruptRegs, }; const DBRegs = extern struct { db: [256]u32, }; const Controller = extern struct { cap_regs: *volatile CapRegs, op_regs: *volatile OpRegs, run_regs: *volatile RunRegs, db_regs: *volatile DBRegs, context_size: usize = undefined, fn init(bar: usize) @This() { const cap_regs = os.platform.phys_ptr(*volatile CapRegs).from_int(bar).get_uncached(); return .{ .cap_regs = cap_regs, .op_regs = os.platform.phys_ptr(*volatile OpRegs).from_int(bar + cap_regs.capabilites_length).get_uncached(), .run_regs = os.platform.phys_ptr(*volatile RunRegs).from_int(bar + cap_regs.run_regs_bar_offset).get_uncached(), .db_regs = os.platform.phys_ptr(*volatile DBRegs).from_int(bar + cap_regs.db_regs_bar_offset).get_uncached(), }; } fn extcapsPtr(self: *const @This()) [*]volatile u32 { const eoff = ((self.cap_regs.hcc_params_1 & 0xFFFF0000) >> 16) * 4; return @intToPtr([*]u32, @ptrToInt(self.cap_regs) + eoff); } fn claim(self: *const @This()) void { var ext = self.extcapsPtr(); while (true) { const ident = ext[0]; if (ident == ~@as(u32, 0)) break; if ((ident & 0xFF) == 0) break; if ((ident & 0xFF) == 1) { // Bios semaphore const bios_sem = @intToPtr(*volatile u8, @ptrToInt(ext) + 2); const os_sem = @intToPtr(*volatile u8, @ptrToInt(ext) + 3); if (bios_sem.* != 0) { log(.debug, "XHCI: Controller is BIOS owned.", .{}); os_sem.* = 1; while (bios_sem.* != 0) os.thread.scheduler.yield(); log(.debug, "XHCI: Controller stolen from BIOS.", .{}); } } const next_offset = (ident >> 8) & 0xFF; if (next_offset == 0) break; ext += next_offset; } } }; fn controllerTask(dev: os.platform.pci.Addr) !void { const bar = dev.barinfo(0); var controller = Controller.init(bar.phy); controller.claim(); const usb3 = dev.read(u32, 0xDC); log(.debug, "XHCI: Switching usb3 ports: 0x{X}", .{usb3}); dev.write(u32, 0xD8, usb3); const usb2 = dev.read(u32, 0xD4); log(.debug, "XHCI: Switching usb2 ports: 0x{X}", .{usb2}); dev.write(u32, 0xD0, usb2); // Shut controller down controller.op_regs.usbcmd |= 1 << 1; while ((controller.op_regs.usbcmd & (1 << 1)) != 0) os.thread.scheduler.yield(); while ((controller.op_regs.usbsts & (1 << 0)) == 0) os.thread.scheduler.yield(); log(.debug, "XHCI: Controller halted.", .{}); controller.op_regs.config = 44; controller.context_size = if ((controller.cap_regs.hcc_params_1 & 0b10) != 0) 64 else 32; log(.debug, "XHCI: context size: {d}", .{controller.context_size}); } pub fn registerController(dev: os.platform.pci.Addr) void { if (comptime (!config.drivers.usb.xhci.enable)) return; dev.command().write(dev.command().read() | 0x6); os.vital(os.thread.scheduler.spawnTask("XHCI controller task", controllerTask, .{dev}), "Spawning XHCI controller task"); }
subprojects/flork/src/drivers/usb/xhci.zig
pub usingnamespace @import("std").zig.c_builtins; pub const webview_t = ?*c_void; pub extern fn webview_create(debug: c_int, window: ?*c_void) webview_t; pub extern fn webview_destroy(w: webview_t) void; pub extern fn webview_run(w: webview_t) void; pub extern fn webview_terminate(w: webview_t) void; pub extern fn webview_dispatch(w: webview_t, @"fn": ?fn (webview_t, ?*c_void) callconv(.C) void, arg: ?*c_void) void; pub extern fn webview_get_window(w: webview_t) ?*c_void; pub extern fn webview_set_title(w: webview_t, title: [*c]const u8) void; pub extern fn webview_set_size(w: webview_t, width: c_int, height: c_int, hints: c_int) void; pub extern fn webview_navigate(w: webview_t, url: [*c]const u8) void; pub extern fn webview_init(w: webview_t, js: [*c]const u8) void; pub extern fn webview_eval(w: webview_t, js: [*c]const u8) void; pub extern fn webview_bind(w: webview_t, name: [*c]const u8, @"fn": ?fn ([*c]const u8, [*c]const u8, ?*c_void) callconv(.C) void, arg: ?*c_void) void; pub extern fn webview_return(w: webview_t, seq: [*c]const u8, status: c_int, result: [*c]const u8) void; pub const WEBVIEW_API = @compileError("unable to translate C expr: unexpected token .Keyword_extern"); // src/webview.h:28:9 pub const __llvm__ = @as(c_int, 1); pub const __clang__ = @as(c_int, 1); pub const __clang_major__ = @as(c_int, 12); pub const __clang_minor__ = @as(c_int, 0); pub const __clang_patchlevel__ = @as(c_int, 1); pub const __clang_version__ = "12.0.1 "; pub const __GNUC__ = @as(c_int, 4); pub const __GNUC_MINOR__ = @as(c_int, 2); pub const __GNUC_PATCHLEVEL__ = @as(c_int, 1); pub const __GXX_ABI_VERSION = @as(c_int, 1002); pub const __ATOMIC_RELAXED = @as(c_int, 0); pub const __ATOMIC_CONSUME = @as(c_int, 1); pub const __ATOMIC_ACQUIRE = @as(c_int, 2); pub const __ATOMIC_RELEASE = @as(c_int, 3); pub const __ATOMIC_ACQ_REL = @as(c_int, 4); pub const __ATOMIC_SEQ_CST = @as(c_int, 5); pub const __OPENCL_MEMORY_SCOPE_WORK_ITEM = @as(c_int, 0); pub const __OPENCL_MEMORY_SCOPE_WORK_GROUP = @as(c_int, 1); pub const __OPENCL_MEMORY_SCOPE_DEVICE = @as(c_int, 2); pub const __OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES = @as(c_int, 3); pub const __OPENCL_MEMORY_SCOPE_SUB_GROUP = @as(c_int, 4); pub const __PRAGMA_REDEFINE_EXTNAME = @as(c_int, 1); pub const __VERSION__ = "Homebrew Clang 12.0.1"; pub const __OBJC_BOOL_IS_BOOL = @as(c_int, 0); pub const __CONSTANT_CFSTRINGS__ = @as(c_int, 1); pub const __block = __attribute__(__blocks__(byref)); pub const __BLOCKS__ = @as(c_int, 1); pub const __OPTIMIZE__ = @as(c_int, 1); pub const __ORDER_LITTLE_ENDIAN__ = @as(c_int, 1234); pub const __ORDER_BIG_ENDIAN__ = @as(c_int, 4321); pub const __ORDER_PDP_ENDIAN__ = @as(c_int, 3412); pub const __BYTE_ORDER__ = __ORDER_LITTLE_ENDIAN__; pub const __LITTLE_ENDIAN__ = @as(c_int, 1); pub const _LP64 = @as(c_int, 1); pub const __LP64__ = @as(c_int, 1); pub const __CHAR_BIT__ = @as(c_int, 8); pub const __SCHAR_MAX__ = @as(c_int, 127); pub const __SHRT_MAX__ = @as(c_int, 32767); pub const __INT_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal); pub const __LONG_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_long, 9223372036854775807, .decimal); pub const __LONG_LONG_MAX__ = @as(c_longlong, 9223372036854775807); pub const __WCHAR_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal); pub const __WINT_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal); pub const __INTMAX_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_long, 9223372036854775807, .decimal); pub const __SIZE_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_ulong, 18446744073709551615, .decimal); pub const __UINTMAX_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_ulong, 18446744073709551615, .decimal); pub const __PTRDIFF_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_long, 9223372036854775807, .decimal); pub const __INTPTR_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_long, 9223372036854775807, .decimal); pub const __UINTPTR_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_ulong, 18446744073709551615, .decimal); pub const __SIZEOF_DOUBLE__ = @as(c_int, 8); pub const __SIZEOF_FLOAT__ = @as(c_int, 4); pub const __SIZEOF_INT__ = @as(c_int, 4); pub const __SIZEOF_LONG__ = @as(c_int, 8); pub const __SIZEOF_LONG_DOUBLE__ = @as(c_int, 16); pub const __SIZEOF_LONG_LONG__ = @as(c_int, 8); pub const __SIZEOF_POINTER__ = @as(c_int, 8); pub const __SIZEOF_SHORT__ = @as(c_int, 2); pub const __SIZEOF_PTRDIFF_T__ = @as(c_int, 8); pub const __SIZEOF_SIZE_T__ = @as(c_int, 8); pub const __SIZEOF_WCHAR_T__ = @as(c_int, 4); pub const __SIZEOF_WINT_T__ = @as(c_int, 4); pub const __SIZEOF_INT128__ = @as(c_int, 16); pub const __INTMAX_TYPE__ = c_long; pub const __INTMAX_FMTd__ = "ld"; pub const __INTMAX_FMTi__ = "li"; pub const __INTMAX_C_SUFFIX__ = L; pub const __UINTMAX_TYPE__ = c_ulong; pub const __UINTMAX_FMTo__ = "lo"; pub const __UINTMAX_FMTu__ = "lu"; pub const __UINTMAX_FMTx__ = "lx"; pub const __UINTMAX_FMTX__ = "lX"; pub const __UINTMAX_C_SUFFIX__ = UL; pub const __INTMAX_WIDTH__ = @as(c_int, 64); pub const __PTRDIFF_TYPE__ = c_long; pub const __PTRDIFF_FMTd__ = "ld"; pub const __PTRDIFF_FMTi__ = "li"; pub const __PTRDIFF_WIDTH__ = @as(c_int, 64); pub const __INTPTR_TYPE__ = c_long; pub const __INTPTR_FMTd__ = "ld"; pub const __INTPTR_FMTi__ = "li"; pub const __INTPTR_WIDTH__ = @as(c_int, 64); pub const __SIZE_TYPE__ = c_ulong; pub const __SIZE_FMTo__ = "lo"; pub const __SIZE_FMTu__ = "lu"; pub const __SIZE_FMTx__ = "lx"; pub const __SIZE_FMTX__ = "lX"; pub const __SIZE_WIDTH__ = @as(c_int, 64); pub const __WCHAR_TYPE__ = c_int; pub const __WCHAR_WIDTH__ = @as(c_int, 32); pub const __WINT_TYPE__ = c_int; pub const __WINT_WIDTH__ = @as(c_int, 32); pub const __SIG_ATOMIC_WIDTH__ = @as(c_int, 32); pub const __SIG_ATOMIC_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal); pub const __CHAR16_TYPE__ = c_ushort; pub const __CHAR32_TYPE__ = c_uint; pub const __UINTMAX_WIDTH__ = @as(c_int, 64); pub const __UINTPTR_TYPE__ = c_ulong; pub const __UINTPTR_FMTo__ = "lo"; pub const __UINTPTR_FMTu__ = "lu"; pub const __UINTPTR_FMTx__ = "lx"; pub const __UINTPTR_FMTX__ = "lX"; pub const __UINTPTR_WIDTH__ = @as(c_int, 64); pub const __FLT_DENORM_MIN__ = @as(f32, 1.40129846e-45); pub const __FLT_HAS_DENORM__ = @as(c_int, 1); pub const __FLT_DIG__ = @as(c_int, 6); pub const __FLT_DECIMAL_DIG__ = @as(c_int, 9); pub const __FLT_EPSILON__ = @as(f32, 1.19209290e-7); pub const __FLT_HAS_INFINITY__ = @as(c_int, 1); pub const __FLT_HAS_QUIET_NAN__ = @as(c_int, 1); pub const __FLT_MANT_DIG__ = @as(c_int, 24); pub const __FLT_MAX_10_EXP__ = @as(c_int, 38); pub const __FLT_MAX_EXP__ = @as(c_int, 128); pub const __FLT_MAX__ = @as(f32, 3.40282347e+38); pub const __FLT_MIN_10_EXP__ = -@as(c_int, 37); pub const __FLT_MIN_EXP__ = -@as(c_int, 125); pub const __FLT_MIN__ = @as(f32, 1.17549435e-38); pub const __DBL_DENORM_MIN__ = 4.9406564584124654e-324; pub const __DBL_HAS_DENORM__ = @as(c_int, 1); pub const __DBL_DIG__ = @as(c_int, 15); pub const __DBL_DECIMAL_DIG__ = @as(c_int, 17); pub const __DBL_EPSILON__ = 2.2204460492503131e-16; pub const __DBL_HAS_INFINITY__ = @as(c_int, 1); pub const __DBL_HAS_QUIET_NAN__ = @as(c_int, 1); pub const __DBL_MANT_DIG__ = @as(c_int, 53); pub const __DBL_MAX_10_EXP__ = @as(c_int, 308); pub const __DBL_MAX_EXP__ = @as(c_int, 1024); pub const __DBL_MAX__ = 1.7976931348623157e+308; pub const __DBL_MIN_10_EXP__ = -@as(c_int, 307); pub const __DBL_MIN_EXP__ = -@as(c_int, 1021); pub const __DBL_MIN__ = 2.2250738585072014e-308; pub const __LDBL_DENORM_MIN__ = @as(c_longdouble, 3.64519953188247460253e-4951); pub const __LDBL_HAS_DENORM__ = @as(c_int, 1); pub const __LDBL_DIG__ = @as(c_int, 18); pub const __LDBL_DECIMAL_DIG__ = @as(c_int, 21); pub const __LDBL_EPSILON__ = @as(c_longdouble, 1.08420217248550443401e-19); pub const __LDBL_HAS_INFINITY__ = @as(c_int, 1); pub const __LDBL_HAS_QUIET_NAN__ = @as(c_int, 1); pub const __LDBL_MANT_DIG__ = @as(c_int, 64); pub const __LDBL_MAX_10_EXP__ = @as(c_int, 4932); pub const __LDBL_MAX_EXP__ = @as(c_int, 16384); pub const __LDBL_MAX__ = @as(c_longdouble, 1.18973149535723176502e+4932); pub const __LDBL_MIN_10_EXP__ = -@as(c_int, 4931); pub const __LDBL_MIN_EXP__ = -@as(c_int, 16381); pub const __LDBL_MIN__ = @as(c_longdouble, 3.36210314311209350626e-4932); pub const __POINTER_WIDTH__ = @as(c_int, 64); pub const __BIGGEST_ALIGNMENT__ = @as(c_int, 16); pub const __INT8_TYPE__ = i8; pub const __INT8_FMTd__ = "hhd"; pub const __INT8_FMTi__ = "hhi"; pub const __INT16_TYPE__ = c_short; pub const __INT16_FMTd__ = "hd"; pub const __INT16_FMTi__ = "hi"; pub const __INT32_TYPE__ = c_int; pub const __INT32_FMTd__ = "d"; pub const __INT32_FMTi__ = "i"; pub const __INT64_TYPE__ = c_longlong; pub const __INT64_FMTd__ = "lld"; pub const __INT64_FMTi__ = "lli"; pub const __INT64_C_SUFFIX__ = LL; pub const __UINT8_TYPE__ = u8; pub const __UINT8_FMTo__ = "hho"; pub const __UINT8_FMTu__ = "hhu"; pub const __UINT8_FMTx__ = "hhx"; pub const __UINT8_FMTX__ = "hhX"; pub const __UINT8_MAX__ = @as(c_int, 255); pub const __INT8_MAX__ = @as(c_int, 127); pub const __UINT16_TYPE__ = c_ushort; pub const __UINT16_FMTo__ = "ho"; pub const __UINT16_FMTu__ = "hu"; pub const __UINT16_FMTx__ = "hx"; pub const __UINT16_FMTX__ = "hX"; pub const __UINT16_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 65535, .decimal); pub const __INT16_MAX__ = @as(c_int, 32767); pub const __UINT32_TYPE__ = c_uint; pub const __UINT32_FMTo__ = "o"; pub const __UINT32_FMTu__ = "u"; pub const __UINT32_FMTx__ = "x"; pub const __UINT32_FMTX__ = "X"; pub const __UINT32_C_SUFFIX__ = U; pub const __UINT32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 4294967295, .decimal); pub const __INT32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal); pub const __UINT64_TYPE__ = c_ulonglong; pub const __UINT64_FMTo__ = "llo"; pub const __UINT64_FMTu__ = "llu"; pub const __UINT64_FMTx__ = "llx"; pub const __UINT64_FMTX__ = "llX"; pub const __UINT64_C_SUFFIX__ = ULL; pub const __UINT64_MAX__ = @as(c_ulonglong, 18446744073709551615); pub const __INT64_MAX__ = @as(c_longlong, 9223372036854775807); pub const __INT_LEAST8_TYPE__ = i8; pub const __INT_LEAST8_MAX__ = @as(c_int, 127); pub const __INT_LEAST8_FMTd__ = "hhd"; pub const __INT_LEAST8_FMTi__ = "hhi"; pub const __UINT_LEAST8_TYPE__ = u8; pub const __UINT_LEAST8_MAX__ = @as(c_int, 255); pub const __UINT_LEAST8_FMTo__ = "hho"; pub const __UINT_LEAST8_FMTu__ = "hhu"; pub const __UINT_LEAST8_FMTx__ = "hhx"; pub const __UINT_LEAST8_FMTX__ = "hhX"; pub const __INT_LEAST16_TYPE__ = c_short; pub const __INT_LEAST16_MAX__ = @as(c_int, 32767); pub const __INT_LEAST16_FMTd__ = "hd"; pub const __INT_LEAST16_FMTi__ = "hi"; pub const __UINT_LEAST16_TYPE__ = c_ushort; pub const __UINT_LEAST16_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 65535, .decimal); pub const __UINT_LEAST16_FMTo__ = "ho"; pub const __UINT_LEAST16_FMTu__ = "hu"; pub const __UINT_LEAST16_FMTx__ = "hx"; pub const __UINT_LEAST16_FMTX__ = "hX"; pub const __INT_LEAST32_TYPE__ = c_int; pub const __INT_LEAST32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal); pub const __INT_LEAST32_FMTd__ = "d"; pub const __INT_LEAST32_FMTi__ = "i"; pub const __UINT_LEAST32_TYPE__ = c_uint; pub const __UINT_LEAST32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 4294967295, .decimal); pub const __UINT_LEAST32_FMTo__ = "o"; pub const __UINT_LEAST32_FMTu__ = "u"; pub const __UINT_LEAST32_FMTx__ = "x"; pub const __UINT_LEAST32_FMTX__ = "X"; pub const __INT_LEAST64_TYPE__ = c_longlong; pub const __INT_LEAST64_MAX__ = @as(c_longlong, 9223372036854775807); pub const __INT_LEAST64_FMTd__ = "lld"; pub const __INT_LEAST64_FMTi__ = "lli"; pub const __UINT_LEAST64_TYPE__ = c_ulonglong; pub const __UINT_LEAST64_MAX__ = @as(c_ulonglong, 18446744073709551615); pub const __UINT_LEAST64_FMTo__ = "llo"; pub const __UINT_LEAST64_FMTu__ = "llu"; pub const __UINT_LEAST64_FMTx__ = "llx"; pub const __UINT_LEAST64_FMTX__ = "llX"; pub const __INT_FAST8_TYPE__ = i8; pub const __INT_FAST8_MAX__ = @as(c_int, 127); pub const __INT_FAST8_FMTd__ = "hhd"; pub const __INT_FAST8_FMTi__ = "hhi"; pub const __UINT_FAST8_TYPE__ = u8; pub const __UINT_FAST8_MAX__ = @as(c_int, 255); pub const __UINT_FAST8_FMTo__ = "hho"; pub const __UINT_FAST8_FMTu__ = "hhu"; pub const __UINT_FAST8_FMTx__ = "hhx"; pub const __UINT_FAST8_FMTX__ = "hhX"; pub const __INT_FAST16_TYPE__ = c_short; pub const __INT_FAST16_MAX__ = @as(c_int, 32767); pub const __INT_FAST16_FMTd__ = "hd"; pub const __INT_FAST16_FMTi__ = "hi"; pub const __UINT_FAST16_TYPE__ = c_ushort; pub const __UINT_FAST16_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 65535, .decimal); pub const __UINT_FAST16_FMTo__ = "ho"; pub const __UINT_FAST16_FMTu__ = "hu"; pub const __UINT_FAST16_FMTx__ = "hx"; pub const __UINT_FAST16_FMTX__ = "hX"; pub const __INT_FAST32_TYPE__ = c_int; pub const __INT_FAST32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal); pub const __INT_FAST32_FMTd__ = "d"; pub const __INT_FAST32_FMTi__ = "i"; pub const __UINT_FAST32_TYPE__ = c_uint; pub const __UINT_FAST32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 4294967295, .decimal); pub const __UINT_FAST32_FMTo__ = "o"; pub const __UINT_FAST32_FMTu__ = "u"; pub const __UINT_FAST32_FMTx__ = "x"; pub const __UINT_FAST32_FMTX__ = "X"; pub const __INT_FAST64_TYPE__ = c_longlong; pub const __INT_FAST64_MAX__ = @as(c_longlong, 9223372036854775807); pub const __INT_FAST64_FMTd__ = "lld"; pub const __INT_FAST64_FMTi__ = "lli"; pub const __UINT_FAST64_TYPE__ = c_ulonglong; pub const __UINT_FAST64_MAX__ = @as(c_ulonglong, 18446744073709551615); pub const __UINT_FAST64_FMTo__ = "llo"; pub const __UINT_FAST64_FMTu__ = "llu"; pub const __UINT_FAST64_FMTx__ = "llx"; pub const __UINT_FAST64_FMTX__ = "llX"; pub const __USER_LABEL_PREFIX__ = @"_"; pub const __FINITE_MATH_ONLY__ = @as(c_int, 0); pub const __GNUC_STDC_INLINE__ = @as(c_int, 1); pub const __GCC_ATOMIC_TEST_AND_SET_TRUEVAL = @as(c_int, 1); pub const __CLANG_ATOMIC_BOOL_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_CHAR_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_CHAR16_T_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_CHAR32_T_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_WCHAR_T_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_SHORT_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_INT_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_LONG_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_LLONG_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_POINTER_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_BOOL_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_CHAR_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_CHAR16_T_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_CHAR32_T_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_WCHAR_T_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_SHORT_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_INT_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_LONG_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_LLONG_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_POINTER_LOCK_FREE = @as(c_int, 2); pub const __PIC__ = @as(c_int, 2); pub const __pic__ = @as(c_int, 2); pub const __FLT_EVAL_METHOD__ = @as(c_int, 0); pub const __FLT_RADIX__ = @as(c_int, 2); pub const __DECIMAL_DIG__ = __LDBL_DECIMAL_DIG__; pub const __SSP_STRONG__ = @as(c_int, 2); pub const __nonnull = _Nonnull; pub const __null_unspecified = _Null_unspecified; pub const __nullable = _Nullable; pub const __GCC_ASM_FLAG_OUTPUTS__ = @as(c_int, 1); pub const __code_model_small__ = @as(c_int, 1); pub const __amd64__ = @as(c_int, 1); pub const __amd64 = @as(c_int, 1); pub const __x86_64 = @as(c_int, 1); pub const __x86_64__ = @as(c_int, 1); pub const __SEG_GS = @as(c_int, 1); pub const __SEG_FS = @as(c_int, 1); pub const __seg_gs = __attribute__(address_space(@as(c_int, 256))); pub const __seg_fs = __attribute__(address_space(@as(c_int, 257))); pub const __corei7 = @as(c_int, 1); pub const __corei7__ = @as(c_int, 1); pub const __tune_corei7__ = @as(c_int, 1); pub const __NO_MATH_INLINES = @as(c_int, 1); pub const __AES__ = @as(c_int, 1); pub const __PCLMUL__ = @as(c_int, 1); pub const __LAHF_SAHF__ = @as(c_int, 1); pub const __LZCNT__ = @as(c_int, 1); pub const __RDRND__ = @as(c_int, 1); pub const __FSGSBASE__ = @as(c_int, 1); pub const __BMI__ = @as(c_int, 1); pub const __BMI2__ = @as(c_int, 1); pub const __POPCNT__ = @as(c_int, 1); pub const __RTM__ = @as(c_int, 1); pub const __PRFCHW__ = @as(c_int, 1); pub const __RDSEED__ = @as(c_int, 1); pub const __ADX__ = @as(c_int, 1); pub const __MOVBE__ = @as(c_int, 1); pub const __FMA__ = @as(c_int, 1); pub const __F16C__ = @as(c_int, 1); pub const __FXSR__ = @as(c_int, 1); pub const __XSAVE__ = @as(c_int, 1); pub const __XSAVEOPT__ = @as(c_int, 1); pub const __XSAVEC__ = @as(c_int, 1); pub const __XSAVES__ = @as(c_int, 1); pub const __CLFLUSHOPT__ = @as(c_int, 1); pub const __SGX__ = @as(c_int, 1); pub const __INVPCID__ = @as(c_int, 1); pub const __AVX2__ = @as(c_int, 1); pub const __AVX__ = @as(c_int, 1); pub const __SSE4_2__ = @as(c_int, 1); pub const __SSE4_1__ = @as(c_int, 1); pub const __SSSE3__ = @as(c_int, 1); pub const __SSE3__ = @as(c_int, 1); pub const __SSE2__ = @as(c_int, 1); pub const __SSE2_MATH__ = @as(c_int, 1); pub const __SSE__ = @as(c_int, 1); pub const __SSE_MATH__ = @as(c_int, 1); pub const __MMX__ = @as(c_int, 1); pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 = @as(c_int, 1); pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 = @as(c_int, 1); pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 = @as(c_int, 1); pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 = @as(c_int, 1); pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_16 = @as(c_int, 1); pub const __APPLE_CC__ = @as(c_int, 6000); pub const __APPLE__ = @as(c_int, 1); pub const __STDC_NO_THREADS__ = @as(c_int, 1); pub const __weak = __attribute__(objc_gc(weak)); pub const __DYNAMIC__ = @as(c_int, 1); pub const __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 101406, .decimal); pub const __MACH__ = @as(c_int, 1); pub const __STDC__ = @as(c_int, 1); pub const __STDC_HOSTED__ = @as(c_int, 1); pub const __STDC_VERSION__ = @as(c_long, 201710); pub const __STDC_UTF_16__ = @as(c_int, 1); pub const __STDC_UTF_32__ = @as(c_int, 1); pub const _LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS = @as(c_int, 1); pub const _LIBCXXABI_DISABLE_VISIBILITY_ANNOTATIONS = @as(c_int, 1); pub const _LIBCPP_HAS_NO_VENDOR_AVAILABILITY_ANNOTATIONS = @as(c_int, 1); pub const _DEBUG = @as(c_int, 1); pub const WEBVIEW_HEADER = @as(c_int, 1); pub const WEBVIEW_HINT_NONE = @as(c_int, 0); pub const WEBVIEW_HINT_MIN = @as(c_int, 1); pub const WEBVIEW_HINT_MAX = @as(c_int, 2); pub const WEBVIEW_HINT_FIXED = @as(c_int, 3);
webview/webview.zig
const std = @import("std"); const spirv = @import("../spirv.zig"); pub const magic_number = 0x07230203; pub const version = (1 << 16) | (0 << 8); pub const instructions = struct { pub fn nop(self: *spirv.Builder) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try self.insns.append(self.allocator, .{ .op = 0, .operands = operands.toOwnedSlice(), }); } pub fn undef(self: *spirv.Builder, result_type: spirv.Id) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try self.insns.append(self.allocator, .{ .op = 1, .operands = operands.toOwnedSlice(), }); return result; } pub fn sourceContinued(self: *spirv.Builder, arg0: LiteralString) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, LiteralString, arg0); try self.insns.append(self.allocator, .{ .op = 2, .operands = operands.toOwnedSlice(), }); } pub fn source(self: *spirv.Builder, arg0: SourceLanguage, arg1: LiteralInteger, arg2: ?IdRef, arg3: ?LiteralString) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, SourceLanguage, arg0); try spirv.Builder.writeOperand(&operands, LiteralInteger, arg1); try spirv.Builder.writeOperand(&operands, ?IdRef, arg2); try spirv.Builder.writeOperand(&operands, ?LiteralString, arg3); try self.insns.append(self.allocator, .{ .op = 3, .operands = operands.toOwnedSlice(), }); } pub fn sourceExtension(self: *spirv.Builder, arg0: LiteralString) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, LiteralString, arg0); try self.insns.append(self.allocator, .{ .op = 4, .operands = operands.toOwnedSlice(), }); } pub fn name(self: *spirv.Builder, arg0: IdRef, arg1: LiteralString) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, LiteralString, arg1); try self.insns.append(self.allocator, .{ .op = 5, .operands = operands.toOwnedSlice(), }); } pub fn memberName(self: *spirv.Builder, arg0: IdRef, arg1: LiteralInteger, arg2: LiteralString) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, LiteralInteger, arg1); try spirv.Builder.writeOperand(&operands, LiteralString, arg2); try self.insns.append(self.allocator, .{ .op = 6, .operands = operands.toOwnedSlice(), }); } pub fn string(self: *spirv.Builder, arg0: LiteralString) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, LiteralString, arg0); try self.insns.append(self.allocator, .{ .op = 7, .operands = operands.toOwnedSlice(), }); return result; } pub fn line(self: *spirv.Builder, arg0: IdRef, arg1: LiteralInteger, arg2: LiteralInteger) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, LiteralInteger, arg1); try spirv.Builder.writeOperand(&operands, LiteralInteger, arg2); try self.insns.append(self.allocator, .{ .op = 8, .operands = operands.toOwnedSlice(), }); } pub fn extension(self: *spirv.Builder, arg0: LiteralString) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, LiteralString, arg0); try self.insns.append(self.allocator, .{ .op = 10, .operands = operands.toOwnedSlice(), }); } pub fn extInstImport(self: *spirv.Builder, arg0: LiteralString) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, LiteralString, arg0); try self.insns.append(self.allocator, .{ .op = 11, .operands = operands.toOwnedSlice(), }); return result; } pub fn extInst(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: LiteralExtInstInteger, arg2: []const IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, LiteralExtInstInteger, arg1); try spirv.Builder.writeOperand(&operands, []const IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 12, .operands = operands.toOwnedSlice(), }); return result; } pub fn memoryModel(self: *spirv.Builder, arg0: AddressingModel, arg1: MemoryModel) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, AddressingModel, arg0); try spirv.Builder.writeOperand(&operands, MemoryModel, arg1); try self.insns.append(self.allocator, .{ .op = 14, .operands = operands.toOwnedSlice(), }); } pub fn entryPoint(self: *spirv.Builder, arg0: ExecutionModel, arg1: IdRef, arg2: LiteralString, arg3: []const IdRef) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, ExecutionModel, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, LiteralString, arg2); try spirv.Builder.writeOperand(&operands, []const IdRef, arg3); try self.insns.append(self.allocator, .{ .op = 15, .operands = operands.toOwnedSlice(), }); } pub fn executionMode(self: *spirv.Builder, arg0: IdRef, arg1: ExecutionMode) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, ExecutionMode, arg1); try self.insns.append(self.allocator, .{ .op = 16, .operands = operands.toOwnedSlice(), }); } pub fn capability(self: *spirv.Builder, arg0: Capability) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, Capability, arg0); try self.insns.append(self.allocator, .{ .op = 17, .operands = operands.toOwnedSlice(), }); } pub fn typeVoid(self: *spirv.Builder) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try self.insns.append(self.allocator, .{ .op = 19, .operands = operands.toOwnedSlice(), }); return result; } pub fn typeBool(self: *spirv.Builder) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try self.insns.append(self.allocator, .{ .op = 20, .operands = operands.toOwnedSlice(), }); return result; } pub fn typeInt(self: *spirv.Builder, arg0: LiteralInteger, arg1: LiteralInteger) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, LiteralInteger, arg0); try spirv.Builder.writeOperand(&operands, LiteralInteger, arg1); try self.insns.append(self.allocator, .{ .op = 21, .operands = operands.toOwnedSlice(), }); return result; } pub fn typeFloat(self: *spirv.Builder, arg0: LiteralInteger) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, LiteralInteger, arg0); try self.insns.append(self.allocator, .{ .op = 22, .operands = operands.toOwnedSlice(), }); return result; } pub fn typeVector(self: *spirv.Builder, arg0: IdRef, arg1: LiteralInteger) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, LiteralInteger, arg1); try self.insns.append(self.allocator, .{ .op = 23, .operands = operands.toOwnedSlice(), }); return result; } pub fn typeMatrix(self: *spirv.Builder, arg0: IdRef, arg1: LiteralInteger) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, LiteralInteger, arg1); try self.insns.append(self.allocator, .{ .op = 24, .operands = operands.toOwnedSlice(), }); return result; } pub fn typeImage(self: *spirv.Builder, arg0: IdRef, arg1: Dim, arg2: LiteralInteger, arg3: LiteralInteger, arg4: LiteralInteger, arg5: LiteralInteger, arg6: ImageFormat, arg7: ?AccessQualifier) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, Dim, arg1); try spirv.Builder.writeOperand(&operands, LiteralInteger, arg2); try spirv.Builder.writeOperand(&operands, LiteralInteger, arg3); try spirv.Builder.writeOperand(&operands, LiteralInteger, arg4); try spirv.Builder.writeOperand(&operands, LiteralInteger, arg5); try spirv.Builder.writeOperand(&operands, ImageFormat, arg6); try spirv.Builder.writeOperand(&operands, ?AccessQualifier, arg7); try self.insns.append(self.allocator, .{ .op = 25, .operands = operands.toOwnedSlice(), }); return result; } pub fn typeSampler(self: *spirv.Builder) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try self.insns.append(self.allocator, .{ .op = 26, .operands = operands.toOwnedSlice(), }); return result; } pub fn typeSampledImage(self: *spirv.Builder, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 27, .operands = operands.toOwnedSlice(), }); return result; } pub fn typeArray(self: *spirv.Builder, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 28, .operands = operands.toOwnedSlice(), }); return result; } pub fn typeRuntimeArray(self: *spirv.Builder, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 29, .operands = operands.toOwnedSlice(), }); return result; } pub fn typeStruct(self: *spirv.Builder, arg0: []const IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, []const IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 30, .operands = operands.toOwnedSlice(), }); return result; } pub fn typeOpaque(self: *spirv.Builder, arg0: LiteralString) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, LiteralString, arg0); try self.insns.append(self.allocator, .{ .op = 31, .operands = operands.toOwnedSlice(), }); return result; } pub fn typePointer(self: *spirv.Builder, arg0: StorageClass, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, StorageClass, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 32, .operands = operands.toOwnedSlice(), }); return result; } pub fn typeFunction(self: *spirv.Builder, arg0: IdRef, arg1: []const IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, []const IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 33, .operands = operands.toOwnedSlice(), }); return result; } pub fn typeEvent(self: *spirv.Builder) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try self.insns.append(self.allocator, .{ .op = 34, .operands = operands.toOwnedSlice(), }); return result; } pub fn typeDeviceEvent(self: *spirv.Builder) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try self.insns.append(self.allocator, .{ .op = 35, .operands = operands.toOwnedSlice(), }); return result; } pub fn typeReserveId(self: *spirv.Builder) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try self.insns.append(self.allocator, .{ .op = 36, .operands = operands.toOwnedSlice(), }); return result; } pub fn typeQueue(self: *spirv.Builder) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try self.insns.append(self.allocator, .{ .op = 37, .operands = operands.toOwnedSlice(), }); return result; } pub fn typePipe(self: *spirv.Builder, arg0: AccessQualifier) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, AccessQualifier, arg0); try self.insns.append(self.allocator, .{ .op = 38, .operands = operands.toOwnedSlice(), }); return result; } pub fn typeForwardPointer(self: *spirv.Builder, arg0: IdRef, arg1: StorageClass) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, StorageClass, arg1); try self.insns.append(self.allocator, .{ .op = 39, .operands = operands.toOwnedSlice(), }); } pub fn constantTrue(self: *spirv.Builder, result_type: spirv.Id) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try self.insns.append(self.allocator, .{ .op = 41, .operands = operands.toOwnedSlice(), }); return result; } pub fn constantFalse(self: *spirv.Builder, result_type: spirv.Id) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try self.insns.append(self.allocator, .{ .op = 42, .operands = operands.toOwnedSlice(), }); return result; } pub fn constant(self: *spirv.Builder, result_type: spirv.Id, arg0: LiteralContextDependentNumber) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, LiteralContextDependentNumber, arg0); try self.insns.append(self.allocator, .{ .op = 43, .operands = operands.toOwnedSlice(), }); return result; } pub fn constantComposite(self: *spirv.Builder, result_type: spirv.Id, arg0: []const IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, []const IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 44, .operands = operands.toOwnedSlice(), }); return result; } pub fn constantSampler(self: *spirv.Builder, result_type: spirv.Id, arg0: SamplerAddressingMode, arg1: LiteralInteger, arg2: SamplerFilterMode) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, SamplerAddressingMode, arg0); try spirv.Builder.writeOperand(&operands, LiteralInteger, arg1); try spirv.Builder.writeOperand(&operands, SamplerFilterMode, arg2); try self.insns.append(self.allocator, .{ .op = 45, .operands = operands.toOwnedSlice(), }); return result; } pub fn constantNull(self: *spirv.Builder, result_type: spirv.Id) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try self.insns.append(self.allocator, .{ .op = 46, .operands = operands.toOwnedSlice(), }); return result; } pub fn specConstantTrue(self: *spirv.Builder, result_type: spirv.Id) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try self.insns.append(self.allocator, .{ .op = 48, .operands = operands.toOwnedSlice(), }); return result; } pub fn specConstantFalse(self: *spirv.Builder, result_type: spirv.Id) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try self.insns.append(self.allocator, .{ .op = 49, .operands = operands.toOwnedSlice(), }); return result; } pub fn specConstant(self: *spirv.Builder, result_type: spirv.Id, arg0: LiteralContextDependentNumber) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, LiteralContextDependentNumber, arg0); try self.insns.append(self.allocator, .{ .op = 50, .operands = operands.toOwnedSlice(), }); return result; } pub fn specConstantComposite(self: *spirv.Builder, result_type: spirv.Id, arg0: []const IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, []const IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 51, .operands = operands.toOwnedSlice(), }); return result; } pub fn specConstantOp(self: *spirv.Builder, result_type: spirv.Id, arg0: LiteralSpecConstantOpInteger) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, LiteralSpecConstantOpInteger, arg0); try self.insns.append(self.allocator, .{ .op = 52, .operands = operands.toOwnedSlice(), }); return result; } pub fn function(self: *spirv.Builder, result_type: spirv.Id, arg0: FunctionControl, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, FunctionControl, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 54, .operands = operands.toOwnedSlice(), }); return result; } pub fn functionParameter(self: *spirv.Builder, result_type: spirv.Id) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try self.insns.append(self.allocator, .{ .op = 55, .operands = operands.toOwnedSlice(), }); return result; } pub fn functionEnd(self: *spirv.Builder) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try self.insns.append(self.allocator, .{ .op = 56, .operands = operands.toOwnedSlice(), }); } pub fn functionCall(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: []const IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, []const IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 57, .operands = operands.toOwnedSlice(), }); return result; } pub fn variable(self: *spirv.Builder, result_type: spirv.Id, arg0: StorageClass, arg1: ?IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, StorageClass, arg0); try spirv.Builder.writeOperand(&operands, ?IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 59, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageTexelPointer(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 60, .operands = operands.toOwnedSlice(), }); return result; } pub fn load(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: ?MemoryAccess) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, ?MemoryAccess, arg1); try self.insns.append(self.allocator, .{ .op = 61, .operands = operands.toOwnedSlice(), }); return result; } pub fn store(self: *spirv.Builder, arg0: IdRef, arg1: IdRef, arg2: ?MemoryAccess) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, ?MemoryAccess, arg2); try self.insns.append(self.allocator, .{ .op = 62, .operands = operands.toOwnedSlice(), }); } pub fn copyMemory(self: *spirv.Builder, arg0: IdRef, arg1: IdRef, arg2: ?MemoryAccess) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, ?MemoryAccess, arg2); try self.insns.append(self.allocator, .{ .op = 63, .operands = operands.toOwnedSlice(), }); } pub fn copyMemorySized(self: *spirv.Builder, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: ?MemoryAccess) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, ?MemoryAccess, arg3); try self.insns.append(self.allocator, .{ .op = 64, .operands = operands.toOwnedSlice(), }); } pub fn accessChain(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: []const IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, []const IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 65, .operands = operands.toOwnedSlice(), }); return result; } pub fn inBoundsAccessChain(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: []const IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, []const IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 66, .operands = operands.toOwnedSlice(), }); return result; } pub fn ptrAccessChain(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: []const IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, []const IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 67, .operands = operands.toOwnedSlice(), }); return result; } pub fn arrayLength(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: LiteralInteger) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, LiteralInteger, arg1); try self.insns.append(self.allocator, .{ .op = 68, .operands = operands.toOwnedSlice(), }); return result; } pub fn genericPtrMemSemantics(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 69, .operands = operands.toOwnedSlice(), }); return result; } pub fn inBoundsPtrAccessChain(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: []const IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, []const IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 70, .operands = operands.toOwnedSlice(), }); return result; } pub fn decorate(self: *spirv.Builder, arg0: IdRef, arg1: Decoration) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, Decoration, arg1); try self.insns.append(self.allocator, .{ .op = 71, .operands = operands.toOwnedSlice(), }); } pub fn memberDecorate(self: *spirv.Builder, arg0: IdRef, arg1: LiteralInteger, arg2: Decoration) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, LiteralInteger, arg1); try spirv.Builder.writeOperand(&operands, Decoration, arg2); try self.insns.append(self.allocator, .{ .op = 72, .operands = operands.toOwnedSlice(), }); } pub fn decorationGroup(self: *spirv.Builder) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try self.insns.append(self.allocator, .{ .op = 73, .operands = operands.toOwnedSlice(), }); return result; } pub fn groupDecorate(self: *spirv.Builder, arg0: IdRef, arg1: []const IdRef) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, []const IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 74, .operands = operands.toOwnedSlice(), }); } pub fn groupMemberDecorate(self: *spirv.Builder, arg0: IdRef, arg1: []const PairIdRefLiteralInteger) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, []const PairIdRefLiteralInteger, arg1); try self.insns.append(self.allocator, .{ .op = 75, .operands = operands.toOwnedSlice(), }); } pub fn vectorExtractDynamic(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 77, .operands = operands.toOwnedSlice(), }); return result; } pub fn vectorInsertDynamic(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 78, .operands = operands.toOwnedSlice(), }); return result; } pub fn vectorShuffle(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: []const LiteralInteger) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, []const LiteralInteger, arg2); try self.insns.append(self.allocator, .{ .op = 79, .operands = operands.toOwnedSlice(), }); return result; } pub fn compositeConstruct(self: *spirv.Builder, result_type: spirv.Id, arg0: []const IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, []const IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 80, .operands = operands.toOwnedSlice(), }); return result; } pub fn compositeExtract(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: []const LiteralInteger) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, []const LiteralInteger, arg1); try self.insns.append(self.allocator, .{ .op = 81, .operands = operands.toOwnedSlice(), }); return result; } pub fn compositeInsert(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: []const LiteralInteger) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, []const LiteralInteger, arg2); try self.insns.append(self.allocator, .{ .op = 82, .operands = operands.toOwnedSlice(), }); return result; } pub fn copyObject(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 83, .operands = operands.toOwnedSlice(), }); return result; } pub fn transpose(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 84, .operands = operands.toOwnedSlice(), }); return result; } pub fn sampledImage(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 86, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageSampleImplicitLod(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: ?ImageOperands) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, ?ImageOperands, arg2); try self.insns.append(self.allocator, .{ .op = 87, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageSampleExplicitLod(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: ImageOperands) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, ImageOperands, arg2); try self.insns.append(self.allocator, .{ .op = 88, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageSampleDrefImplicitLod(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: ?ImageOperands) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, ?ImageOperands, arg3); try self.insns.append(self.allocator, .{ .op = 89, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageSampleDrefExplicitLod(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: ImageOperands) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, ImageOperands, arg3); try self.insns.append(self.allocator, .{ .op = 90, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageSampleProjImplicitLod(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: ?ImageOperands) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, ?ImageOperands, arg2); try self.insns.append(self.allocator, .{ .op = 91, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageSampleProjExplicitLod(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: ImageOperands) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, ImageOperands, arg2); try self.insns.append(self.allocator, .{ .op = 92, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageSampleProjDrefImplicitLod(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: ?ImageOperands) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, ?ImageOperands, arg3); try self.insns.append(self.allocator, .{ .op = 93, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageSampleProjDrefExplicitLod(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: ImageOperands) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, ImageOperands, arg3); try self.insns.append(self.allocator, .{ .op = 94, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageFetch(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: ?ImageOperands) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, ?ImageOperands, arg2); try self.insns.append(self.allocator, .{ .op = 95, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageGather(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: ?ImageOperands) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, ?ImageOperands, arg3); try self.insns.append(self.allocator, .{ .op = 96, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageDrefGather(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: ?ImageOperands) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, ?ImageOperands, arg3); try self.insns.append(self.allocator, .{ .op = 97, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageRead(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: ?ImageOperands) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, ?ImageOperands, arg2); try self.insns.append(self.allocator, .{ .op = 98, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageWrite(self: *spirv.Builder, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: ?ImageOperands) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, ?ImageOperands, arg3); try self.insns.append(self.allocator, .{ .op = 99, .operands = operands.toOwnedSlice(), }); } pub fn image(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 100, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageQueryFormat(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 101, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageQueryOrder(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 102, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageQuerySizeLod(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 103, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageQuerySize(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 104, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageQueryLod(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 105, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageQueryLevels(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 106, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageQuerySamples(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 107, .operands = operands.toOwnedSlice(), }); return result; } pub fn convertFToU(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 109, .operands = operands.toOwnedSlice(), }); return result; } pub fn convertFToS(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 110, .operands = operands.toOwnedSlice(), }); return result; } pub fn convertSToF(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 111, .operands = operands.toOwnedSlice(), }); return result; } pub fn convertUToF(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 112, .operands = operands.toOwnedSlice(), }); return result; } pub fn uConvert(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 113, .operands = operands.toOwnedSlice(), }); return result; } pub fn sConvert(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 114, .operands = operands.toOwnedSlice(), }); return result; } pub fn fConvert(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 115, .operands = operands.toOwnedSlice(), }); return result; } pub fn quantizeToF16(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 116, .operands = operands.toOwnedSlice(), }); return result; } pub fn convertPtrToU(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 117, .operands = operands.toOwnedSlice(), }); return result; } pub fn satConvertSToU(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 118, .operands = operands.toOwnedSlice(), }); return result; } pub fn satConvertUToS(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 119, .operands = operands.toOwnedSlice(), }); return result; } pub fn convertUToPtr(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 120, .operands = operands.toOwnedSlice(), }); return result; } pub fn ptrCastToGeneric(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 121, .operands = operands.toOwnedSlice(), }); return result; } pub fn genericCastToPtr(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 122, .operands = operands.toOwnedSlice(), }); return result; } pub fn genericCastToPtrExplicit(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: StorageClass) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, StorageClass, arg1); try self.insns.append(self.allocator, .{ .op = 123, .operands = operands.toOwnedSlice(), }); return result; } pub fn bitcast(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 124, .operands = operands.toOwnedSlice(), }); return result; } pub fn sNegate(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 126, .operands = operands.toOwnedSlice(), }); return result; } pub fn fNegate(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 127, .operands = operands.toOwnedSlice(), }); return result; } pub fn iAdd(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 128, .operands = operands.toOwnedSlice(), }); return result; } pub fn fAdd(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 129, .operands = operands.toOwnedSlice(), }); return result; } pub fn iSub(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 130, .operands = operands.toOwnedSlice(), }); return result; } pub fn fSub(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 131, .operands = operands.toOwnedSlice(), }); return result; } pub fn iMul(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 132, .operands = operands.toOwnedSlice(), }); return result; } pub fn fMul(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 133, .operands = operands.toOwnedSlice(), }); return result; } pub fn uDiv(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 134, .operands = operands.toOwnedSlice(), }); return result; } pub fn sDiv(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 135, .operands = operands.toOwnedSlice(), }); return result; } pub fn fDiv(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 136, .operands = operands.toOwnedSlice(), }); return result; } pub fn uMod(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 137, .operands = operands.toOwnedSlice(), }); return result; } pub fn sRem(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 138, .operands = operands.toOwnedSlice(), }); return result; } pub fn sMod(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 139, .operands = operands.toOwnedSlice(), }); return result; } pub fn fRem(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 140, .operands = operands.toOwnedSlice(), }); return result; } pub fn fMod(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 141, .operands = operands.toOwnedSlice(), }); return result; } pub fn vectorTimesScalar(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 142, .operands = operands.toOwnedSlice(), }); return result; } pub fn matrixTimesScalar(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 143, .operands = operands.toOwnedSlice(), }); return result; } pub fn vectorTimesMatrix(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 144, .operands = operands.toOwnedSlice(), }); return result; } pub fn matrixTimesVector(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 145, .operands = operands.toOwnedSlice(), }); return result; } pub fn matrixTimesMatrix(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 146, .operands = operands.toOwnedSlice(), }); return result; } pub fn outerProduct(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 147, .operands = operands.toOwnedSlice(), }); return result; } pub fn dot(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 148, .operands = operands.toOwnedSlice(), }); return result; } pub fn iAddCarry(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 149, .operands = operands.toOwnedSlice(), }); return result; } pub fn iSubBorrow(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 150, .operands = operands.toOwnedSlice(), }); return result; } pub fn uMulExtended(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 151, .operands = operands.toOwnedSlice(), }); return result; } pub fn sMulExtended(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 152, .operands = operands.toOwnedSlice(), }); return result; } pub fn any(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 154, .operands = operands.toOwnedSlice(), }); return result; } pub fn all(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 155, .operands = operands.toOwnedSlice(), }); return result; } pub fn isNan(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 156, .operands = operands.toOwnedSlice(), }); return result; } pub fn isInf(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 157, .operands = operands.toOwnedSlice(), }); return result; } pub fn isFinite(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 158, .operands = operands.toOwnedSlice(), }); return result; } pub fn isNormal(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 159, .operands = operands.toOwnedSlice(), }); return result; } pub fn signBitSet(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 160, .operands = operands.toOwnedSlice(), }); return result; } pub fn lessOrGreater(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 161, .operands = operands.toOwnedSlice(), }); return result; } pub fn ordered(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 162, .operands = operands.toOwnedSlice(), }); return result; } pub fn unordered(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 163, .operands = operands.toOwnedSlice(), }); return result; } pub fn logicalEqual(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 164, .operands = operands.toOwnedSlice(), }); return result; } pub fn logicalNotEqual(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 165, .operands = operands.toOwnedSlice(), }); return result; } pub fn logicalOr(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 166, .operands = operands.toOwnedSlice(), }); return result; } pub fn logicalAnd(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 167, .operands = operands.toOwnedSlice(), }); return result; } pub fn logicalNot(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 168, .operands = operands.toOwnedSlice(), }); return result; } pub fn select(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 169, .operands = operands.toOwnedSlice(), }); return result; } pub fn iEqual(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 170, .operands = operands.toOwnedSlice(), }); return result; } pub fn iNotEqual(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 171, .operands = operands.toOwnedSlice(), }); return result; } pub fn uGreaterThan(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 172, .operands = operands.toOwnedSlice(), }); return result; } pub fn sGreaterThan(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 173, .operands = operands.toOwnedSlice(), }); return result; } pub fn uGreaterThanEqual(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 174, .operands = operands.toOwnedSlice(), }); return result; } pub fn sGreaterThanEqual(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 175, .operands = operands.toOwnedSlice(), }); return result; } pub fn uLessThan(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 176, .operands = operands.toOwnedSlice(), }); return result; } pub fn sLessThan(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 177, .operands = operands.toOwnedSlice(), }); return result; } pub fn uLessThanEqual(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 178, .operands = operands.toOwnedSlice(), }); return result; } pub fn sLessThanEqual(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 179, .operands = operands.toOwnedSlice(), }); return result; } pub fn fOrdEqual(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 180, .operands = operands.toOwnedSlice(), }); return result; } pub fn fUnordEqual(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 181, .operands = operands.toOwnedSlice(), }); return result; } pub fn fOrdNotEqual(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 182, .operands = operands.toOwnedSlice(), }); return result; } pub fn fUnordNotEqual(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 183, .operands = operands.toOwnedSlice(), }); return result; } pub fn fOrdLessThan(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 184, .operands = operands.toOwnedSlice(), }); return result; } pub fn fUnordLessThan(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 185, .operands = operands.toOwnedSlice(), }); return result; } pub fn fOrdGreaterThan(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 186, .operands = operands.toOwnedSlice(), }); return result; } pub fn fUnordGreaterThan(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 187, .operands = operands.toOwnedSlice(), }); return result; } pub fn fOrdLessThanEqual(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 188, .operands = operands.toOwnedSlice(), }); return result; } pub fn fUnordLessThanEqual(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 189, .operands = operands.toOwnedSlice(), }); return result; } pub fn fOrdGreaterThanEqual(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 190, .operands = operands.toOwnedSlice(), }); return result; } pub fn fUnordGreaterThanEqual(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 191, .operands = operands.toOwnedSlice(), }); return result; } pub fn shiftRightLogical(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 194, .operands = operands.toOwnedSlice(), }); return result; } pub fn shiftRightArithmetic(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 195, .operands = operands.toOwnedSlice(), }); return result; } pub fn shiftLeftLogical(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 196, .operands = operands.toOwnedSlice(), }); return result; } pub fn bitwiseOr(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 197, .operands = operands.toOwnedSlice(), }); return result; } pub fn bitwiseXor(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 198, .operands = operands.toOwnedSlice(), }); return result; } pub fn bitwiseAnd(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 199, .operands = operands.toOwnedSlice(), }); return result; } pub fn not(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 200, .operands = operands.toOwnedSlice(), }); return result; } pub fn bitFieldInsert(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try self.insns.append(self.allocator, .{ .op = 201, .operands = operands.toOwnedSlice(), }); return result; } pub fn bitFieldSExtract(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 202, .operands = operands.toOwnedSlice(), }); return result; } pub fn bitFieldUExtract(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 203, .operands = operands.toOwnedSlice(), }); return result; } pub fn bitReverse(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 204, .operands = operands.toOwnedSlice(), }); return result; } pub fn bitCount(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 205, .operands = operands.toOwnedSlice(), }); return result; } pub fn dPdx(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 207, .operands = operands.toOwnedSlice(), }); return result; } pub fn dPdy(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 208, .operands = operands.toOwnedSlice(), }); return result; } pub fn fwidth(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 209, .operands = operands.toOwnedSlice(), }); return result; } pub fn dPdxFine(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 210, .operands = operands.toOwnedSlice(), }); return result; } pub fn dPdyFine(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 211, .operands = operands.toOwnedSlice(), }); return result; } pub fn fwidthFine(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 212, .operands = operands.toOwnedSlice(), }); return result; } pub fn dPdxCoarse(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 213, .operands = operands.toOwnedSlice(), }); return result; } pub fn dPdyCoarse(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 214, .operands = operands.toOwnedSlice(), }); return result; } pub fn fwidthCoarse(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 215, .operands = operands.toOwnedSlice(), }); return result; } pub fn emitVertex(self: *spirv.Builder) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try self.insns.append(self.allocator, .{ .op = 218, .operands = operands.toOwnedSlice(), }); } pub fn endPrimitive(self: *spirv.Builder) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try self.insns.append(self.allocator, .{ .op = 219, .operands = operands.toOwnedSlice(), }); } pub fn emitStreamVertex(self: *spirv.Builder, arg0: IdRef) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 220, .operands = operands.toOwnedSlice(), }); } pub fn endStreamPrimitive(self: *spirv.Builder, arg0: IdRef) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 221, .operands = operands.toOwnedSlice(), }); } pub fn controlBarrier(self: *spirv.Builder, arg0: IdScope, arg1: IdScope, arg2: IdMemorySemantics) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, IdScope, arg1); try spirv.Builder.writeOperand(&operands, IdMemorySemantics, arg2); try self.insns.append(self.allocator, .{ .op = 224, .operands = operands.toOwnedSlice(), }); } pub fn memoryBarrier(self: *spirv.Builder, arg0: IdScope, arg1: IdMemorySemantics) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, IdMemorySemantics, arg1); try self.insns.append(self.allocator, .{ .op = 225, .operands = operands.toOwnedSlice(), }); } pub fn atomicLoad(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdScope, arg2: IdMemorySemantics) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdScope, arg1); try spirv.Builder.writeOperand(&operands, IdMemorySemantics, arg2); try self.insns.append(self.allocator, .{ .op = 227, .operands = operands.toOwnedSlice(), }); return result; } pub fn atomicStore(self: *spirv.Builder, arg0: IdRef, arg1: IdScope, arg2: IdMemorySemantics, arg3: IdRef) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdScope, arg1); try spirv.Builder.writeOperand(&operands, IdMemorySemantics, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try self.insns.append(self.allocator, .{ .op = 228, .operands = operands.toOwnedSlice(), }); } pub fn atomicExchange(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdScope, arg2: IdMemorySemantics, arg3: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdScope, arg1); try spirv.Builder.writeOperand(&operands, IdMemorySemantics, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try self.insns.append(self.allocator, .{ .op = 229, .operands = operands.toOwnedSlice(), }); return result; } pub fn atomicCompareExchange(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdScope, arg2: IdMemorySemantics, arg3: IdMemorySemantics, arg4: IdRef, arg5: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdScope, arg1); try spirv.Builder.writeOperand(&operands, IdMemorySemantics, arg2); try spirv.Builder.writeOperand(&operands, IdMemorySemantics, arg3); try spirv.Builder.writeOperand(&operands, IdRef, arg4); try spirv.Builder.writeOperand(&operands, IdRef, arg5); try self.insns.append(self.allocator, .{ .op = 230, .operands = operands.toOwnedSlice(), }); return result; } pub fn atomicCompareExchangeWeak(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdScope, arg2: IdMemorySemantics, arg3: IdMemorySemantics, arg4: IdRef, arg5: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdScope, arg1); try spirv.Builder.writeOperand(&operands, IdMemorySemantics, arg2); try spirv.Builder.writeOperand(&operands, IdMemorySemantics, arg3); try spirv.Builder.writeOperand(&operands, IdRef, arg4); try spirv.Builder.writeOperand(&operands, IdRef, arg5); try self.insns.append(self.allocator, .{ .op = 231, .operands = operands.toOwnedSlice(), }); return result; } pub fn atomicIIncrement(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdScope, arg2: IdMemorySemantics) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdScope, arg1); try spirv.Builder.writeOperand(&operands, IdMemorySemantics, arg2); try self.insns.append(self.allocator, .{ .op = 232, .operands = operands.toOwnedSlice(), }); return result; } pub fn atomicIDecrement(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdScope, arg2: IdMemorySemantics) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdScope, arg1); try spirv.Builder.writeOperand(&operands, IdMemorySemantics, arg2); try self.insns.append(self.allocator, .{ .op = 233, .operands = operands.toOwnedSlice(), }); return result; } pub fn atomicIAdd(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdScope, arg2: IdMemorySemantics, arg3: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdScope, arg1); try spirv.Builder.writeOperand(&operands, IdMemorySemantics, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try self.insns.append(self.allocator, .{ .op = 234, .operands = operands.toOwnedSlice(), }); return result; } pub fn atomicISub(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdScope, arg2: IdMemorySemantics, arg3: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdScope, arg1); try spirv.Builder.writeOperand(&operands, IdMemorySemantics, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try self.insns.append(self.allocator, .{ .op = 235, .operands = operands.toOwnedSlice(), }); return result; } pub fn atomicSMin(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdScope, arg2: IdMemorySemantics, arg3: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdScope, arg1); try spirv.Builder.writeOperand(&operands, IdMemorySemantics, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try self.insns.append(self.allocator, .{ .op = 236, .operands = operands.toOwnedSlice(), }); return result; } pub fn atomicUMin(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdScope, arg2: IdMemorySemantics, arg3: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdScope, arg1); try spirv.Builder.writeOperand(&operands, IdMemorySemantics, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try self.insns.append(self.allocator, .{ .op = 237, .operands = operands.toOwnedSlice(), }); return result; } pub fn atomicSMax(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdScope, arg2: IdMemorySemantics, arg3: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdScope, arg1); try spirv.Builder.writeOperand(&operands, IdMemorySemantics, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try self.insns.append(self.allocator, .{ .op = 238, .operands = operands.toOwnedSlice(), }); return result; } pub fn atomicUMax(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdScope, arg2: IdMemorySemantics, arg3: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdScope, arg1); try spirv.Builder.writeOperand(&operands, IdMemorySemantics, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try self.insns.append(self.allocator, .{ .op = 239, .operands = operands.toOwnedSlice(), }); return result; } pub fn atomicAnd(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdScope, arg2: IdMemorySemantics, arg3: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdScope, arg1); try spirv.Builder.writeOperand(&operands, IdMemorySemantics, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try self.insns.append(self.allocator, .{ .op = 240, .operands = operands.toOwnedSlice(), }); return result; } pub fn atomicOr(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdScope, arg2: IdMemorySemantics, arg3: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdScope, arg1); try spirv.Builder.writeOperand(&operands, IdMemorySemantics, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try self.insns.append(self.allocator, .{ .op = 241, .operands = operands.toOwnedSlice(), }); return result; } pub fn atomicXor(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdScope, arg2: IdMemorySemantics, arg3: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdScope, arg1); try spirv.Builder.writeOperand(&operands, IdMemorySemantics, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try self.insns.append(self.allocator, .{ .op = 242, .operands = operands.toOwnedSlice(), }); return result; } pub fn phi(self: *spirv.Builder, result_type: spirv.Id, arg0: []const PairIdRefIdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, []const PairIdRefIdRef, arg0); try self.insns.append(self.allocator, .{ .op = 245, .operands = operands.toOwnedSlice(), }); return result; } pub fn loopMerge(self: *spirv.Builder, arg0: IdRef, arg1: IdRef, arg2: LoopControl) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, LoopControl, arg2); try self.insns.append(self.allocator, .{ .op = 246, .operands = operands.toOwnedSlice(), }); } pub fn selectionMerge(self: *spirv.Builder, arg0: IdRef, arg1: SelectionControl) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, SelectionControl, arg1); try self.insns.append(self.allocator, .{ .op = 247, .operands = operands.toOwnedSlice(), }); } pub fn label(self: *spirv.Builder) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try self.insns.append(self.allocator, .{ .op = 248, .operands = operands.toOwnedSlice(), }); return result; } pub fn branch(self: *spirv.Builder, arg0: IdRef) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 249, .operands = operands.toOwnedSlice(), }); } pub fn branchConditional(self: *spirv.Builder, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: []const LiteralInteger) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, []const LiteralInteger, arg3); try self.insns.append(self.allocator, .{ .op = 250, .operands = operands.toOwnedSlice(), }); } pub fn @"switch"(self: *spirv.Builder, arg0: IdRef, arg1: IdRef, arg2: []const PairLiteralIntegerIdRef) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, []const PairLiteralIntegerIdRef, arg2); try self.insns.append(self.allocator, .{ .op = 251, .operands = operands.toOwnedSlice(), }); } pub fn kill(self: *spirv.Builder) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try self.insns.append(self.allocator, .{ .op = 252, .operands = operands.toOwnedSlice(), }); } pub fn @"return"(self: *spirv.Builder) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try self.insns.append(self.allocator, .{ .op = 253, .operands = operands.toOwnedSlice(), }); } pub fn returnValue(self: *spirv.Builder, arg0: IdRef) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 254, .operands = operands.toOwnedSlice(), }); } pub fn @"unreachable"(self: *spirv.Builder) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try self.insns.append(self.allocator, .{ .op = 255, .operands = operands.toOwnedSlice(), }); } pub fn lifetimeStart(self: *spirv.Builder, arg0: IdRef, arg1: LiteralInteger) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, LiteralInteger, arg1); try self.insns.append(self.allocator, .{ .op = 256, .operands = operands.toOwnedSlice(), }); } pub fn lifetimeStop(self: *spirv.Builder, arg0: IdRef, arg1: LiteralInteger) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, LiteralInteger, arg1); try self.insns.append(self.allocator, .{ .op = 257, .operands = operands.toOwnedSlice(), }); } pub fn groupAsyncCopy(self: *spirv.Builder, result_type: spirv.Id, arg0: IdScope, arg1: IdRef, arg2: IdRef, arg3: IdRef, arg4: IdRef, arg5: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try spirv.Builder.writeOperand(&operands, IdRef, arg4); try spirv.Builder.writeOperand(&operands, IdRef, arg5); try self.insns.append(self.allocator, .{ .op = 259, .operands = operands.toOwnedSlice(), }); return result; } pub fn groupWaitEvents(self: *spirv.Builder, arg0: IdScope, arg1: IdRef, arg2: IdRef) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 260, .operands = operands.toOwnedSlice(), }); } pub fn groupAll(self: *spirv.Builder, result_type: spirv.Id, arg0: IdScope, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 261, .operands = operands.toOwnedSlice(), }); return result; } pub fn groupAny(self: *spirv.Builder, result_type: spirv.Id, arg0: IdScope, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 262, .operands = operands.toOwnedSlice(), }); return result; } pub fn groupBroadcast(self: *spirv.Builder, result_type: spirv.Id, arg0: IdScope, arg1: IdRef, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 263, .operands = operands.toOwnedSlice(), }); return result; } pub fn groupIAdd(self: *spirv.Builder, result_type: spirv.Id, arg0: IdScope, arg1: GroupOperation, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, GroupOperation, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 264, .operands = operands.toOwnedSlice(), }); return result; } pub fn groupFAdd(self: *spirv.Builder, result_type: spirv.Id, arg0: IdScope, arg1: GroupOperation, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, GroupOperation, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 265, .operands = operands.toOwnedSlice(), }); return result; } pub fn groupFMin(self: *spirv.Builder, result_type: spirv.Id, arg0: IdScope, arg1: GroupOperation, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, GroupOperation, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 266, .operands = operands.toOwnedSlice(), }); return result; } pub fn groupUMin(self: *spirv.Builder, result_type: spirv.Id, arg0: IdScope, arg1: GroupOperation, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, GroupOperation, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 267, .operands = operands.toOwnedSlice(), }); return result; } pub fn groupSMin(self: *spirv.Builder, result_type: spirv.Id, arg0: IdScope, arg1: GroupOperation, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, GroupOperation, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 268, .operands = operands.toOwnedSlice(), }); return result; } pub fn groupFMax(self: *spirv.Builder, result_type: spirv.Id, arg0: IdScope, arg1: GroupOperation, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, GroupOperation, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 269, .operands = operands.toOwnedSlice(), }); return result; } pub fn groupUMax(self: *spirv.Builder, result_type: spirv.Id, arg0: IdScope, arg1: GroupOperation, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, GroupOperation, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 270, .operands = operands.toOwnedSlice(), }); return result; } pub fn groupSMax(self: *spirv.Builder, result_type: spirv.Id, arg0: IdScope, arg1: GroupOperation, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, GroupOperation, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 271, .operands = operands.toOwnedSlice(), }); return result; } pub fn readPipe(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try self.insns.append(self.allocator, .{ .op = 274, .operands = operands.toOwnedSlice(), }); return result; } pub fn writePipe(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try self.insns.append(self.allocator, .{ .op = 275, .operands = operands.toOwnedSlice(), }); return result; } pub fn reservedReadPipe(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: IdRef, arg4: IdRef, arg5: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try spirv.Builder.writeOperand(&operands, IdRef, arg4); try spirv.Builder.writeOperand(&operands, IdRef, arg5); try self.insns.append(self.allocator, .{ .op = 276, .operands = operands.toOwnedSlice(), }); return result; } pub fn reservedWritePipe(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: IdRef, arg4: IdRef, arg5: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try spirv.Builder.writeOperand(&operands, IdRef, arg4); try spirv.Builder.writeOperand(&operands, IdRef, arg5); try self.insns.append(self.allocator, .{ .op = 277, .operands = operands.toOwnedSlice(), }); return result; } pub fn reserveReadPipePackets(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try self.insns.append(self.allocator, .{ .op = 278, .operands = operands.toOwnedSlice(), }); return result; } pub fn reserveWritePipePackets(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try self.insns.append(self.allocator, .{ .op = 279, .operands = operands.toOwnedSlice(), }); return result; } pub fn commitReadPipe(self: *spirv.Builder, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: IdRef) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try self.insns.append(self.allocator, .{ .op = 280, .operands = operands.toOwnedSlice(), }); } pub fn commitWritePipe(self: *spirv.Builder, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: IdRef) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try self.insns.append(self.allocator, .{ .op = 281, .operands = operands.toOwnedSlice(), }); } pub fn isValidReserveId(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 282, .operands = operands.toOwnedSlice(), }); return result; } pub fn getNumPipePackets(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 283, .operands = operands.toOwnedSlice(), }); return result; } pub fn getMaxPipePackets(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 284, .operands = operands.toOwnedSlice(), }); return result; } pub fn groupReserveReadPipePackets(self: *spirv.Builder, result_type: spirv.Id, arg0: IdScope, arg1: IdRef, arg2: IdRef, arg3: IdRef, arg4: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try spirv.Builder.writeOperand(&operands, IdRef, arg4); try self.insns.append(self.allocator, .{ .op = 285, .operands = operands.toOwnedSlice(), }); return result; } pub fn groupReserveWritePipePackets(self: *spirv.Builder, result_type: spirv.Id, arg0: IdScope, arg1: IdRef, arg2: IdRef, arg3: IdRef, arg4: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try spirv.Builder.writeOperand(&operands, IdRef, arg4); try self.insns.append(self.allocator, .{ .op = 286, .operands = operands.toOwnedSlice(), }); return result; } pub fn groupCommitReadPipe(self: *spirv.Builder, arg0: IdScope, arg1: IdRef, arg2: IdRef, arg3: IdRef, arg4: IdRef) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try spirv.Builder.writeOperand(&operands, IdRef, arg4); try self.insns.append(self.allocator, .{ .op = 287, .operands = operands.toOwnedSlice(), }); } pub fn groupCommitWritePipe(self: *spirv.Builder, arg0: IdScope, arg1: IdRef, arg2: IdRef, arg3: IdRef, arg4: IdRef) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try spirv.Builder.writeOperand(&operands, IdRef, arg4); try self.insns.append(self.allocator, .{ .op = 288, .operands = operands.toOwnedSlice(), }); } pub fn enqueueMarker(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try self.insns.append(self.allocator, .{ .op = 291, .operands = operands.toOwnedSlice(), }); return result; } pub fn enqueueKernel(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: IdRef, arg4: IdRef, arg5: IdRef, arg6: IdRef, arg7: IdRef, arg8: IdRef, arg9: IdRef, arg10: []const IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try spirv.Builder.writeOperand(&operands, IdRef, arg4); try spirv.Builder.writeOperand(&operands, IdRef, arg5); try spirv.Builder.writeOperand(&operands, IdRef, arg6); try spirv.Builder.writeOperand(&operands, IdRef, arg7); try spirv.Builder.writeOperand(&operands, IdRef, arg8); try spirv.Builder.writeOperand(&operands, IdRef, arg9); try spirv.Builder.writeOperand(&operands, []const IdRef, arg10); try self.insns.append(self.allocator, .{ .op = 292, .operands = operands.toOwnedSlice(), }); return result; } pub fn getKernelNDrangeSubGroupCount(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: IdRef, arg4: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try spirv.Builder.writeOperand(&operands, IdRef, arg4); try self.insns.append(self.allocator, .{ .op = 293, .operands = operands.toOwnedSlice(), }); return result; } pub fn getKernelNDrangeMaxSubGroupSize(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: IdRef, arg4: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try spirv.Builder.writeOperand(&operands, IdRef, arg4); try self.insns.append(self.allocator, .{ .op = 294, .operands = operands.toOwnedSlice(), }); return result; } pub fn getKernelWorkGroupSize(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try self.insns.append(self.allocator, .{ .op = 295, .operands = operands.toOwnedSlice(), }); return result; } pub fn getKernelPreferredWorkGroupSizeMultiple(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, IdRef, arg3); try self.insns.append(self.allocator, .{ .op = 296, .operands = operands.toOwnedSlice(), }); return result; } pub fn retainEvent(self: *spirv.Builder, arg0: IdRef) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 297, .operands = operands.toOwnedSlice(), }); } pub fn releaseEvent(self: *spirv.Builder, arg0: IdRef) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 298, .operands = operands.toOwnedSlice(), }); } pub fn createUserEvent(self: *spirv.Builder, result_type: spirv.Id) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try self.insns.append(self.allocator, .{ .op = 299, .operands = operands.toOwnedSlice(), }); return result; } pub fn isValidEvent(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 300, .operands = operands.toOwnedSlice(), }); return result; } pub fn setUserEventStatus(self: *spirv.Builder, arg0: IdRef, arg1: IdRef) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 301, .operands = operands.toOwnedSlice(), }); } pub fn captureEventProfilingInfo(self: *spirv.Builder, arg0: IdRef, arg1: IdRef, arg2: IdRef) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 302, .operands = operands.toOwnedSlice(), }); } pub fn getDefaultQueue(self: *spirv.Builder, result_type: spirv.Id) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try self.insns.append(self.allocator, .{ .op = 303, .operands = operands.toOwnedSlice(), }); return result; } pub fn buildNDRange(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 304, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageSparseSampleImplicitLod(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: ?ImageOperands) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, ?ImageOperands, arg2); try self.insns.append(self.allocator, .{ .op = 305, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageSparseSampleExplicitLod(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: ImageOperands) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, ImageOperands, arg2); try self.insns.append(self.allocator, .{ .op = 306, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageSparseSampleDrefImplicitLod(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: ?ImageOperands) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, ?ImageOperands, arg3); try self.insns.append(self.allocator, .{ .op = 307, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageSparseSampleDrefExplicitLod(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: ImageOperands) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, ImageOperands, arg3); try self.insns.append(self.allocator, .{ .op = 308, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageSparseSampleProjImplicitLod(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: ?ImageOperands) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, ?ImageOperands, arg2); try self.insns.append(self.allocator, .{ .op = 309, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageSparseSampleProjExplicitLod(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: ImageOperands) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, ImageOperands, arg2); try self.insns.append(self.allocator, .{ .op = 310, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageSparseSampleProjDrefImplicitLod(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: ?ImageOperands) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, ?ImageOperands, arg3); try self.insns.append(self.allocator, .{ .op = 311, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageSparseSampleProjDrefExplicitLod(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: ImageOperands) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, ImageOperands, arg3); try self.insns.append(self.allocator, .{ .op = 312, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageSparseFetch(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: ?ImageOperands) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, ?ImageOperands, arg2); try self.insns.append(self.allocator, .{ .op = 313, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageSparseGather(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: ?ImageOperands) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, ?ImageOperands, arg3); try self.insns.append(self.allocator, .{ .op = 314, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageSparseDrefGather(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef, arg3: ?ImageOperands) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try spirv.Builder.writeOperand(&operands, ?ImageOperands, arg3); try self.insns.append(self.allocator, .{ .op = 315, .operands = operands.toOwnedSlice(), }); return result; } pub fn imageSparseTexelsResident(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 316, .operands = operands.toOwnedSlice(), }); return result; } pub fn noLine(self: *spirv.Builder) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try self.insns.append(self.allocator, .{ .op = 317, .operands = operands.toOwnedSlice(), }); } pub fn atomicFlagTestAndSet(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdScope, arg2: IdMemorySemantics) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdScope, arg1); try spirv.Builder.writeOperand(&operands, IdMemorySemantics, arg2); try self.insns.append(self.allocator, .{ .op = 318, .operands = operands.toOwnedSlice(), }); return result; } pub fn atomicFlagClear(self: *spirv.Builder, arg0: IdRef, arg1: IdScope, arg2: IdMemorySemantics) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdScope, arg1); try spirv.Builder.writeOperand(&operands, IdMemorySemantics, arg2); try self.insns.append(self.allocator, .{ .op = 319, .operands = operands.toOwnedSlice(), }); } pub fn imageSparseRead(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: ?ImageOperands) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, ?ImageOperands, arg2); try self.insns.append(self.allocator, .{ .op = 320, .operands = operands.toOwnedSlice(), }); return result; } pub fn decorateId(self: *spirv.Builder, arg0: IdRef, arg1: Decoration) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, Decoration, arg1); try self.insns.append(self.allocator, .{ .op = 332, .operands = operands.toOwnedSlice(), }); } pub fn subgroupBallotKhr(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 4421, .operands = operands.toOwnedSlice(), }); return result; } pub fn subgroupFirstInvocationKhr(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 4422, .operands = operands.toOwnedSlice(), }); return result; } pub fn subgroupAllKhr(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 4428, .operands = operands.toOwnedSlice(), }); return result; } pub fn subgroupAnyKhr(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 4429, .operands = operands.toOwnedSlice(), }); return result; } pub fn subgroupAllEqualKhr(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 4430, .operands = operands.toOwnedSlice(), }); return result; } pub fn subgroupReadInvocationKhr(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 4432, .operands = operands.toOwnedSlice(), }); return result; } pub fn groupIAddNonUniformAmd(self: *spirv.Builder, result_type: spirv.Id, arg0: IdScope, arg1: GroupOperation, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, GroupOperation, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 5000, .operands = operands.toOwnedSlice(), }); return result; } pub fn groupFAddNonUniformAmd(self: *spirv.Builder, result_type: spirv.Id, arg0: IdScope, arg1: GroupOperation, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, GroupOperation, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 5001, .operands = operands.toOwnedSlice(), }); return result; } pub fn groupFMinNonUniformAmd(self: *spirv.Builder, result_type: spirv.Id, arg0: IdScope, arg1: GroupOperation, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, GroupOperation, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 5002, .operands = operands.toOwnedSlice(), }); return result; } pub fn groupUMinNonUniformAmd(self: *spirv.Builder, result_type: spirv.Id, arg0: IdScope, arg1: GroupOperation, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, GroupOperation, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 5003, .operands = operands.toOwnedSlice(), }); return result; } pub fn groupSMinNonUniformAmd(self: *spirv.Builder, result_type: spirv.Id, arg0: IdScope, arg1: GroupOperation, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, GroupOperation, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 5004, .operands = operands.toOwnedSlice(), }); return result; } pub fn groupFMaxNonUniformAmd(self: *spirv.Builder, result_type: spirv.Id, arg0: IdScope, arg1: GroupOperation, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, GroupOperation, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 5005, .operands = operands.toOwnedSlice(), }); return result; } pub fn groupUMaxNonUniformAmd(self: *spirv.Builder, result_type: spirv.Id, arg0: IdScope, arg1: GroupOperation, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, GroupOperation, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 5006, .operands = operands.toOwnedSlice(), }); return result; } pub fn groupSMaxNonUniformAmd(self: *spirv.Builder, result_type: spirv.Id, arg0: IdScope, arg1: GroupOperation, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdScope, arg0); try spirv.Builder.writeOperand(&operands, GroupOperation, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 5007, .operands = operands.toOwnedSlice(), }); return result; } pub fn fragmentMaskFetchAmd(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 5011, .operands = operands.toOwnedSlice(), }); return result; } pub fn fragmentFetchAmd(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 5012, .operands = operands.toOwnedSlice(), }); return result; } pub fn subgroupShuffleIntel(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 5571, .operands = operands.toOwnedSlice(), }); return result; } pub fn subgroupShuffleDownIntel(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 5572, .operands = operands.toOwnedSlice(), }); return result; } pub fn subgroupShuffleUpIntel(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef, arg2: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 5573, .operands = operands.toOwnedSlice(), }); return result; } pub fn subgroupShuffleXorIntel(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 5574, .operands = operands.toOwnedSlice(), }); return result; } pub fn subgroupBlockReadIntel(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try self.insns.append(self.allocator, .{ .op = 5575, .operands = operands.toOwnedSlice(), }); return result; } pub fn subgroupBlockWriteIntel(self: *spirv.Builder, arg0: IdRef, arg1: IdRef) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 5576, .operands = operands.toOwnedSlice(), }); } pub fn subgroupImageBlockReadIntel(self: *spirv.Builder, result_type: spirv.Id, arg0: IdRef, arg1: IdRef) !spirv.Id { const result = self.newId(); var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, spirv.Id, result_type); try spirv.Builder.writeOperand(&operands, spirv.Id, result); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try self.insns.append(self.allocator, .{ .op = 5577, .operands = operands.toOwnedSlice(), }); return result; } pub fn subgroupImageBlockWriteIntel(self: *spirv.Builder, arg0: IdRef, arg1: IdRef, arg2: IdRef) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, IdRef, arg1); try spirv.Builder.writeOperand(&operands, IdRef, arg2); try self.insns.append(self.allocator, .{ .op = 5578, .operands = operands.toOwnedSlice(), }); } pub fn decorateStringGoogle(self: *spirv.Builder, arg0: IdRef, arg1: Decoration) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, Decoration, arg1); try self.insns.append(self.allocator, .{ .op = 5632, .operands = operands.toOwnedSlice(), }); } pub fn memberDecorateStringGoogle(self: *spirv.Builder, arg0: IdRef, arg1: LiteralInteger, arg2: Decoration) !void { var operands = std.ArrayList(spirv.Operand).init(self.allocator); errdefer operands.deinit(); try spirv.Builder.writeOperand(&operands, IdRef, arg0); try spirv.Builder.writeOperand(&operands, LiteralInteger, arg1); try spirv.Builder.writeOperand(&operands, Decoration, arg2); try self.insns.append(self.allocator, .{ .op = 5633, .operands = operands.toOwnedSlice(), }); } }; pub const ImageOperands = packed struct { bias: ?IdRef = null, lod: ?IdRef = null, grad: ?std.meta.Tuple(IdRef, IdRef) = null, const_offset: ?IdRef = null, offset: ?IdRef = null, const_offsets: ?IdRef = null, sample: ?IdRef = null, min_lod: ?IdRef = null, pub fn bitmask(self: ImageOperands) u32 { var bits: u32 = 0; if (self.bias != null) bits |= 0x1; if (self.lod != null) bits |= 0x2; if (self.grad != null) bits |= 0x4; if (self.const_offset != null) bits |= 0x8; if (self.offset != null) bits |= 0x10; if (self.const_offsets != null) bits |= 0x20; if (self.sample != null) bits |= 0x40; if (self.min_lod != null) bits |= 0x80; return bits; } }; pub const FPFastMathMode = packed struct { not_nan: bool = false, not_inf: bool = false, nsz: bool = false, allow_recip: bool = false, fast: bool = false, pub fn bitmask(self: FPFastMathMode) u32 { var bits: u32 = 0; if (self.not_nan) bits |= 0x1; if (self.not_inf) bits |= 0x2; if (self.nsz) bits |= 0x4; if (self.allow_recip) bits |= 0x8; if (self.fast) bits |= 0x10; return bits; } }; pub const SelectionControl = packed struct { flatten: bool = false, dont_flatten: bool = false, pub fn bitmask(self: SelectionControl) u32 { var bits: u32 = 0; if (self.flatten) bits |= 0x1; if (self.dont_flatten) bits |= 0x2; return bits; } }; pub const LoopControl = packed struct { unroll: bool = false, dont_unroll: bool = false, pub fn bitmask(self: LoopControl) u32 { var bits: u32 = 0; if (self.unroll) bits |= 0x1; if (self.dont_unroll) bits |= 0x2; return bits; } }; pub const FunctionControl = packed struct { @"inline": bool = false, dont_inline: bool = false, pure: bool = false, @"const": bool = false, pub fn bitmask(self: FunctionControl) u32 { var bits: u32 = 0; if (self.@"inline") bits |= 0x1; if (self.dont_inline) bits |= 0x2; if (self.pure) bits |= 0x4; if (self.@"const") bits |= 0x8; return bits; } }; pub const MemorySemantics = packed struct { acquire: bool = false, release: bool = false, acquire_release: bool = false, sequentially_consistent: bool = false, uniform_memory: bool = false, subgroup_memory: bool = false, workgroup_memory: bool = false, cross_workgroup_memory: bool = false, atomic_counter_memory: bool = false, image_memory: bool = false, pub fn bitmask(self: MemorySemantics) u32 { var bits: u32 = 0; if (self.acquire) bits |= 0x2; if (self.release) bits |= 0x4; if (self.acquire_release) bits |= 0x8; if (self.sequentially_consistent) bits |= 0x10; if (self.uniform_memory) bits |= 0x40; if (self.subgroup_memory) bits |= 0x80; if (self.workgroup_memory) bits |= 0x100; if (self.cross_workgroup_memory) bits |= 0x200; if (self.atomic_counter_memory) bits |= 0x400; if (self.image_memory) bits |= 0x800; return bits; } }; pub const MemoryAccess = packed struct { @"volatile": bool = false, aligned: ?LiteralInteger = null, nontemporal: bool = false, pub fn bitmask(self: MemoryAccess) u32 { var bits: u32 = 0; if (self.@"volatile") bits |= 0x1; if (self.aligned != null) bits |= 0x2; if (self.nontemporal) bits |= 0x4; return bits; } }; pub const KernelProfilingInfo = packed struct { cmd_exec_time: bool = false, pub fn bitmask(self: KernelProfilingInfo) u32 { var bits: u32 = 0; if (self.cmd_exec_time) bits |= 0x1; return bits; } }; pub const SourceLanguage = enum(u16) { unknown = 0, essl = 1, glsl = 2, opencl_c = 3, opencl_cpp = 4, hlsl = 5, }; pub const ExecutionModel = enum(u16) { vertex = 0, tessellation_control = 1, tessellation_evaluation = 2, geometry = 3, fragment = 4, gl_compute = 5, kernel = 6, }; pub const AddressingModel = enum(u16) { logical = 0, physical32 = 1, physical64 = 2, }; pub const MemoryModel = enum(u16) { simple = 0, glsl450 = 1, opencl = 2, }; pub const ExecutionMode = union(ExecutionModeTag) { invocations: LiteralInteger, spacing_equal: void, spacing_fractional_even: void, spacing_fractional_odd: void, vertex_order_cw: void, vertex_order_ccw: void, pixel_center_integer: void, origin_upper_left: void, origin_lower_left: void, early_fragment_tests: void, point_mode: void, xfb: void, depth_replacing: void, depth_greater: void, depth_less: void, depth_unchanged: void, local_size: std.meta.Tuple(LiteralInteger, LiteralInteger, LiteralInteger), local_size_hint: std.meta.Tuple(LiteralInteger, LiteralInteger, LiteralInteger), input_points: void, input_lines: void, input_lines_adjacency: void, triangles: void, input_triangles_adjacency: void, quads: void, isolines: void, output_vertices: LiteralInteger, output_points: void, output_line_strip: void, output_triangle_strip: void, vec_type_hint: LiteralInteger, contraction_off: void, post_depth_coverage: void, stencil_ref_replacing_ext: void, }; pub const ExecutionModeTag = enum(u16) { invocations = 0, spacing_equal = 1, spacing_fractional_even = 2, spacing_fractional_odd = 3, vertex_order_cw = 4, vertex_order_ccw = 5, pixel_center_integer = 6, origin_upper_left = 7, origin_lower_left = 8, early_fragment_tests = 9, point_mode = 10, xfb = 11, depth_replacing = 12, depth_greater = 14, depth_less = 15, depth_unchanged = 16, local_size = 17, local_size_hint = 18, input_points = 19, input_lines = 20, input_lines_adjacency = 21, triangles = 22, input_triangles_adjacency = 23, quads = 24, isolines = 25, output_vertices = 26, output_points = 27, output_line_strip = 28, output_triangle_strip = 29, vec_type_hint = 30, contraction_off = 31, post_depth_coverage = 4446, stencil_ref_replacing_ext = 5027, }; pub const StorageClass = enum(u16) { uniform_constant = 0, input = 1, uniform = 2, output = 3, workgroup = 4, cross_workgroup = 5, private = 6, function = 7, generic = 8, push_constant = 9, atomic_counter = 10, image = 11, storage_buffer = 12, }; pub const Dim = enum(u16) { @"1d" = 0, @"2d" = 1, @"3d" = 2, cube = 3, rect = 4, buffer = 5, subpass_data = 6, }; pub const SamplerAddressingMode = enum(u16) { none = 0, clamp_to_edge = 1, clamp = 2, repeat = 3, repeat_mirrored = 4, }; pub const SamplerFilterMode = enum(u16) { nearest = 0, linear = 1, }; pub const ImageFormat = enum(u16) { unknown = 0, rgba32f = 1, rgba16f = 2, r32f = 3, rgba8 = 4, rgba8_snorm = 5, rg32f = 6, rg16f = 7, r11f_g11f_b10f = 8, r16f = 9, rgba16 = 10, rgb10_a2 = 11, rg16 = 12, rg8 = 13, r16 = 14, r8 = 15, rgba16_snorm = 16, rg16_snorm = 17, rg8_snorm = 18, r16_snorm = 19, r8_snorm = 20, rgba32i = 21, rgba16i = 22, rgba8i = 23, r32i = 24, rg32i = 25, rg16i = 26, rg8i = 27, r16i = 28, r8i = 29, rgba32ui = 30, rgba16ui = 31, rgba8ui = 32, r32ui = 33, rgb10a2ui = 34, rg32ui = 35, rg16ui = 36, rg8ui = 37, r16ui = 38, r8ui = 39, }; pub const ImageChannelOrder = enum(u16) { r = 0, a = 1, rg = 2, ra = 3, rgb = 4, rgba = 5, bgra = 6, argb = 7, intensity = 8, luminance = 9, rx = 10, rgx = 11, rgbx = 12, depth = 13, depth_stencil = 14, srgb = 15, srgbx = 16, srgba = 17, sbgra = 18, abgr = 19, }; pub const ImageChannelDataType = enum(u16) { snorm_int8 = 0, snorm_int16 = 1, unorm_int8 = 2, unorm_int16 = 3, unorm_short565 = 4, unorm_short555 = 5, unorm_int101010 = 6, signed_int8 = 7, signed_int16 = 8, signed_int32 = 9, unsigned_int8 = 10, unsigned_int16 = 11, unsigned_int32 = 12, half_float = 13, float = 14, unorm_int24 = 15, unorm_int101010_2 = 16, }; pub const FPRoundingMode = enum(u16) { rte = 0, rtz = 1, rtp = 2, rtn = 3, }; pub const LinkageType = enum(u16) { @"export" = 0, import = 1, }; pub const AccessQualifier = enum(u16) { read_only = 0, write_only = 1, read_write = 2, }; pub const FunctionParameterAttribute = enum(u16) { zext = 0, sext = 1, by_val = 2, sret = 3, no_alias = 4, no_capture = 5, no_write = 6, no_read_write = 7, }; pub const Decoration = union(DecorationTag) { relaxed_precision: void, spec_id: LiteralInteger, block: void, buffer_block: void, row_major: void, col_major: void, array_stride: LiteralInteger, matrix_stride: LiteralInteger, glsl_shared: void, glsl_packed: void, c_packed: void, built_in: BuiltIn, no_perspective: void, flat: void, patch: void, centroid: void, sample: void, invariant: void, restrict: void, aliased: void, @"volatile": void, constant: void, coherent: void, non_writable: void, non_readable: void, uniform: void, saturated_conversion: void, stream: LiteralInteger, location: LiteralInteger, component: LiteralInteger, index: LiteralInteger, binding: LiteralInteger, descriptor_set: LiteralInteger, offset: LiteralInteger, xfb_buffer: LiteralInteger, xfb_stride: LiteralInteger, func_param_attr: FunctionParameterAttribute, fp_rounding_mode: FPRoundingMode, fp_fast_math_mode: FPFastMathMode, linkage_attributes: std.meta.Tuple(LiteralString, LinkageType), no_contraction: void, input_attachment_index: LiteralInteger, alignment: LiteralInteger, explicit_interp_amd: void, override_coverage_nv: void, passthrough_nv: void, viewport_relative_nv: void, secondary_viewport_relative_nv: LiteralInteger, hlsl_counter_buffer_google: IdRef, hlsl_semantic_google: LiteralString, }; pub const DecorationTag = enum(u16) { relaxed_precision = 0, spec_id = 1, block = 2, buffer_block = 3, row_major = 4, col_major = 5, array_stride = 6, matrix_stride = 7, glsl_shared = 8, glsl_packed = 9, c_packed = 10, built_in = 11, no_perspective = 13, flat = 14, patch = 15, centroid = 16, sample = 17, invariant = 18, restrict = 19, aliased = 20, @"volatile" = 21, constant = 22, coherent = 23, non_writable = 24, non_readable = 25, uniform = 26, saturated_conversion = 28, stream = 29, location = 30, component = 31, index = 32, binding = 33, descriptor_set = 34, offset = 35, xfb_buffer = 36, xfb_stride = 37, func_param_attr = 38, fp_rounding_mode = 39, fp_fast_math_mode = 40, linkage_attributes = 41, no_contraction = 42, input_attachment_index = 43, alignment = 44, explicit_interp_amd = 4999, override_coverage_nv = 5248, passthrough_nv = 5250, viewport_relative_nv = 5252, secondary_viewport_relative_nv = 5256, hlsl_counter_buffer_google = 5634, hlsl_semantic_google = 5635, }; pub const BuiltIn = enum(u16) { position = 0, point_size = 1, clip_distance = 3, cull_distance = 4, vertex_id = 5, instance_id = 6, primitive_id = 7, invocation_id = 8, layer = 9, viewport_index = 10, tess_level_outer = 11, tess_level_inner = 12, tess_coord = 13, patch_vertices = 14, frag_coord = 15, point_coord = 16, front_facing = 17, sample_id = 18, sample_position = 19, sample_mask = 20, frag_depth = 22, helper_invocation = 23, num_workgroups = 24, workgroup_size = 25, workgroup_id = 26, local_invocation_id = 27, global_invocation_id = 28, local_invocation_index = 29, work_dim = 30, global_size = 31, enqueued_workgroup_size = 32, global_offset = 33, global_linear_id = 34, subgroup_size = 36, subgroup_max_size = 37, num_subgroups = 38, num_enqueued_subgroups = 39, subgroup_id = 40, subgroup_local_invocation_id = 41, vertex_index = 42, instance_index = 43, subgroup_eq_mask_khr = 4416, subgroup_ge_mask_khr = 4417, subgroup_gt_mask_khr = 4418, subgroup_le_mask_khr = 4419, subgroup_lt_mask_khr = 4420, base_vertex = 4424, base_instance = 4425, draw_index = 4426, device_index = 4438, view_index = 4440, bary_coord_no_persp_amd = 4992, bary_coord_no_persp_centroid_amd = 4993, bary_coord_no_persp_sample_amd = 4994, bary_coord_smooth_amd = 4995, bary_coord_smooth_centroid_amd = 4996, bary_coord_smooth_sample_amd = 4997, bary_coord_pull_model_amd = 4998, frag_stencil_ref_ext = 5014, viewport_mask_nv = 5253, secondary_position_nv = 5257, secondary_viewport_mask_nv = 5258, position_per_view_nv = 5261, viewport_mask_per_view_nv = 5262, }; pub const Scope = enum(u16) { cross_device = 0, device = 1, workgroup = 2, subgroup = 3, invocation = 4, }; pub const GroupOperation = enum(u16) { reduce = 0, inclusive_scan = 1, exclusive_scan = 2, }; pub const KernelEnqueueFlags = enum(u16) { no_wait = 0, wait_kernel = 1, wait_work_group = 2, }; pub const Capability = enum(u16) { matrix = 0, shader = 1, geometry = 2, tessellation = 3, addresses = 4, linkage = 5, kernel = 6, vector16 = 7, float16_buffer = 8, float16 = 9, float64 = 10, int64 = 11, int64_atomics = 12, image_basic = 13, image_read_write = 14, image_mipmap = 15, pipes = 17, groups = 18, device_enqueue = 19, literal_sampler = 20, atomic_storage = 21, int16 = 22, tessellation_point_size = 23, geometry_point_size = 24, image_gather_extended = 25, storage_image_multisample = 27, uniform_buffer_array_dynamic_indexing = 28, sampled_image_array_dynamic_indexing = 29, storage_buffer_array_dynamic_indexing = 30, storage_image_array_dynamic_indexing = 31, clip_distance = 32, cull_distance = 33, image_cube_array = 34, sample_rate_shading = 35, image_rect = 36, sampled_rect = 37, generic_pointer = 38, int8 = 39, input_attachment = 40, sparse_residency = 41, min_lod = 42, sampled1d = 43, image1d = 44, sampled_cube_array = 45, sampled_buffer = 46, image_buffer = 47, image_ms_array = 48, storage_image_extended_formats = 49, image_query = 50, derivative_control = 51, interpolation_function = 52, transform_feedback = 53, geometry_streams = 54, storage_image_read_without_format = 55, storage_image_write_without_format = 56, multi_viewport = 57, subgroup_ballot_khr = 4423, draw_parameters = 4427, subgroup_vote_khr = 4431, storage_buffer16_bit_access = 4433, uniform_and_storage_buffer16_bit_access = 4434, storage_push_constant16 = 4435, storage_input_output16 = 4436, device_group = 4437, multi_view = 4439, variable_pointers_storage_buffer = 4441, variable_pointers = 4442, atomic_storage_ops = 4445, sample_mask_post_depth_coverage = 4447, image_gather_bias_lod_amd = 5009, fragment_mask_amd = 5010, stencil_export_ext = 5013, image_read_write_lod_amd = 5015, sample_mask_override_coverage_nv = 5249, geometry_shader_passthrough_nv = 5251, shader_viewport_index_layer_ext = 5254, shader_viewport_mask_nv = 5255, shader_stereo_view_nv = 5259, per_view_attributes_nv = 5260, subgroup_shuffle_intel = 5568, subgroup_buffer_block_io_intel = 5569, subgroup_image_block_io_intel = 5570, }; /// Reference to an <id> representing the result's type of the enclosing instruction pub const IdResultType = spirv.Id; /// Definition of an <id> representing the result of the enclosing instruction pub const IdResult = spirv.Id; /// Reference to an <id> representing a 32-bit integer that is a mask from the MemorySemantics operand kind pub const IdMemorySemantics = spirv.Id; /// Reference to an <id> representing a 32-bit integer that is a mask from the Scope operand kind pub const IdScope = spirv.Id; /// Reference to an <id> pub const IdRef = spirv.Id; /// An integer consuming one or more words pub const LiteralInteger = u64; /// A null-terminated stream of characters consuming an integral number of words pub const LiteralString = []const u8; /// A literal number whose size and format are determined by a previous operand in the enclosing instruction pub const LiteralContextDependentNumber = @compileError("TODO"); /// A 32-bit unsigned integer indicating which instruction to use and determining the layout of following operands (for OpExtInst) pub const LiteralExtInstInteger = @compileError("TODO"); /// An opcode indicating the operation to be performed and determining the layout of following operands (for OpSpecConstantOp) pub const LiteralSpecConstantOpInteger = @compileError("TODO"); pub const PairLiteralIntegerIdRef = std.meta.Tuple(&.{ LiteralInteger, IdRef }); pub const PairIdRefLiteralInteger = std.meta.Tuple(&.{ IdRef, LiteralInteger }); pub const PairIdRefIdRef = std.meta.Tuple(&.{ IdRef, IdRef });
src/gen/core.zig
const LeafIterator = struct { child_it: Node.ChildIterator, prev_child_its: std.ArrayList(Node.ChildIterator), // pub fn next_(self: *LeafIterator) ?Leaf { // while (self.child_it.next()) |child| { // std.debug.print("LeafIterator.next child {}\n", .{child}); // switch (child.*) { // .leaf => return child.leaf, // .empty => return null, // else => { // // const child_it = self.child_it; // // defer self.child_it = child_it; // self.child_it = child.childIterator(); // return self.next(); // }, // } // } // return null; // } // fn recursiveIter(t: *Tree, n: *Node, data: anytype, depth: usize, cb: anytype) bool { pub fn next(self: *LeafIterator) Error!?Leaf { // const child = self.child_it.next() orelse if (self.prev_child_its.items.len > 0) // // self.prev_child_it.next() // blk2: { // self.child_it = self.prev_child_its.pop(); // break :blk2 self.child_it.next() orelse return null; // } else // return null; const child = self.child_it.next() orelse return null; // const child_it = self.child_it; // defer self.child_it = child_it; std.debug.print("LeafIterator.next child {} prev_child_its len {}\n", .{ child, self.prev_child_its.items.len }); // std.debug.print("LeafIterator.next child {}\nchild_it {}\n", .{ child, self.child_it }); switch (child.*) { .empty => {}, .leaf => { // defer self.child_it = child_it; return child.leaf; }, .node4, .node16, .node48, .node256 => { // var cli = LeafIterator {.child_it = child.childIterator()}; // // while (ci.next()) |child2| { // // if (t.recursiveIter(child, data, depth + 1, cb)) // // return true; // // } // return cli.next(); // defer self.child_it = child_it; _ = try self.prev_child_its.append(self.child_it); self.child_it = child.childIterator(); return try self.next(); // var li = LeafIterator{ .child_it = child.childIterator() }; // return li.next(); }, } if (self.prev_child_its.items.len > 0) { self.child_it = self.prev_child_its.pop(); return try self.next(); } return null; } }; pub fn iterator(t: *Tree) LeafIterator { return .{ .child_it = t.root.childIterator(), .prev_child_its = std.ArrayList(Node.ChildIterator).init(t.allocator) }; }
src/iterator_ideas.zig
const std = @import("std"); const platform = @import("brucelib.platform"); const graphics = @import("brucelib.graphics").usingBackendAPI(.default); const audio_on = false; pub fn main() anyerror!void { try platform.run(.{ .title = "000_funky_triangle", .window_size = .{ .width = 854, .height = 480, }, .init_fn = init, .deinit_fn = deinit, .frame_fn = frame, .audio_playback = if (audio_on) .{ .callback = audioPlayback, } else null, }); } var state: struct { triangle_hue: f32 = 0, audio_cursor: u64 = 0, tone_hz: f32 = 440, volume: f32 = 0.67, debug_gui: graphics.DebugGUI.State = .{}, } = .{}; /// Called before the platform event loop begins fn init(allocator: std.mem.Allocator) !void { try graphics.init(allocator, platform); } /// Called before the program terminates, after the `frame_fn` returns false fn deinit(_: std.mem.Allocator) void { graphics.deinit(); } /// Called every time the platform module wants a new frame to display to meet the target /// framerate. The target framerate is determined by the platform layer using the display /// refresh rate, frame metrics and the optional user set arg of `platform.run`: /// `.requested_framerate`. `FrameInput` is passed as an argument, containing events and /// other data used to produce the next frame. fn frame(input: platform.FrameInput) !bool { if (input.quit_requested) { return false; } var draw_list = try graphics.beginDrawing(input.frame_arena_allocator); try graphics.setViewport(&draw_list, .{ .x = 0, .y = 0, .width = input.window_size.width, .height = input.window_size.height, }); try graphics.clearViewport(&draw_list, graphics.Colour.black); { // update and draw funky triangle state.triangle_hue = @mod( state.triangle_hue + @intToFloat(f32, input.target_frame_dt) / 1e9, 1.0, ); try graphics.setProjectionTransform(&draw_list, graphics.identityMatrix()); try graphics.drawUniformColourVerts( &draw_list, graphics.builtin_pipeline_resources.uniform_colour_verts, graphics.Colour.fromHSV(state.triangle_hue, 0.5, 1.0), &[_]graphics.Vertex{ .{ .pos = .{ -0.5, -0.5, 0.0 } }, .{ .pos = .{ 0.5, -0.5, 0.0 } }, .{ .pos = .{ 0.0, 0.5, 0.0 } }, }, ); } { // update and draw debug overlay state.debug_gui.input.mapPlatformInput(input.user_input); var debug_gui = try graphics.DebugGUI.begin( input.frame_arena_allocator, &draw_list, @intToFloat(f32, input.window_size.width), @intToFloat(f32, input.window_size.height), &state.debug_gui, ); try debug_gui.label( "{d:.2} ms update", .{@intToFloat(f32, input.debug_stats.prev_cpu_frame_elapsed) / 1e6}, ); const prev_frame_time_ms = @intToFloat(f32, input.prev_frame_elapsed) / 1e6; try debug_gui.label( "{d:.2} ms frame, {d:.0} FPS", .{ prev_frame_time_ms, 1e3 / prev_frame_time_ms }, ); try debug_gui.textField(f32, "{d:.2} Hz", &state.tone_hz); // try debug_gui.slider(u32, 20, 20_000, &state.tone_hz, 200); try debug_gui.label( "Mouse pos = ({}, {})", .{ input.user_input.mouse_position.x, input.user_input.mouse_position.y }, ); try debug_gui.end(); } try graphics.submitDrawList(&draw_list); return true; } /// Optional audio playback callback. If set it can be called at any time by the platform module /// on a dedicated audio thread. fn audioPlayback(stream: platform.AudioPlaybackStream) !u32 { const sin = std.math.sinh; const pi = std.math.pi; const tao = 2 * pi; const sample_rate = @intToFloat(f32, stream.sample_rate); const num_frames = stream.max_frames; var n: u32 = 0; while (n < num_frames) : (n += 1) { var sample = 0.5 * sin( @intToFloat(f32, state.audio_cursor + n) * (tao * state.tone_hz) / sample_rate, ); sample *= state.volume; var channel: u32 = 0; while (channel < stream.channels) : (channel += 1) { stream.sample_buf[n * stream.channels + channel] = @floatCast(f32, sample); } } const frames_written = num_frames; state.audio_cursor += frames_written; return frames_written; }
examples/000_funky_triangle/main.zig
const std = @import("std"); const u = @import("../util.zig"); const Expr = @import("../Expr.zig"); fn UN(comptime N: u16) type { return std.meta.Int(.unsigned, N); } fn SN(comptime N: u16) type { return std.meta.Int(.signed, N); } fn IN(comptime N: u16) type { return SN(N + 1); } inline fn digit(c: u8, hexnum: bool) !u8 { return switch (c) { '0'...'9' => c - '0', 'A'...'F' => if (hexnum) c - 'A' + 10 else null, 'a'...'f' => if (hexnum) c - 'a' + 10 else null, else => null, } orelse error.NotDigit; } fn num(comptime V: type, str: u.Txt, hexnum: bool) !V { if (str.len == 0) return error.Empty; var v: V = try digit(str[0], hexnum); var i: usize = 1; while (i < str.len) : (i += 1) { if (str[i] == '_') { i += 1; if (str.len <= i) return error.Empty; } const d = try digit(str[i], hexnum); v = try std.math.mul(V, v, @as(u8, if (hexnum) 16 else 10)); v = try std.math.add(V, v, d); } return v; } fn iN(str: u.Txt, comptime N: u16) !IN(N) { var i: usize = 0; if (str.len == 0) return error.Empty; const sign = str[i] == '-'; if (sign or str[i] == '+') i += 1; const hexnum = std.mem.startsWith(u8, str[i..], "0x"); if (hexnum) i += 2; var v = try num(IN(N), str[i..], hexnum); if (sign) v = try std.math.negate(v); return v; } fn uN(str: u.Txt, comptime N: u16) !UN(N) { const i = try iN(str, N); if (i < 0) return error.Signed; return std.math.lossyCast(UN(N), i); } fn sN(str: u.Txt, comptime N: u16) !SN(N) { return iN(str, N - 1); } pub fn fNs(str: u.Txt) !f64 { var i: usize = 0; if (str.len == 0) return error.Empty; const sign = str[i] == '-'; if (sign or str[i] == '+') i += 1; var v = if (u.strEql("inf", str[i..])) std.math.inf_f64 else if (std.mem.startsWith(u8, str[i..], "nan")) blk: { // MAYBE: support nan:0x hexnum if (str[i..].len > 3) return error.TooMany; break :blk std.math.nan_f64; } else blk: { // NOTE: not correct on i64 overflow const hexnum = std.mem.startsWith(u8, str[i..], "0x"); if (hexnum) i += 2; const dot = std.mem.indexOfScalar(u8, str[i..], '.'); var p = @intToFloat(f64, try num(i64, if (dot) |j| str[i .. i + j] else str[i..], hexnum)); if (dot == null or i + dot.? + 1 >= str.len) break :blk p; i += dot.? + 1; const pow = std.mem.indexOfScalar(u8, str[i..], 'p') orelse std.mem.indexOfScalar(u8, str[i..], 'P'); if (pow == null or str.len > pow.? + 1) { const q = @intToFloat(f64, try num(i64, if (pow) |j| str[i .. i + j] else str[i..], hexnum)); p *= (1.0 / q); } if (pow != null) { //exp i += pow.? + 1; if (str.len >= i) return error.Empty; const exp_sign = str[i] == '-'; if (exp_sign or str[i] == '+') i += 1; var e = @intToFloat(f64, try num(i64, str[i..], false)); if (exp_sign) e *= -1; p *= std.math.pow(f64, 2, e); } break :blk p; }; if (sign) v *= -1; return v; } pub fn keyword(arg: Expr) !u.Txt { return arg.val.asKeyword() orelse return error.NotKeyword; } pub fn u32s(str: u.Txt) !u32 { return uN(str, 32); } pub fn i32s(str: u.Txt) !i32 { return sN(str, 32); } pub fn i64s(str: u.Txt) !i64 { return sN(str, 64); } pub inline fn u32_(arg: Expr) !u32 { return u32s(try keyword(arg)); } pub const Func = struct { name: u.Txt, id: ?u.Txt = null, args: []Expr = &[_]Expr{}, }; pub fn asFunc(arg: Expr) ?Func { switch (arg.val) { .list => |exprs| { if (exprs.len > 0) { if (exprs[0].val.asKeyword()) |name| { const id = if (exprs.len > 1) exprs[1].val.asId() else null; const offset = @as(usize, 1) + @boolToInt(id != null); return Func{ .name = name, .id = id, .args = exprs[offset..] }; } } }, else => {}, } return null; } pub fn asFuncNamed(arg: Expr, comptime name: u.Txt) ?Func { const func = asFunc(arg) orelse return null; return if (u.strEql(name, func.name)) func else null; } pub fn nTypeuse(args: []const Expr) usize { var i: usize = 0; if (args.len > 0 and asFuncNamed(args[0], "type") != null) i += 1; while (i < args.len) : (i += 1) { if (asFuncNamed(args[i], "param") == null) break; } while (i < args.len) : (i += 1) { if (asFuncNamed(args[i], "result") == null) break; } return i; } pub fn enumKv(comptime T: type) fn (arg: Expr) ?T { return struct { fn do(arg: Expr) ?T { const key = arg.val.asKeyword() orelse return null; return std.meta.stringToEnum(T, key); } }.do; } pub const numtype = enumKv(std.wasm.Valtype);
src/Wat/parse.zig
const std = @import("std"); const backend = @import("backend.zig"); const Size = @import("data.zig").Size; const DataWrapper = @import("data.zig").DataWrapper; pub const DrawContext = backend.Canvas.DrawContext; pub const Canvas_Impl = struct { pub usingnamespace @import("internal.zig").All(Canvas_Impl); peer: ?backend.Canvas = null, handlers: Canvas_Impl.Handlers = undefined, dataWrappers: Canvas_Impl.DataWrappers = .{}, preferredSize: ?Size = null, pub const DrawContext = backend.Canvas.DrawContext; pub fn init() Canvas_Impl { return Canvas_Impl.init_events(Canvas_Impl{}); } pub fn getPreferredSize(self: *Canvas_Impl, available: Size) Size { _ = self; _ = available; // As it's a canvas, by default it should take the available space return self.preferredSize orelse available; } pub fn setPreferredSize(self: *Canvas_Impl, preferred: Size) Canvas_Impl { self.preferredSize = preferred; return self.*; } pub fn show(self: *Canvas_Impl) !void { if (self.peer == null) { self.peer = try backend.Canvas.create(); try self.show_events(); } } }; pub fn Canvas(config: struct { onclick: ?Canvas_Impl.Callback = null }) Canvas_Impl { var btn = Canvas_Impl.init(); if (config.onclick) |onclick| { btn.addClickHandler(onclick) catch unreachable; // TODO: improve } return btn; } const Color = @import("color.zig").Color; pub const Rect_Impl = struct { pub usingnamespace @import("internal.zig").All(Rect_Impl); peer: ?backend.Canvas = null, handlers: Rect_Impl.Handlers = undefined, dataWrappers: Rect_Impl.DataWrappers = .{}, preferredSize: ?Size = null, color: DataWrapper(Color) = DataWrapper(Color).of(Color.black), pub fn init() Rect_Impl { return Rect_Impl.init_events(Rect_Impl{}); } pub fn getPreferredSize(self: *Rect_Impl, available: Size) Size { return self.preferredSize orelse available.intersect(Size.init(0, 0)); } pub fn setPreferredSize(self: *Rect_Impl, preferred: Size) Rect_Impl { self.preferredSize = preferred; return self.*; } pub fn draw(self: *Rect_Impl, ctx: *Canvas_Impl.DrawContext) !void { ctx.setColorByte(self.color.get()); ctx.rectangle(0, 0, self.getWidth(), self.getHeight()); ctx.fill(); } pub fn show(self: *Rect_Impl) !void { if (self.peer == null) { self.peer = try backend.Canvas.create(); _ = try self.color.addChangeListener(.{ .function = struct { fn callback(_: Color, userdata: usize) void { const peer = @intToPtr(*?backend.Canvas, userdata); peer.*.?.requestDraw() catch {}; } }.callback, .userdata = @ptrToInt(&self.peer) }); try self.show_events(); } } }; pub fn Rect(config: struct { size: ?Size = null, color: Color = Color.black }) Rect_Impl { var rect = Rect_Impl.init(); _ = rect.addDrawHandler(Rect_Impl.draw) catch unreachable; rect.preferredSize = config.size; rect.color = DataWrapper(Color).of(config.color); return rect; } const fuzz = @import("fuzz.zig"); test "instantiate Canvas" { var canvas = Canvas(.{}); defer canvas.deinit(); _ = canvas; } test "instantiate Rect" { var rect = Rect(.{ .color = Color.blue }); defer rect.deinit(); try std.testing.expectEqual(Color.blue, rect.color.get()); var rect2 = Rect(.{ .color = Color.yellow }); defer rect2.deinit(); try std.testing.expectEqual(Color.yellow, rect2.color.get()); }
src/canvas.zig
const std = @import("std"); const znt = @import("znt"); const gl = @import("zgl"); pub fn ui(comptime Scene: type) type { return struct { const box_component = Scene.componentByType(Box); const rect_component = Scene.componentByType(Rect); /// The Box component specifies a tree of nested boxes that can be laid out by the LayoutSystem pub const Box = struct { parent: ?znt.EntityId, // Parent of this box sibling: ?znt.EntityId, // Previous sibling settings: Settings, // Box layout settings shape: RectShape = undefined, // Shape of the box, set by layout // Internal _visited: bool = false, // Has this box been processed yet? // Total growth of all children, or size of one growth unit, depending on what stage of layout we're at _grow_total_or_unit: f32 = undefined, _offset: f32 = undefined, // Current offset into the box pub const Relation = enum { parent, sibling, }; pub const Settings = struct { direction: Direction = .row, grow: f32 = 1, fill_cross: bool = true, margins: Margins = .{}, min_size: [2]usize = .{ 0, 0 }, // TODO: minimum size function }; pub const Direction = enum { row, col }; pub const Margins = struct { l: usize = 0, b: usize = 0, r: usize = 0, t: usize = 0, }; pub fn init(parent: ?znt.EntityId, sibling: ?znt.EntityId, settings: Settings) Box { return .{ .parent = parent, .sibling = sibling, .settings = settings }; } }; /// The Rect component displays a colored rectangle at a size and location specified by a callback pub const Rect = struct { color: [4]f32, shapeFn: fn (*Scene, znt.EntityId) RectShape, pub fn init(color: [4]f32, shapeFn: fn (*Scene, znt.EntityId) RectShape) Rect { return .{ .color = color, .shapeFn = shapeFn }; } }; pub const RectShape = struct { x: f32, y: f32, w: f32, h: f32, inline fn coord(self: *RectShape, axis: u1) *f32 { return switch (axis) { 0 => &self.x, 1 => &self.y, }; } inline fn dim(self: *RectShape, axis: u1) *f32 { return switch (axis) { 0 => &self.w, 1 => &self.h, }; } }; const Renderer = struct { vao: gl.VertexArray, prog: gl.Program, u_color: ?u32, buf: gl.Buffer, origin: RenderSystem.Origin, pub fn init(origin: RenderSystem.Origin) Renderer { const vao = gl.VertexArray.create(); vao.enableVertexAttribute(0); vao.attribFormat(0, 2, .float, false, 0); vao.attribBinding(0, 0); const buf = gl.Buffer.create(); buf.storage([2]f32, 4, null, .{ .map_write = true }); vao.vertexBuffer(0, buf, 0, @sizeOf([2]f32)); const prog = createProgram(); const u_color = prog.uniformLocation("u_color"); return .{ .vao = vao, .prog = prog, .u_color = u_color, .buf = buf, .origin = origin, }; } pub fn deinit(self: Renderer) void { self.vao.delete(); self.prog.delete(); self.buf.delete(); } fn createProgram() gl.Program { const vert = gl.Shader.create(.vertex); defer vert.delete(); vert.source(1, &.{ \\ #version 330 \\ layout(location = 0) in vec2 pos; \\ void main() { \\ gl_Position = vec4(pos, 0, 1); \\ } }); vert.compile(); if (vert.get(.compile_status) == 0) { std.debug.panic("Vertex shader compilation failed:\n{s}\n", .{vert.getCompileLog(std.heap.page_allocator)}); } const frag = gl.Shader.create(.fragment); defer frag.delete(); frag.source(1, &.{ \\ #version 330 \\ uniform vec4 u_color; \\ out vec4 f_color; \\ void main() { \\ f_color = u_color; \\ } }); frag.compile(); if (frag.get(.compile_status) == 0) { std.debug.panic("Fragment shader compilation failed:\n{s}\n", .{frag.getCompileLog(std.heap.page_allocator)}); } const prog = gl.Program.create(); prog.attach(vert); defer prog.detach(vert); prog.attach(frag); defer prog.detach(frag); prog.link(); if (prog.get(.link_status) == 0) { std.debug.panic("Shader linking failed:\n{s}\n", .{frag.getCompileLog(std.heap.page_allocator)}); } return prog; } // TODO: use multidraw // TODO: use persistent mappings pub fn drawRect(self: *Renderer, rect: RectShape, color: [4]f32) void { self.prog.uniform4f(self.u_color, color[0], color[1], color[2], color[3]); while (true) { const buf = self.buf.mapRange([2]gl.Float, 0, 4, .{ .write = true }); buf[0] = self.coord(.{ rect.x, rect.y }); buf[1] = self.coord(.{ rect.x, rect.y + rect.h }); buf[2] = self.coord(.{ rect.x + rect.w, rect.y }); buf[3] = self.coord(.{ rect.x + rect.w, rect.y + rect.h }); if (self.buf.unmap()) break; } self.vao.bind(); self.prog.use(); gl.drawArrays(.triangle_strip, 0, 4); } /// Origin-adjust a coordinate fn coord(self: Renderer, input_coord: [2]gl.Float) [2]gl.Float { var c = input_coord; switch (self.origin) { .bottom_left => {}, // Nothing to do .bottom_right => c[0] = -c[0], // Flip X .top_left => c[1] = -c[1], // Flip Y .top_right => { // Flip X and Y c[0] = -c[0]; c[1] = -c[1]; }, } return c; } }; /// boxRect is a Rect callback that takes the size and location from a Box component pub fn boxRect(scene: *Scene, eid: znt.EntityId) RectShape { const box = scene.getOne(box_component, eid).?; return box.shape; } /// The LayoutSystem arranges a tree of nested boxes according to their constraints pub const LayoutSystem = struct { const BoxEntity = struct { id: znt.EntityId, box: *Box, }; s: *Scene, boxes: std.ArrayList(BoxEntity), view_scale: [2]f32, // Viewport scale // Viewport width and height should be in screen units, not pixels pub fn init(allocator: *std.mem.Allocator, scene: *Scene, viewport_size: [2]u31) LayoutSystem { var self = LayoutSystem{ .s = scene, .boxes = std.ArrayList(BoxEntity).init(allocator), .view_scale = undefined, }; self.setViewport(viewport_size); return self; } pub fn deinit(self: LayoutSystem) void { self.boxes.deinit(); } pub fn setViewport(self: *LayoutSystem, size: [2]u31) void { self.view_scale = .{ 2.0 / @intToFloat(f32, size[0]), 2.0 / @intToFloat(f32, size[1]), }; } pub fn layout(self: *LayoutSystem) std.mem.Allocator.Error!void { // Collect all boxes, parents before children // We also reset every box to a zero shape during this process try self.resetAndCollectBoxes(); // Compute minimum sizes // Iterate backwards so we compute child sizes before fitting parents around them var i = self.boxes.items.len; while (i > 0) { i -= 1; const ent = self.boxes.items[i]; self.layoutMin(ent.box); } // Compute layout // Iterate forwards so we compute parent capacities before fitting children to them for (self.boxes.items) |ent| { self.layoutFull(ent.box); ent.box._visited = false; // Reset the visited flag while we're here } } /// Collect the scene's boxes into the box list, with parents before children, and siblings in order /// Also resets boxes in preparation for layout fn resetAndCollectBoxes(self: *LayoutSystem) !void { self.boxes.clearRetainingCapacity(); try self.boxes.ensureTotalCapacity(self.s.count(box_component)); var have_root = false; var iter = self.s.iter(&.{box_component}); var entity = iter.next() orelse return; while (true) { var box = @field(entity, @tagName(box_component)); // Reset and append the box, followed by all siblings and parents const start = self.boxes.items.len; while (!box._visited) { box._visited = true; // Tag as visited // Reset box box.shape = .{ .x = 0, .y = 0, .w = 0, .h = 0 }; box._grow_total_or_unit = 0; box._offset = 0; self.boxes.appendAssumeCapacity(.{ .id = entity.id, .box = entity.box, }); if (box.sibling) |id| { const sibling = self.s.getOne(box_component, id).?; // TODO: cycle detection std.debug.assert(sibling.parent.? == box.parent.?); box = sibling; } else if (box.parent) |id| { // TODO: detect more than one first child box = self.s.getOne(box_component, id).?; } else { std.debug.assert(!have_root); // There can only be one root box have_root = true; break; } } // Then reverse the appended data to put the parents first std.mem.reverse(BoxEntity, self.boxes.items[start..]); entity = iter.next() orelse break; } std.debug.assert(have_root); // There must be one root box if there are any boxes std.debug.assert(self.boxes.items[0].box.parent == null); // All boxes must be descendants of the root box } /// Layout a box at its minimum size, in preparation for full layout. /// All children must have been laid out by this function beforehand. fn layoutMin(self: LayoutSystem, box: *Box) void { // Compute minimum size const minw = self.view_scale[0] * @intToFloat(f32, box.settings.min_size[0]); const minh = self.view_scale[1] * @intToFloat(f32, box.settings.min_size[1]); box.shape.w = std.math.max(box.shape.w, minw); box.shape.h = std.math.max(box.shape.h, minh); if (box.parent) |parent_id| { const parent = self.s.getOne(box_component, parent_id).?; // Add to parent minsize const outer_size = self.pad(.out, box.shape, box.settings.margins); switch (parent.settings.direction) { .row => { parent.shape.w += outer_size.w; parent.shape.h = std.math.max(parent.shape.h, outer_size.h); }, .col => { parent.shape.w = std.math.max(parent.shape.w, outer_size.w); parent.shape.h += outer_size.h; }, } // Compute grow total (for second pass) parent._grow_total_or_unit += box.settings.grow; } } /// Layout a box at its full size. /// All parents and prior siblings must have been laid out by this function beforehand. fn layoutFull(self: LayoutSystem, box: *Box) void { // Default shape is OpenGL full screen plane, padded inwards by margin var shape = self.pad(.in, .{ .x = -1, .y = -1, .w = 2, .h = 2 }, box.settings.margins); if (box.parent) |parent_id| { const parent = self.s.getOne(box_component, parent_id).?; const main_axis = @enumToInt(parent.settings.direction); const cross_axis = 1 - main_axis; const main_growth = box.settings.grow * parent._grow_total_or_unit; const main_size = box.shape.dim(main_axis).* + main_growth; shape = self.pad(.in, parent.shape, box.settings.margins); // Compute initial shape shape.dim(main_axis).* = std.math.max(0, main_size); // Replace main axis size shape.coord(main_axis).* += parent._offset; // Adjust main axis position if (!box.settings.fill_cross) { // If we're not filling cross axis, replace with min cross size shape.dim(cross_axis).* = box.shape.dim(cross_axis).*; } // Advance parent offset parent._offset += self.pad(.out, shape, box.settings.margins).dim(main_axis).*; } // Clamp to min size shape.w = std.math.max(shape.w, box.shape.w); shape.h = std.math.max(shape.h, box.shape.h); const child_main_axis = @enumToInt(box.settings.direction); const extra_space = shape.dim(child_main_axis).* - box.shape.dim(child_main_axis).*; if (box._grow_total_or_unit != 0) { box._grow_total_or_unit = std.math.max(0, extra_space) / box._grow_total_or_unit; } box.shape = shape; } const PaddingSide = enum { in, out }; fn pad(self: LayoutSystem, comptime side: PaddingSide, rect: RectShape, margins: Box.Margins) RectShape { const mx = self.view_scale[0] * @intToFloat(f32, margins.l); const my = self.view_scale[1] * @intToFloat(f32, margins.b); const mw = self.view_scale[0] * @intToFloat(f32, margins.l + margins.r); const mh = self.view_scale[1] * @intToFloat(f32, margins.b + margins.t); return switch (side) { .in => .{ .x = rect.x + mx, .y = rect.y + my, .w = std.math.max(0, rect.w - mw), .h = std.math.max(0, rect.h - mh), }, .out => .{ .x = rect.x - mx, .y = rect.y - my, .w = rect.w + mw, .h = rect.h + mh, }, }; } pub fn resolveCoordinate(self: *LayoutSystem, x: u31, y: u31) ?znt.EntityId { const fx = self.view_scale[0] * @intToFloat(f32, x) - 1; const fy = self.view_scale[1] * @intToFloat(f32, y) - 1; var i = self.boxes.items.len; while (i > 0) { i -= 1; var ent = self.boxes.items[i]; if (fx < ent.box.shape.x) continue; if (fy < ent.box.shape.y) continue; if (fx > ent.box.shape.x + ent.box.shape.w) continue; if (fy > ent.box.shape.y + ent.box.shape.h) continue; return ent.id; } return null; } }; /// The RenderSystem draws Rects to an OpenGL context pub const RenderSystem = struct { s: *Scene, renderer: Renderer, pub const Origin = enum { top_left, top_right, bottom_left, bottom_right, }; pub fn init(scene: *Scene, origin: Origin) RenderSystem { return .{ .s = scene, .renderer = Renderer.init(origin) }; } pub fn deinit(self: RenderSystem) void { self.renderer.deinit(); } pub fn render(self: *RenderSystem) void { var iter = self.s.iter(&.{rect_component}); while (iter.next()) |entity| { const rect = @field(entity, @tagName(rect_component)); var shape = rect.shapeFn(self.s, entity.id); self.renderer.drawRect(shape, rect.color); } } }; }; }
znt-ui.zig
const std = @import("std"); const clap = @import("clap"); const zfetch = @import("zfetch"); usingnamespace @import("commands.zig"); //pub const io_mode = .evented; pub const zfetch_use_buffered_io = false; const Command = enum { init, add, package, fetch, update, build, }; fn printUsage() noreturn { const stderr = std.io.getStdErr().writer(); _ = stderr.write( \\gyro <cmd> [cmd specific options] \\ \\cmds: \\ init Initialize a gyro.zzz with a link to a github repo \\ add Add dependencies to the project \\ build Build your project with build dependencies \\ fetch Download any undownloaded dependencies \\ package Bundle package(s) into a ziglet \\ update Delete lock file and fetch new package versions \\ \\for more information: gyro <cmd> --help \\ \\ ) catch {}; std.os.exit(1); } fn showHelp(comptime summary: []const u8, comptime params: anytype) void { const stderr = std.io.getStdErr().writer(); _ = stderr.write(summary ++ "\n\n") catch {}; clap.help(stderr, params) catch {}; _ = stderr.write("\n") catch {}; } fn parseHandlingHelpAndErrors( allocator: *std.mem.Allocator, comptime summary: []const u8, comptime params: anytype, iter: anytype, ) clap.ComptimeClap(clap.Help, params) { var diag: clap.Diagnostic = undefined; var args = clap.ComptimeClap(clap.Help, params).parse(allocator, iter, &diag) catch |err| { // Report useful error and exit const stderr = std.io.getStdErr().writer(); diag.report(stderr, err) catch {}; showHelp(summary, params); std.os.exit(1); }; // formerly checkHelp(summary, params, args); if (args.flag("--help")) { showHelp(summary, params); std.os.exit(0); } return args; } pub fn main() !void { try zfetch.init(); defer zfetch.deinit(); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = &gpa.allocator; runCommands(allocator) catch |err| { switch (err) { error.Explained => std.process.exit(1), else => return err, } }; } fn runCommands(allocator: *std.mem.Allocator) !void { var iter = try clap.args.OsIterator.init(allocator); defer iter.deinit(); const stderr = std.io.getStdErr().writer(); const cmd_str = (try iter.next()) orelse { try stderr.print("no command given\n", .{}); printUsage(); }; const cmd = inline for (std.meta.fields(Command)) |field| { if (std.mem.eql(u8, cmd_str, field.name)) { break @field(Command, field.name); } } else { try stderr.print("{s} is not a valid command\n", .{cmd_str}); printUsage(); }; @setEvalBranchQuota(2000); switch (cmd) { .build => try build(allocator, &iter), .fetch => try fetch(allocator), .update => try update(allocator), .init => { const summary = "Initialize a gyro.zzz with a link to a github repo"; const params = comptime [_]clap.Param(clap.Help){ clap.parseParam("-h, --help Display help") catch unreachable, clap.Param(clap.Help){ .takes_value = .One, }, }; var args = parseHandlingHelpAndErrors(allocator, summary, &params, &iter); defer args.deinit(); const num = args.positionals().len; if (num < 1) { std.log.err("please give me a link to your github repo or just '<user>/<repo>'", .{}); return error.Explained; } else if (num > 1) { std.log.err("that's too many args, please just give me one in the form of a link to your github repo or just '<user>/<repo>'", .{}); return error.Explained; } try init(allocator, args.positionals()[0]); }, .add => { // TODO: add more arguments const summary = "Add dependencies to the project"; const params = comptime [_]clap.Param(clap.Help){ clap.parseParam("-h, --help Display help") catch unreachable, clap.parseParam("-b, --build-dep Add a build dependency") catch unreachable, clap.parseParam("-g, --github Get dependency from a git repo") catch unreachable, clap.Param(clap.Help){ .takes_value = .Many, }, }; var args = parseHandlingHelpAndErrors(allocator, summary, &params, &iter); defer args.deinit(); try add(allocator, args.positionals(), args.flag("--build-dep"), args.flag("--github")); }, .package => { const summary = "Bundle package(s) into a ziglet"; const params = comptime [_]clap.Param(clap.Help){ clap.parseParam("-h, --help Display help") catch unreachable, clap.parseParam("-o, --output-dir <DIR> Directory to put tarballs in") catch unreachable, clap.Param(clap.Help){ .takes_value = .Many, }, }; var args = parseHandlingHelpAndErrors(allocator, summary, &params, &iter); defer args.deinit(); try package(allocator, args.option("--output-dir"), args.positionals()); }, } } test "all" { std.testing.refAllDecls(@import("Dependency.zig")); }
src/main.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"); pub const Blob = opaque { pub fn deinit(self: *Blob) void { log.debug("Blob.deinit called", .{}); c.git_blob_free(@ptrCast(*c.git_blob, self)); log.debug("Blob freed successfully", .{}); } pub fn id(self: *const Blob) *const git.Oid { log.debug("Blame.id called", .{}); const ret = @ptrCast(*const git.Oid, c.git_blob_id(@ptrCast(*const c.git_blob, self))); // This check is to prevent formating the oid when we are not going to print anything if (@enumToInt(std.log.Level.debug) <= @enumToInt(std.log.level)) { var buf: [git.Oid.HEX_BUFFER_SIZE]u8 = undefined; if (ret.formatHex(&buf)) |slice| { log.debug("successfully fetched blob id: {s}", .{slice}); } else |_| { log.debug("successfully fetched blob id, but unable to format it", .{}); } } return ret; } pub fn owner(self: *const Blob) *git.Repository { log.debug("Blame.owner called", .{}); const ret = @ptrCast( *git.Repository, c.git_blob_owner(@ptrCast(*const c.git_blob, self)), ); log.debug("successfully fetched owning repository: {s}", .{ret}); return ret; } pub fn rawContent(self: *const Blob) !*const anyopaque { log.debug("Blame.rawContent called", .{}); if (c.git_blob_rawcontent(@ptrCast(*const c.git_blob, self))) |ret| { log.debug("successfully fetched raw content pointer: {*}", .{ret}); return ret; } else { return error.Invalid; } } pub fn rawContentLength(self: *const Blob) u64 { log.debug("Blame.rawContentLength called", .{}); const return_type_signedness: std.builtin.Signedness = comptime blk: { const ret_type = @typeInfo(@TypeOf(c.git_blob_rawsize)).Fn.return_type.?; break :blk @typeInfo(ret_type).Int.signedness; }; const ret = c.git_blob_rawsize(@ptrCast(*const c.git_blob, self)); log.debug("successfully fetched raw content length: {}", .{ret}); if (return_type_signedness == .signed) { return @intCast(u64, ret); } return ret; } pub fn isBinary(self: *const Blob) bool { return c.git_blob_is_binary(@ptrCast(*const c.git_blob, self)) == 1; } pub fn copy(self: *Blob) !*Blob { var new_blob: *Blob = undefined; const ret = c.git_blob_dup( @ptrCast(*?*c.git_blob, &new_blob), @ptrCast(*c.git_blob, self), ); // This always returns 0 std.debug.assert(ret == 0); return new_blob; } pub fn filter(self: *Blob, as_path: [:0]const u8, options: FilterOptions) !git.Buf { log.debug("Blob.filter called, as_path={s}, options={}", .{ as_path, options }); var buf: git.Buf = .{}; var c_options = options.makeCOptionObject(); try internal.wrapCall("git_blob_filter", .{ @ptrCast(*c.git_buf, &buf), @ptrCast(*c.git_blob, self), as_path.ptr, &c_options, }); log.debug("successfully filtered blob", .{}); return buf; } pub const FilterOptions = struct { flags: BlobFilterFlags = .{}, commit_id: ?*git.Oid = null, /// The commit to load attributes from, when `FilterFlags.ATTRIBUTES_FROM_COMMIT` is specified. attr_commit_id: git.Oid = .{.id = [_]u8{0}**20}, pub const BlobFilterFlags = packed struct { /// When set, filters will not be applied to binary files. CHECK_FOR_BINARY: bool = false, /// When set, filters will not load configuration from the system-wide `gitattributes` in `/etc` (or system equivalent). NO_SYSTEM_ATTRIBUTES: bool = false, /// When set, filters will be loaded from a `.gitattributes` file in the HEAD commit. ATTRIBUTES_FROM_HEAD: bool = false, /// When set, filters will be loaded from a `.gitattributes` file in the specified commit. ATTRIBUTES_FROM_COMMIT: bool = false, z_padding: u28 = 0, pub fn format( value: BlobFilterFlags, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { _ = fmt; return internal.formatWithoutFields( value, options, writer, &.{"z_padding"}, ); } test { try std.testing.expectEqual(@sizeOf(u32), @sizeOf(BlobFilterFlags)); try std.testing.expectEqual(@bitSizeOf(u32), @bitSizeOf(BlobFilterFlags)); } comptime { std.testing.refAllDecls(@This()); } }; pub fn makeCOptionObject(self: FilterOptions) c.git_blob_filter_options { return .{ .version = c.GIT_BLOB_FILTER_OPTIONS_VERSION, .flags = @bitCast(u32, self.flags), .commit_id = @ptrCast(?*c.git_oid, self.commit_id), .attr_commit_id = @bitCast(c.git_oid, self.attr_commit_id), }; } comptime { std.testing.refAllDecls(@This()); } }; comptime { std.testing.refAllDecls(@This()); } }; comptime { std.testing.refAllDecls(@This()); }
src/blob.zig
const std = @import("std"); const debug = std.debug; const assert = debug.assert; const assertError = debug.assertError; const warn = debug.warn; const mem = std.mem; const math = std.math; const Allocator = mem.Allocator; const builtin = @import("builtin"); const TypeId = builtin.TypeId; const globals = @import("modules/globals.zig"); const pDb = &globals.debug_bits; fn d(bit: usize) bool { return pDb.r(globals.dbg_offset_parsers + bit) == 1; } fn dbgw(bit: usize, value: usize) void { pDb.w(globals.dbg_offset_parsers + bit, value); } fn toLower(ch: u8) u8 { return if ((ch >= 'A') and (ch <= 'Z')) ch + ('a' - 'A') else ch; } pub fn U8Iter() type { return struct { const Self = @This(); initial_idx: usize, idx: usize, str: []const u8, pub fn init(str: []const u8, initial_idx: usize) Self { return Self{ .initial_idx = initial_idx, .idx = initial_idx, .str = str, }; } pub fn set(pSelf: *Self, str: []const u8, initial_idx: usize) void { pSelf.initial_idx = initial_idx; pSelf.idx = initial_idx; pSelf.str = str; } pub fn done(pSelf: *Self) bool { return pSelf.idx >= pSelf.str.len; } pub fn next(pSelf: *Self) void { if (!pSelf.done()) pSelf.idx += 1; if (d(0)) warn("I: next {}\n", pSelf); } pub fn curIdx(pSelf: *Self) usize { return pSelf.idx; } pub fn curCh(pSelf: *Self) u8 { if (pSelf.done()) return 0; return pSelf.str[pSelf.idx]; } pub fn curChLc(pSelf: *Self) u8 { return toLower(pSelf.curCh()); } // Peek next character, if end of string pub fn peekNextCh(pSelf: *Self) u8 { if (pSelf.done()) return 0; return pSelf.curCh(); } // Peek Prev character or first character or 0 if end of string pub fn peekPrevCh(pSelf: *Self) u8 { var idx = if (pSelf.idx > pSelf.initial_idx) pSelf.idx - 1 else pSelf.idx; if (pSelf.done()) return 0; return pSelf.str[pSelf.idx]; } // Next character or 0 if end of string pub fn nextCh(pSelf: *Self) u8 { if (pSelf.done()) return 0; var ch = pSelf.str[pSelf.idx]; pSelf.idx += 1; return ch; } // Prev character or first character or if string is empty 0 pub fn prevCh(pSelf: *Self) u8 { if (pSelf.idx > pSelf.initial_idx) pSelf.idx -= 1; return pSelf.peekNextCh(); } // Next character skipping white space characters or 0 if end of string // Ignore ' ':0x20, HT:0x9 // What about LF:0xA, VT:0xB, FF:0xC, CR:0xD, NEL:0x85, NBS:0xA0? // Or other White Space chars: https://en.wikipedia.org/wiki/Whitespace_character pub fn skipWs(pSelf: *Self) u8 { var ch = pSelf.curCh(); while ((ch == ' ') or (ch == '\t')) { pSelf.next(); ch = pSelf.curCh(); } if (d(0)) warn("SkipWs:- ch='{c}':0x{x} {}\n", ch, ch, pSelf); return ch; } // Next character converted to lower case or 0 if end of string pub fn nextChLc(pSelf: *Self) u8 { return toLower(pSelf.nextCh()); } // Prev character converted to lower case or 0 the string is empty pub fn prevChLc(pSelf: *Self) u8 { return toLower(pSelf.prevCh()); } // Next character converted to lower case skipping leading white space character pub fn nextChLcSkipWs(pSelf: *Self) u8 { return toLower(pSelf.skipWs()); } }; } pub fn ParseResult(comptime T: type) type { return struct { const Self = @This(); last_idx: usize, value: T, value_set: bool, digits: usize, pub fn init() Self { //warn("PR: init\n"); return Self{ .last_idx = 0, .value = 0, .value_set = false, .digits = 0, }; } pub fn reinit(pSelf: *Self) void { //warn("PR: reinit\n"); pSelf.last_idx = 0; pSelf.value = 0; pSelf.value_set = false; pSelf.digits = 0; } pub fn set(pSelf: *Self, v: T, last_idx: usize, digits: usize) void { //warn("PR: set v={} last_idx={}\n", v, last_idx); pSelf.last_idx = last_idx; pSelf.value = v; pSelf.value_set = true; pSelf.digits = digits; } }; } // Return last charter with 0 if end of string pub fn parseNumber(comptime T: type, pIter: *U8Iter(), radix_val: usize) ParseResult(T) { var result = ParseResult(T).init(); pIter.initial_idx = pIter.idx; //var ch = pIter.curChLc(); var ch = pIter.nextChLc(); if (d(0)) warn("PN:+ pr={}, it={} ch='{c}':0x{x}\n", result, pIter, ch, ch); defer if (d(0)) warn("PN:- pr={} it={} ch='{c}':0x{x}\n", result, pIter, ch, ch); var radix = radix_val; var value: u128 = 0; var negative: i128 = 1; // Handle leading +, - if (ch == '-') { ch = pIter.nextChLc(); if (d(1)) warn("PN: neg ch='{c}':0x{x}\n", ch, ch); negative = -1; } else if (ch == '+') { ch = pIter.nextChLc(); if (d(1)) warn("PN: plus ch='{c}':0x{x}\n", ch, ch); negative = 1; } // Handle radix if not passed if (radix == 0) { if ((ch == '0') and !pIter.done()) { switch (pIter.nextChLc()) { 'b' => { radix = 2; ch = pIter.nextChLc(); }, 'o' => { radix = 8; ch = pIter.nextChLc(); }, 'd' => { radix = 10; ch = pIter.nextChLc(); }, 'x' => { radix = 16; ch = pIter.nextChLc(); }, else => { radix = 10; ch = pIter.prevChLc(); }, } if (d(1)) warn("PN: radix={} ch='{c}':0x{x}\n", radix, ch, ch); } else { radix = 10; if (d(1)) warn("PN: default radix={} ch='{c}':0x{x}\n", radix, ch, ch); } } // Handle remaining digits until end of string or an invalid character var digits: usize = 0; while (ch != 0) : (ch = pIter.nextChLc()) { if (d(1)) warn("PN: TOL value={} it={} digits={} ch='{c}':0x{x}\n", value, pIter, digits, ch, ch); if (ch == '_') { continue; } var v: u8 = undefined; if ((ch >= '0') and (ch <= '9')) { v = ch - '0'; } else if ((ch >= 'a') and (ch <= 'f')) { v = 10 + (ch - 'a'); } else { // An invalid character, done if (d(1)) warn("PN: bad ch='{c}':0x{x}\n", ch, ch); _ = pIter.prevCh(); break; } // An invalid character for current radix, done if (v >= radix) { if (d(1)) warn("PN: v:{} >= radix:{} ch='{c}':0x{x}\n", v, radix, ch, ch); _ = pIter.prevCh(); break; } value *= radix; value += v; digits += 1; } if (d(1)) warn("PN: AL value={} it={} digits={}\n", value, pIter, digits); // We didn't have any digits don't update result if (digits > 0) { if (negative < 0) { value = @bitCast(u128, negative *% @intCast(i128, value)); } if (T.is_signed) { result.set(@intCast(T, @intCast(i128, value) & @intCast(T, -1)), pIter.curIdx(), digits); } else { result.set(@intCast(T, value & math.maxInt(T)), pIter.curIdx(), digits); } } return result; } pub fn parseIntegerNumber(comptime T: type, pIter: *U8Iter()) !T { var result = ParseResult(T).init(); var ch = pIter.skipWs(); if (d(0)) warn("PIN:+ pr={} it={} ch='{c}':0x{x}\n", result, pIter, ch, ch); defer if (d(0)) warn("PIN:- pr={} it={} ch='{c}':0x{x}\n", result, pIter, ch, ch); result = parseNumber(T, pIter, 0); if (!result.value_set) { return error.NoValue; } return result.value; } pub fn parseFloatNumber(comptime T: type, pIter: *U8Iter()) !T { var ch = pIter.skipWs(); var pr = ParseResult(T).init(); if (d(0)) warn("PFN:+ pr={} it={} ch='{c}':0x{x}\n", pr, pIter, ch, ch); defer if (d(0)) warn("PFN:- pr={} it={} ch='{c}':0x{x}\n", pr, pIter, ch, ch); // Get Tens var pr_tens = parseNumber(i128, pIter, 10); if (pr_tens.value_set) { if (d(1)) warn("PFN: pr_tens={} it={} ch='{c}':0x{x}\n", pr_tens, pIter, pIter.curCh(), pIter.curCh()); var pr_fraction = ParseResult(i128).init(); var pr_exponent = ParseResult(i128).init(); if (pIter.curCh() == '.') { // Get fraction pIter.next(); pr_fraction = parseNumber(i128, pIter, 10); if (!pr_fraction.value_set) { if (d(1)) warn("PF: no fraction\n"); pr_fraction.set(0, pIter.idx, 0); } } if (d(1)) warn("PFN: pr_fraction={} it={} ch='{c}':0x{x}\n", pr_fraction, pIter, pIter.curCh(), pIter.curCh()); if (pIter.curCh() == 'e') { // Get Exponent pIter.next(); // skip e pr_exponent = parseNumber(i128, pIter, 10); if (!pr_exponent.value_set) { if (d(1)) warn("PF: no exponent\n"); pr_exponent.set(0, pIter.idx, 0); } } if (d(1)) warn("PFN: pr_exponent={} it={} ch='{c}':0x{x}\n", pr_exponent, pIter, pIter.curCh(), pIter.curCh()); var tens = @intToFloat(T, pr_tens.value); var fraction = @intToFloat(T, pr_fraction.value) / std.math.pow(T, 10, @intToFloat(T, pr_fraction.digits)); var significand: T = if (pr_tens.value >= 0) tens + fraction else tens - fraction; var value = significand * std.math.pow(T, @intToFloat(T, 10), @intToFloat(T, pr_exponent.value)); pr.set(value, pIter.idx, pr_tens.digits + pr_fraction.digits); if (d(1)) warn("PFN:-- pr.value={}\n", pr.value); return pr.value; } return error.NoValue; } pub fn ParseNumber(comptime T: type) type { return struct { const Self = @This(); fn parse(str: []const u8) !T { if (d(0)) warn("ParseNumber:+ str={}\n", str); var it: U8Iter() = undefined; it.set(str, 0); var result = try switch (TypeId(@typeInfo(T))) { TypeId.Int => parseIntegerNumber(T, &it), TypeId.Float => parseFloatNumber(T, &it), else => @compileError("Expecting Int or Float only"), }; // Skip any trailing WS and if we didn't conusme the entire string it's an error _ = it.skipWs(); if (it.idx < str.len) return error.NoValue; if (d(0)) warn("ParseNumber:- str={} result={}\n", str, result); return result; } }; } pub fn ParseAllocated(comptime T: type) type { return struct { fn parse(pAllocator: *Allocator, str: []const u8) anyerror!T { if (d(0)) warn("ParseAllocated:+ str={}\n", str); if (str.len == 0) return error.WTF; var result = try mem.dupe(pAllocator, u8, str); if (d(0)) warn("parseAllocated:- str={} &result={*}\n", str, &result); return str; } }; } test "parseIntegerNumber" { // Initialize the debug bits dbgw(0, 0); dbgw(1, 0); if (d(0) or d(1)) warn("\n"); var ch: u8 = undefined; var it: U8Iter() = undefined; it.set("", 0); assertError(parseIntegerNumber(u8, &it), error.NoValue); it.set("0", 0); var vU8 = try parseIntegerNumber(u8, &it); assert(vU8 == 0); assert(it.idx == 1); it.set("1 2", 0); vU8 = try parseIntegerNumber(u8, &it); if (d(0)) warn("vU8={} it={}\n", vU8, it); assert(vU8 == 1); assert(it.idx == 1); vU8 = try parseIntegerNumber(u8, &it); if (d(0)) warn("vU8={} it={}\n", vU8, it); assert(vU8 == 2); assert(it.idx == 3); it.set("\t0", 0); vU8 = try parseIntegerNumber(u8, &it); assert(vU8 == 0); assert(it.idx == 2); it.set(" \t0", 0); vU8 = try parseIntegerNumber(u8, &it); assert(vU8 == 0); assert(it.idx == 3); it.set(" \t 0", 0); vU8 = try parseIntegerNumber(u8, &it); assert(vU8 == 0); assert(it.idx == 4); it.set("1.", 0); vU8 = try parseIntegerNumber(u8, &it); assert(vU8 == 1); assert(it.idx == 1); } test "parseFloatNumber" { if (d(0)) warn("\n"); var ch: u8 = undefined; var it: U8Iter() = undefined; var vF32: f32 = undefined; it.set("", 0); assertError(parseFloatNumber(f32, &it), error.NoValue); it.set("0", 0); vF32 = try parseFloatNumber(f32, &it); assert(vF32 == 0); assert(it.idx == 1); it.set("1", 0); vF32 = try parseFloatNumber(f32, &it); assert(vF32 == 1); assert(it.idx == 1); it.set("+1", 0); vF32 = try parseFloatNumber(f32, &it); assert(vF32 == 1); assert(it.idx == 2); it.set("-1", 0); vF32 = try parseFloatNumber(f32, &it); assert(vF32 == -1); assert(it.idx == 2); it.set("1.2", 0); vF32 = try parseFloatNumber(f32, &it); assert(vF32 == 1.2); assert(it.idx == 3); it.set("1e1", 0); vF32 = try parseFloatNumber(f32, &it); assert(vF32 == 10); assert(it.idx == 3); it.set("1.2 3.4", 0); vF32 = try parseFloatNumber(f32, &it); if (d(0)) warn("vF32={} it={}\n", vF32, it); assert(vF32 == 1.2); assert(it.idx == 3); vF32 = try parseFloatNumber(f32, &it); if (d(0)) warn("vF32={} it={}\n", vF32, it); assert(vF32 == 3.4); assert(it.idx == 7); } test "ParseNumber" { assertError(ParseNumber(u8).parse(""), error.NoValue); assert((try ParseNumber(u8).parse("0")) == 0); assert((try ParseNumber(u8).parse(" 1")) == 1); assert((try ParseNumber(u8).parse(" 2 ")) == 2); assertError(ParseNumber(u8).parse(" 2d"), error.NoValue); const s = " \t 123\t"; var slice = s[0..]; assert((try ParseNumber(u8).parse(slice)) == 123); assert((try ParseNumber(i8).parse("-1")) == -1); assert((try ParseNumber(i8).parse("1")) == 1); assert((try ParseNumber(i8).parse("+1")) == 1); assert((try ParseNumber(u8).parse("0b0")) == 0); assert((try ParseNumber(u8).parse("0b1")) == 1); assert((try ParseNumber(u8).parse("0b1010_0101")) == 0xA5); assertError(ParseNumber(u8).parse("0b2"), error.NoValue); assert((try ParseNumber(u8).parse("0o0")) == 0); assert((try ParseNumber(u8).parse("0o1")) == 1); assert((try ParseNumber(u8).parse("0o7")) == 7); assert((try ParseNumber(u8).parse("0o77")) == 0x3f); assert((try ParseNumber(u32).parse("0o111_777")) == 0b1001001111111111); assertError(ParseNumber(u8).parse("0b8"), error.NoValue); assert((try ParseNumber(u8).parse("0d0")) == 0); assert((try ParseNumber(u8).parse("0d1")) == 1); assert((try ParseNumber(u8).parse("-0d1")) == 255); assert((try ParseNumber(i8).parse("-0d1")) == -1); assert((try ParseNumber(i8).parse("+0d1")) == 1); assert((try ParseNumber(u8).parse("0d9")) == 9); assert((try ParseNumber(u8).parse("0")) == 0); assert((try ParseNumber(u8).parse("-1")) == 255); assert((try ParseNumber(u8).parse("9")) == 9); assert((try ParseNumber(u8).parse("127")) == 0x7F); assert((try ParseNumber(u8).parse("-127")) == 0x81); assert((try ParseNumber(u8).parse("-128")) == 0x80); assert((try ParseNumber(u8).parse("255")) == 255); assert((try ParseNumber(u8).parse("256")) == 0); assert((try ParseNumber(u64).parse("123_456_789")) == 123456789); assert((try ParseNumber(u8).parse("0x0")) == 0x0); assert((try ParseNumber(u8).parse("0x1")) == 0x1); assert((try ParseNumber(u8).parse("0x9")) == 0x9); assert((try ParseNumber(u8).parse("0xa")) == 0xa); assert((try ParseNumber(u8).parse("0xf")) == 0xf); assert((try ParseNumber(i128).parse("-170141183460469231731687303715884105728")) == @bitCast(i128, @intCast(u128, 0x80000000000000000000000000000000))); assert((try ParseNumber(i128).parse("-170141183460469231731687303715884105727")) == @bitCast(i128, @intCast(u128, 0x80000000000000000000000000000001))); assert((try ParseNumber(i128).parse("-1")) == @bitCast(i128, @intCast(u128, 0xffffffffffffffffffffffffffffffff))); assert((try ParseNumber(i128).parse("0")) == @bitCast(i128, @intCast(u128, 0x00000000000000000000000000000000))); assert((try ParseNumber(i128).parse("170141183460469231731687303715884105726")) == @bitCast(i128, @intCast(u128, 0x7ffffffffffffffffffffffffffffffe))); assert((try ParseNumber(i128).parse("170141183460469231731687303715884105727")) == @bitCast(i128, @intCast(u128, 0x7fffffffffffffffffffffffffffffff))); assert((try ParseNumber(u128).parse("0")) == 0); assert((try ParseNumber(u128).parse("1")) == 1); assert((try ParseNumber(u128).parse("340282366920938463463374607431768211454")) == 0xfffffffffffffffffffffffffffffffe); assert((try ParseNumber(u128).parse("340282366920938463463374607431768211455")) == 0xffffffffffffffffffffffffffffffff); assert((try ParseNumber(u128).parse("0x1234_5678_9ABc_Def0_0FEd_Cba9_8765_4321")) == 0x123456789ABcDef00FEdCba987654321); assertError(ParseNumber(u8).parse("0xg"), error.NoValue); assert((try ParseNumber(f32).parse("0")) == 0); assert((try ParseNumber(f32).parse("-1")) == -1); assert((try ParseNumber(f32).parse("1.")) == 1.0); assert((try ParseNumber(f32).parse("1e0")) == 1); assert((try ParseNumber(f32).parse("1e1")) == 10); assert((try ParseNumber(f32).parse("1e-1")) == 0.1); assert((try ParseNumber(f64).parse("0.1")) == 0.1); assert((try ParseNumber(f64).parse("-1.")) == -1.0); assert((try ParseNumber(f64).parse("-2.1")) == -2.1); assert((try ParseNumber(f64).parse("-1.2")) == -1.2); assert(floatFuzzyEql(f64, try ParseNumber(f64).parse("1.2e2"), 1.2e2, 0.00001)); assert(floatFuzzyEql(f64, try ParseNumber(f64).parse("-1.2e-2"), -1.2e-2, 0.00001)); } pub fn floatFuzzyEql(comptime T: type, lhs: T, rhs: T, fuz: T) bool { // Determine which is larger and smallerj // then add the fuz to smaller and subract from larger // If smaller >= larger then they are equal var smaller: T = undefined; var larger: T = undefined; if (lhs > rhs) { larger = lhs - fuz; smaller = rhs + fuz; } else { larger = rhs - fuz; smaller = lhs + fuz; } //warn("smaller={} larger={}\n", smaller, larger); return smaller >= larger; } test "ParseAllocated" { var s = try ParseAllocated([]const u8).parse(debug.global_allocator, "hi"); defer debug.global_allocator.free(s); assert(mem.eql(u8, s, "hi")); }
parsers.zig
const std = @import("std"); const math = std.math; const common = @import("common.zig"); const FloatInfo = @import("FloatInfo.zig"); const Number = common.Number; const floatFromU64 = common.floatFromU64; fn isFastPath(comptime T: type, n: Number(T)) bool { const info = FloatInfo.from(T); return info.min_exponent_fast_path <= n.exponent and n.exponent <= info.max_exponent_fast_path_disguised and n.mantissa <= info.max_mantissa_fast_path and !n.many_digits; } // upper bound for tables is floor(mantissaDigits(T) / log2(5)) // for f64 this is floor(53 / log2(5)) = 22. // // Must have max_disguised_fast_path - max_exponent_fast_path entries. (82 - 48 = 34 for f128) fn fastPow10(comptime T: type, i: usize) T { return switch (T) { f16 => ([8]f16{ 1e0, 1e1, 1e2, 1e3, 1e4, 0, 0, 0, })[i & 7], f32 => ([16]f32{ 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 0, 0, 0, 0, 0, })[i & 15], f64 => ([32]f64{ 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22, 0, 0, 0, 0, 0, 0, 0, 0, 0, })[i & 31], f128 => ([64]f128{ 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22, 1e23, 1e24, 1e25, 1e26, 1e27, 1e28, 1e29, 1e30, 1e31, 1e32, 1e33, 1e34, 1e35, 1e36, 1e37, 1e38, 1e39, 1e40, 1e41, 1e42, 1e43, 1e44, 1e45, 1e46, 1e47, 1e48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, })[i & 63], else => unreachable, }; } fn fastIntPow10(comptime T: type, i: usize) T { return switch (T) { u64 => ([16]u64{ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000, 100000000000, 1000000000000, 10000000000000, 100000000000000, 1000000000000000, })[i], u128 => ([35]u128{ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000, 100000000000, 1000000000000, 10000000000000, 100000000000000, 1000000000000000, 10000000000000000, 100000000000000000, 1000000000000000000, 10000000000000000000, 100000000000000000000, 1000000000000000000000, 10000000000000000000000, 100000000000000000000000, 1000000000000000000000000, 10000000000000000000000000, 100000000000000000000000000, 1000000000000000000000000000, 10000000000000000000000000000, 100000000000000000000000000000, 1000000000000000000000000000000, 10000000000000000000000000000000, 100000000000000000000000000000000, 1000000000000000000000000000000000, 10000000000000000000000000000000000, })[i], else => unreachable, }; } pub fn convertFast(comptime T: type, n: Number(T)) ?T { const MantissaT = common.mantissaType(T); if (!isFastPath(T, n)) { return null; } // TODO: x86 (no SSE/SSE2) requires x87 FPU to be setup correctly with fldcw const info = FloatInfo.from(T); var value: T = 0; if (n.exponent <= info.max_exponent_fast_path) { // normal fast path value = @intToFloat(T, n.mantissa); value = if (n.exponent < 0) value / fastPow10(T, @intCast(usize, -n.exponent)) else value * fastPow10(T, @intCast(usize, n.exponent)); } else { // disguised fast path const shift = n.exponent - info.max_exponent_fast_path; const mantissa = math.mul(MantissaT, n.mantissa, fastIntPow10(MantissaT, @intCast(usize, shift))) catch return null; if (mantissa > info.max_mantissa_fast_path) { return null; } value = @intToFloat(T, mantissa) * fastPow10(T, info.max_exponent_fast_path); } if (n.negative) { value = -value; } return value; }
lib/std/fmt/parse_float/convert_fast.zig
const std = @import("std.zig"); const builtin = @import("builtin"); const os = std.os; const fs = std.fs; const mem = std.mem; const math = std.math; const Allocator = mem.Allocator; const assert = std.debug.assert; const testing = std.testing; const child_process = @import("child_process.zig"); pub const abort = os.abort; pub const exit = os.exit; pub const changeCurDir = os.chdir; pub const changeCurDirC = os.chdirC; /// The result is a slice of `out_buffer`, from index `0`. pub fn getCwd(out_buffer: []u8) ![]u8 { return os.getcwd(out_buffer); } /// Caller must free the returned memory. pub fn getCwdAlloc(allocator: Allocator) ![]u8 { // The use of MAX_PATH_BYTES here is just a heuristic: most paths will fit // in stack_buf, avoiding an extra allocation in the common case. var stack_buf: [fs.MAX_PATH_BYTES]u8 = undefined; var heap_buf: ?[]u8 = null; defer if (heap_buf) |buf| allocator.free(buf); var current_buf: []u8 = &stack_buf; while (true) { if (os.getcwd(current_buf)) |slice| { return allocator.dupe(u8, slice); } else |err| switch (err) { error.NameTooLong => { // The path is too long to fit in stack_buf. Allocate geometrically // increasing buffers until we find one that works const new_capacity = current_buf.len * 2; if (heap_buf) |buf| allocator.free(buf); current_buf = try allocator.alloc(u8, new_capacity); heap_buf = current_buf; }, else => |e| return e, } } } test "getCwdAlloc" { if (builtin.os.tag == .wasi) return error.SkipZigTest; const cwd = try getCwdAlloc(testing.allocator); testing.allocator.free(cwd); } pub const EnvMap = struct { hash_map: HashMap, const HashMap = std.HashMap( []const u8, []const u8, EnvNameHashContext, std.hash_map.default_max_load_percentage, ); pub const Size = HashMap.Size; pub const EnvNameHashContext = struct { fn upcase(c: u21) u21 { if (c <= std.math.maxInt(u16)) return std.os.windows.ntdll.RtlUpcaseUnicodeChar(@intCast(u16, c)); return c; } pub fn hash(self: @This(), s: []const u8) u64 { _ = self; if (builtin.os.tag == .windows) { var h = std.hash.Wyhash.init(0); var it = std.unicode.Utf8View.initUnchecked(s).iterator(); while (it.nextCodepoint()) |cp| { const cp_upper = upcase(cp); h.update(&[_]u8{ @intCast(u8, (cp_upper >> 16) & 0xff), @intCast(u8, (cp_upper >> 8) & 0xff), @intCast(u8, (cp_upper >> 0) & 0xff), }); } return h.final(); } return std.hash_map.hashString(s); } pub fn eql(self: @This(), a: []const u8, b: []const u8) bool { _ = self; if (builtin.os.tag == .windows) { var it_a = std.unicode.Utf8View.initUnchecked(a).iterator(); var it_b = std.unicode.Utf8View.initUnchecked(b).iterator(); while (true) { const c_a = it_a.nextCodepoint() orelse break; const c_b = it_b.nextCodepoint() orelse return false; if (upcase(c_a) != upcase(c_b)) return false; } return if (it_b.nextCodepoint()) |_| false else true; } return std.hash_map.eqlString(a, b); } }; /// Create a EnvMap backed by a specific allocator. /// That allocator will be used for both backing allocations /// and string deduplication. pub fn init(allocator: Allocator) EnvMap { return EnvMap{ .hash_map = HashMap.init(allocator) }; } /// Free the backing storage of the map, as well as all /// of the stored keys and values. pub fn deinit(self: *EnvMap) void { var it = self.hash_map.iterator(); while (it.next()) |entry| { self.free(entry.key_ptr.*); self.free(entry.value_ptr.*); } self.hash_map.deinit(); } /// Same as `put` but the key and value become owned by the EnvMap rather /// than being copied. /// If `putMove` fails, the ownership of key and value does not transfer. /// On Windows `key` must be a valid UTF-8 string. pub fn putMove(self: *EnvMap, key: []u8, value: []u8) !void { const get_or_put = try self.hash_map.getOrPut(key); if (get_or_put.found_existing) { self.free(get_or_put.key_ptr.*); self.free(get_or_put.value_ptr.*); get_or_put.key_ptr.* = key; } get_or_put.value_ptr.* = value; } /// `key` and `value` are copied into the EnvMap. /// On Windows `key` must be a valid UTF-8 string. pub fn put(self: *EnvMap, key: []const u8, value: []const u8) !void { const value_copy = try self.copy(value); errdefer self.free(value_copy); const get_or_put = try self.hash_map.getOrPut(key); if (get_or_put.found_existing) { self.free(get_or_put.value_ptr.*); } else { get_or_put.key_ptr.* = self.copy(key) catch |err| { _ = self.hash_map.remove(key); return err; }; } get_or_put.value_ptr.* = value_copy; } /// Find the address of the value associated with a key. /// The returned pointer is invalidated if the map resizes. /// On Windows `key` must be a valid UTF-8 string. pub fn getPtr(self: EnvMap, key: []const u8) ?*[]const u8 { return self.hash_map.getPtr(key); } /// Return the map's copy of the value associated with /// a key. The returned string is invalidated if this /// key is removed from the map. /// On Windows `key` must be a valid UTF-8 string. pub fn get(self: EnvMap, key: []const u8) ?[]const u8 { return self.hash_map.get(key); } /// Removes the item from the map and frees its value. /// This invalidates the value returned by get() for this key. /// On Windows `key` must be a valid UTF-8 string. pub fn remove(self: *EnvMap, key: []const u8) void { const kv = self.hash_map.fetchRemove(key) orelse return; self.free(kv.key); self.free(kv.value); } /// Returns the number of KV pairs stored in the map. pub fn count(self: EnvMap) HashMap.Size { return self.hash_map.count(); } /// Returns an iterator over entries in the map. pub fn iterator(self: *const EnvMap) HashMap.Iterator { return self.hash_map.iterator(); } fn free(self: EnvMap, value: []const u8) void { self.hash_map.allocator.free(value); } fn copy(self: EnvMap, value: []const u8) ![]u8 { return self.hash_map.allocator.dupe(u8, value); } }; test "EnvMap" { var env = EnvMap.init(testing.allocator); defer env.deinit(); try env.put("SOMETHING_NEW", "hello"); try testing.expectEqualStrings("hello", env.get("SOMETHING_NEW").?); try testing.expectEqual(@as(EnvMap.Size, 1), env.count()); // overwrite try env.put("SOMETHING_NEW", "something"); try testing.expectEqualStrings("something", env.get("SOMETHING_NEW").?); try testing.expectEqual(@as(EnvMap.Size, 1), env.count()); // a new longer name to test the Windows-specific conversion buffer try env.put("SOMETHING_NEW_AND_LONGER", "1"); try testing.expectEqualStrings("1", env.get("SOMETHING_NEW_AND_LONGER").?); try testing.expectEqual(@as(EnvMap.Size, 2), env.count()); // case insensitivity on Windows only if (builtin.os.tag == .windows) { try testing.expectEqualStrings("1", env.get("something_New_aNd_LONGER").?); } else { try testing.expect(null == env.get("something_New_aNd_LONGER")); } var it = env.iterator(); var count: EnvMap.Size = 0; while (it.next()) |entry| { const is_an_expected_name = std.mem.eql(u8, "SOMETHING_NEW", entry.key_ptr.*) or std.mem.eql(u8, "SOMETHING_NEW_AND_LONGER", entry.key_ptr.*); try testing.expect(is_an_expected_name); count += 1; } try testing.expectEqual(@as(EnvMap.Size, 2), count); env.remove("SOMETHING_NEW"); try testing.expect(env.get("SOMETHING_NEW") == null); try testing.expectEqual(@as(EnvMap.Size, 1), env.count()); // test Unicode case-insensitivity on Windows if (builtin.os.tag == .windows) { try env.put("КИРиллИЦА", "something else"); try testing.expectEqualStrings("something else", env.get("кириллица").?); } } /// Returns a snapshot of the environment variables of the current process. /// Any modifications to the resulting EnvMap will not be not reflected in the environment, and /// likewise, any future modifications to the environment will not be reflected in the EnvMap. /// Caller owns resulting `EnvMap` and should call its `deinit` fn when done. pub fn getEnvMap(allocator: Allocator) !EnvMap { var result = EnvMap.init(allocator); errdefer result.deinit(); if (builtin.os.tag == .windows) { const ptr = os.windows.peb().ProcessParameters.Environment; var i: usize = 0; while (ptr[i] != 0) { const key_start = i; // There are some special environment variables that start with =, // so we need a special case to not treat = as a key/value separator // if it's the first character. // https://devblogs.microsoft.com/oldnewthing/20100506-00/?p=14133 if (ptr[key_start] == '=') i += 1; while (ptr[i] != 0 and ptr[i] != '=') : (i += 1) {} const key_w = ptr[key_start..i]; const key = try std.unicode.utf16leToUtf8Alloc(allocator, key_w); errdefer allocator.free(key); if (ptr[i] == '=') i += 1; const value_start = i; while (ptr[i] != 0) : (i += 1) {} const value_w = ptr[value_start..i]; const value = try std.unicode.utf16leToUtf8Alloc(allocator, value_w); errdefer allocator.free(value); i += 1; // skip over null byte try result.putMove(key, value); } return result; } else if (builtin.os.tag == .wasi and !builtin.link_libc) { var environ_count: usize = undefined; var environ_buf_size: usize = undefined; const environ_sizes_get_ret = os.wasi.environ_sizes_get(&environ_count, &environ_buf_size); if (environ_sizes_get_ret != .SUCCESS) { return os.unexpectedErrno(environ_sizes_get_ret); } var environ = try allocator.alloc([*:0]u8, environ_count); defer allocator.free(environ); var environ_buf = try allocator.alloc(u8, environ_buf_size); defer allocator.free(environ_buf); const environ_get_ret = os.wasi.environ_get(environ.ptr, environ_buf.ptr); if (environ_get_ret != .SUCCESS) { return os.unexpectedErrno(environ_get_ret); } for (environ) |env| { const pair = mem.sliceTo(env, 0); var parts = mem.split(u8, pair, "="); const key = parts.next().?; const value = parts.next().?; try result.put(key, value); } return result; } else if (builtin.link_libc) { var ptr = std.c.environ; while (ptr.*) |line| : (ptr += 1) { var line_i: usize = 0; while (line[line_i] != 0 and line[line_i] != '=') : (line_i += 1) {} const key = line[0..line_i]; var end_i: usize = line_i; while (line[end_i] != 0) : (end_i += 1) {} const value = line[line_i + 1 .. end_i]; try result.put(key, value); } return result; } else { for (os.environ) |line| { var line_i: usize = 0; while (line[line_i] != 0 and line[line_i] != '=') : (line_i += 1) {} const key = line[0..line_i]; var end_i: usize = line_i; while (line[end_i] != 0) : (end_i += 1) {} const value = line[line_i + 1 .. end_i]; try result.put(key, value); } return result; } } test "getEnvMap" { var env = try getEnvMap(testing.allocator); defer env.deinit(); } pub const GetEnvVarOwnedError = error{ OutOfMemory, EnvironmentVariableNotFound, /// See https://github.com/ziglang/zig/issues/1774 InvalidUtf8, }; /// Caller must free returned memory. pub fn getEnvVarOwned(allocator: mem.Allocator, key: []const u8) GetEnvVarOwnedError![]u8 { if (builtin.os.tag == .windows) { const result_w = blk: { const key_w = try std.unicode.utf8ToUtf16LeWithNull(allocator, key); defer allocator.free(key_w); break :blk std.os.getenvW(key_w) orelse return error.EnvironmentVariableNotFound; }; return std.unicode.utf16leToUtf8Alloc(allocator, result_w) catch |err| switch (err) { error.DanglingSurrogateHalf => return error.InvalidUtf8, error.ExpectedSecondSurrogateHalf => return error.InvalidUtf8, error.UnexpectedSecondSurrogateHalf => return error.InvalidUtf8, else => |e| return e, }; } else { const result = os.getenv(key) orelse return error.EnvironmentVariableNotFound; return allocator.dupe(u8, result); } } pub fn hasEnvVarConstant(comptime key: []const u8) bool { if (builtin.os.tag == .windows) { const key_w = comptime std.unicode.utf8ToUtf16LeStringLiteral(key); return std.os.getenvW(key_w) != null; } else { return os.getenv(key) != null; } } pub fn hasEnvVar(allocator: Allocator, key: []const u8) error{OutOfMemory}!bool { if (builtin.os.tag == .windows) { var stack_alloc = std.heap.stackFallback(256 * @sizeOf(u16), allocator); const key_w = try std.unicode.utf8ToUtf16LeWithNull(stack_alloc.get(), key); defer stack_alloc.allocator.free(key_w); return std.os.getenvW(key_w) != null; } else { return os.getenv(key) != null; } } test "os.getEnvVarOwned" { var ga = std.testing.allocator; try testing.expectError(error.EnvironmentVariableNotFound, getEnvVarOwned(ga, "BADENV")); } pub const ArgIteratorPosix = struct { index: usize, count: usize, pub const InitError = error{}; pub fn init() ArgIteratorPosix { return ArgIteratorPosix{ .index = 0, .count = os.argv.len, }; } pub fn next(self: *ArgIteratorPosix) ?[:0]const u8 { if (self.index == self.count) return null; const s = os.argv[self.index]; self.index += 1; return mem.sliceTo(s, 0); } pub fn skip(self: *ArgIteratorPosix) bool { if (self.index == self.count) return false; self.index += 1; return true; } }; pub const ArgIteratorWasi = struct { allocator: mem.Allocator, index: usize, args: [][:0]u8, pub const InitError = error{OutOfMemory} || os.UnexpectedError; /// You must call deinit to free the internal buffer of the /// iterator after you are done. pub fn init(allocator: mem.Allocator) InitError!ArgIteratorWasi { const fetched_args = try ArgIteratorWasi.internalInit(allocator); return ArgIteratorWasi{ .allocator = allocator, .index = 0, .args = fetched_args, }; } fn internalInit(allocator: mem.Allocator) InitError![][:0]u8 { const w = os.wasi; var count: usize = undefined; var buf_size: usize = undefined; switch (w.args_sizes_get(&count, &buf_size)) { .SUCCESS => {}, else => |err| return os.unexpectedErrno(err), } var argv = try allocator.alloc([*:0]u8, count); defer allocator.free(argv); var argv_buf = try allocator.alloc(u8, buf_size); switch (w.args_get(argv.ptr, argv_buf.ptr)) { .SUCCESS => {}, else => |err| return os.unexpectedErrno(err), } var result_args = try allocator.alloc([:0]u8, count); var i: usize = 0; while (i < count) : (i += 1) { result_args[i] = mem.sliceTo(argv[i], 0); } return result_args; } pub fn next(self: *ArgIteratorWasi) ?[:0]const u8 { if (self.index == self.args.len) return null; const arg = self.args[self.index]; self.index += 1; return arg; } pub fn skip(self: *ArgIteratorWasi) bool { if (self.index == self.args.len) return false; self.index += 1; return true; } /// Call to free the internal buffer of the iterator. pub fn deinit(self: *ArgIteratorWasi) void { const last_item = self.args[self.args.len - 1]; const last_byte_addr = @ptrToInt(last_item.ptr) + last_item.len + 1; // null terminated const first_item_ptr = self.args[0].ptr; const len = last_byte_addr - @ptrToInt(first_item_ptr); self.allocator.free(first_item_ptr[0..len]); self.allocator.free(self.args); } }; /// Optional parameters for `ArgIteratorGeneral` pub const ArgIteratorGeneralOptions = struct { comments: bool = false, single_quotes: bool = false, }; /// A general Iterator to parse a string into a set of arguments pub fn ArgIteratorGeneral(comptime options: ArgIteratorGeneralOptions) type { return struct { allocator: Allocator, index: usize = 0, cmd_line: []const u8, /// Should the cmd_line field be free'd (using the allocator) on deinit()? free_cmd_line_on_deinit: bool, /// buffer MUST be long enough to hold the cmd_line plus a null terminator. /// buffer will we free'd (using the allocator) on deinit() buffer: []u8, start: usize = 0, end: usize = 0, pub const Self = @This(); pub const InitError = error{OutOfMemory}; pub const InitUtf16leError = error{ OutOfMemory, InvalidCmdLine }; /// cmd_line_utf8 MUST remain valid and constant while using this instance pub fn init(allocator: Allocator, cmd_line_utf8: []const u8) InitError!Self { var buffer = try allocator.alloc(u8, cmd_line_utf8.len + 1); errdefer allocator.free(buffer); return Self{ .allocator = allocator, .cmd_line = cmd_line_utf8, .free_cmd_line_on_deinit = false, .buffer = buffer, }; } /// cmd_line_utf8 will be free'd (with the allocator) on deinit() pub fn initTakeOwnership(allocator: Allocator, cmd_line_utf8: []const u8) InitError!Self { var buffer = try allocator.alloc(u8, cmd_line_utf8.len + 1); errdefer allocator.free(buffer); return Self{ .allocator = allocator, .cmd_line = cmd_line_utf8, .free_cmd_line_on_deinit = true, .buffer = buffer, }; } /// cmd_line_utf16le MUST be encoded UTF16-LE, and is converted to UTF-8 in an internal buffer pub fn initUtf16le(allocator: Allocator, cmd_line_utf16le: [*:0]const u16) InitUtf16leError!Self { var utf16le_slice = mem.sliceTo(cmd_line_utf16le, 0); var cmd_line = std.unicode.utf16leToUtf8Alloc(allocator, utf16le_slice) catch |err| switch (err) { error.ExpectedSecondSurrogateHalf, error.DanglingSurrogateHalf, error.UnexpectedSecondSurrogateHalf, => return error.InvalidCmdLine, error.OutOfMemory => return error.OutOfMemory, }; errdefer allocator.free(cmd_line); var buffer = try allocator.alloc(u8, cmd_line.len + 1); errdefer allocator.free(buffer); return Self{ .allocator = allocator, .cmd_line = cmd_line, .free_cmd_line_on_deinit = true, .buffer = buffer, }; } // Skips over whitespace in the cmd_line. // Returns false if the terminating sentinel is reached, true otherwise. // Also skips over comments (if supported). fn skipWhitespace(self: *Self) bool { while (true) : (self.index += 1) { const character = if (self.index != self.cmd_line.len) self.cmd_line[self.index] else 0; switch (character) { 0 => return false, ' ', '\t', '\r', '\n' => continue, '#' => { if (options.comments) { while (true) : (self.index += 1) { switch (self.cmd_line[self.index]) { '\n' => break, 0 => return false, else => continue, } } continue; } else { break; } }, else => break, } } return true; } pub fn skip(self: *Self) bool { if (!self.skipWhitespace()) { return false; } var backslash_count: usize = 0; var in_quote = false; while (true) : (self.index += 1) { const character = if (self.index != self.cmd_line.len) self.cmd_line[self.index] else 0; switch (character) { 0 => return true, '"', '\'' => { if (!options.single_quotes and character == '\'') { backslash_count = 0; continue; } const quote_is_real = backslash_count % 2 == 0; if (quote_is_real) { in_quote = !in_quote; } }, '\\' => { backslash_count += 1; }, ' ', '\t', '\r', '\n' => { if (!in_quote) { return true; } backslash_count = 0; }, else => { backslash_count = 0; continue; }, } } } /// Returns a slice of the internal buffer that contains the next argument. /// Returns null when it reaches the end. pub fn next(self: *Self) ?[:0]const u8 { if (!self.skipWhitespace()) { return null; } var backslash_count: usize = 0; var in_quote = false; while (true) : (self.index += 1) { const character = if (self.index != self.cmd_line.len) self.cmd_line[self.index] else 0; switch (character) { 0 => { self.emitBackslashes(backslash_count); self.buffer[self.end] = 0; var token = self.buffer[self.start..self.end :0]; self.end += 1; self.start = self.end; return token; }, '"', '\'' => { if (!options.single_quotes and character == '\'') { self.emitBackslashes(backslash_count); backslash_count = 0; self.emitCharacter(character); continue; } const quote_is_real = backslash_count % 2 == 0; self.emitBackslashes(backslash_count / 2); backslash_count = 0; if (quote_is_real) { in_quote = !in_quote; } else { self.emitCharacter('"'); } }, '\\' => { backslash_count += 1; }, ' ', '\t', '\r', '\n' => { self.emitBackslashes(backslash_count); backslash_count = 0; if (in_quote) { self.emitCharacter(character); } else { self.buffer[self.end] = 0; var token = self.buffer[self.start..self.end :0]; self.end += 1; self.start = self.end; return token; } }, else => { self.emitBackslashes(backslash_count); backslash_count = 0; self.emitCharacter(character); }, } } } fn emitBackslashes(self: *Self, emit_count: usize) void { var i: usize = 0; while (i < emit_count) : (i += 1) { self.emitCharacter('\\'); } } fn emitCharacter(self: *Self, char: u8) void { self.buffer[self.end] = char; self.end += 1; } /// Call to free the internal buffer of the iterator. pub fn deinit(self: *Self) void { self.allocator.free(self.buffer); if (self.free_cmd_line_on_deinit) { self.allocator.free(self.cmd_line); } } }; } /// Cross-platform command line argument iterator. pub const ArgIterator = struct { const InnerType = switch (builtin.os.tag) { .windows => ArgIteratorGeneral(.{}), .wasi => if (builtin.link_libc) ArgIteratorPosix else ArgIteratorWasi, else => ArgIteratorPosix, }; inner: InnerType, /// Initialize the args iterator. Consider using initWithAllocator() instead /// for cross-platform compatibility. pub fn init() ArgIterator { if (builtin.os.tag == .wasi) { @compileError("In WASI, use initWithAllocator instead."); } if (builtin.os.tag == .windows) { @compileError("In Windows, use initWithAllocator instead."); } return ArgIterator{ .inner = InnerType.init() }; } pub const InitError = switch (builtin.os.tag) { .windows => InnerType.InitUtf16leError, else => InnerType.InitError, }; /// You must deinitialize iterator's internal buffers by calling `deinit` when done. pub fn initWithAllocator(allocator: mem.Allocator) InitError!ArgIterator { if (builtin.os.tag == .wasi and !builtin.link_libc) { return ArgIterator{ .inner = try InnerType.init(allocator) }; } if (builtin.os.tag == .windows) { const cmd_line_w = os.windows.kernel32.GetCommandLineW(); return ArgIterator{ .inner = try InnerType.initUtf16le(allocator, cmd_line_w) }; } return ArgIterator{ .inner = InnerType.init() }; } /// Get the next argument. Returns 'null' if we are at the end. /// Returned slice is pointing to the iterator's internal buffer. pub fn next(self: *ArgIterator) ?([:0]const u8) { return self.inner.next(); } /// Parse past 1 argument without capturing it. /// Returns `true` if skipped an arg, `false` if we are at the end. pub fn skip(self: *ArgIterator) bool { return self.inner.skip(); } /// Call this to free the iterator's internal buffer if the iterator /// was created with `initWithAllocator` function. pub fn deinit(self: *ArgIterator) void { // Unless we're targeting WASI or Windows, this is a no-op. if (builtin.os.tag == .wasi and !builtin.link_libc) { self.inner.deinit(); } if (builtin.os.tag == .windows) { self.inner.deinit(); } } }; /// Use argsWithAllocator() for cross-platform code pub fn args() ArgIterator { return ArgIterator.init(); } /// You must deinitialize iterator's internal buffers by calling `deinit` when done. pub fn argsWithAllocator(allocator: mem.Allocator) ArgIterator.InitError!ArgIterator { return ArgIterator.initWithAllocator(allocator); } test "args iterator" { var ga = std.testing.allocator; var it = try argsWithAllocator(ga); defer it.deinit(); // no-op unless WASI or Windows const prog_name = it.next() orelse unreachable; const expected_suffix = switch (builtin.os.tag) { .wasi => "test.wasm", .windows => "test.exe", else => "test", }; const given_suffix = std.fs.path.basename(prog_name); try testing.expect(mem.eql(u8, expected_suffix, given_suffix)); try testing.expect(it.skip()); // Skip over zig_exe_path, passed to the test runner try testing.expect(it.next() == null); try testing.expect(!it.skip()); } /// Caller must call argsFree on result. pub fn argsAlloc(allocator: mem.Allocator) ![][:0]u8 { // TODO refactor to only make 1 allocation. var it = try argsWithAllocator(allocator); defer it.deinit(); var contents = std.ArrayList(u8).init(allocator); defer contents.deinit(); var slice_list = std.ArrayList(usize).init(allocator); defer slice_list.deinit(); while (it.next()) |arg| { try contents.appendSlice(arg[0 .. arg.len + 1]); try slice_list.append(arg.len); } const contents_slice = contents.items; const slice_sizes = slice_list.items; const slice_list_bytes = try math.mul(usize, @sizeOf([]u8), slice_sizes.len); const total_bytes = try math.add(usize, slice_list_bytes, contents_slice.len); const buf = try allocator.alignedAlloc(u8, @alignOf([]u8), total_bytes); errdefer allocator.free(buf); const result_slice_list = mem.bytesAsSlice([:0]u8, buf[0..slice_list_bytes]); const result_contents = buf[slice_list_bytes..]; mem.copy(u8, result_contents, contents_slice); var contents_index: usize = 0; for (slice_sizes) |len, i| { const new_index = contents_index + len; result_slice_list[i] = result_contents[contents_index..new_index :0]; contents_index = new_index + 1; } return result_slice_list; } pub fn argsFree(allocator: mem.Allocator, args_alloc: []const [:0]u8) void { var total_bytes: usize = 0; for (args_alloc) |arg| { total_bytes += @sizeOf([]u8) + arg.len + 1; } const unaligned_allocated_buf = @ptrCast([*]const u8, args_alloc.ptr)[0..total_bytes]; const aligned_allocated_buf = @alignCast(@alignOf([]u8), unaligned_allocated_buf); return allocator.free(aligned_allocated_buf); } test "general arg parsing" { try testGeneralCmdLine("a b\tc d", &.{ "a", "b", "c", "d" }); try testGeneralCmdLine("\"abc\" d e", &.{ "abc", "d", "e" }); try testGeneralCmdLine("a\\\\\\b d\"e f\"g h", &.{ "a\\\\\\b", "de fg", "h" }); try testGeneralCmdLine("a\\\\\\\"b c d", &.{ "a\\\"b", "c", "d" }); try testGeneralCmdLine("a\\\\\\\\\"b c\" d e", &.{ "a\\\\b c", "d", "e" }); try testGeneralCmdLine("a b\tc \"d f", &.{ "a", "b", "c", "d f" }); try testGeneralCmdLine("j k l\\", &.{ "j", "k", "l\\" }); try testGeneralCmdLine("\"\" x y z\\\\", &.{ "", "x", "y", "z\\\\" }); try testGeneralCmdLine("\".\\..\\zig-cache\\build\" \"bin\\zig.exe\" \".\\..\" \".\\..\\zig-cache\" \"--help\"", &.{ ".\\..\\zig-cache\\build", "bin\\zig.exe", ".\\..", ".\\..\\zig-cache", "--help", }); try testGeneralCmdLine( \\ 'foo' "bar" , &.{ "'foo'", "bar" }); } fn testGeneralCmdLine(input_cmd_line: []const u8, expected_args: []const []const u8) !void { var it = try ArgIteratorGeneral(.{}).init(std.testing.allocator, input_cmd_line); defer it.deinit(); for (expected_args) |expected_arg| { const arg = it.next().?; try testing.expectEqualStrings(expected_arg, arg); } try testing.expect(it.next() == null); } test "response file arg parsing" { try testResponseFileCmdLine( \\a b \\c d\ , &.{ "a", "b", "c", "d\\" }); try testResponseFileCmdLine("a b c d\\", &.{ "a", "b", "c", "d\\" }); try testResponseFileCmdLine( \\j \\ k l # this is a comment \\ \\\ \\\\ "none" "\\" "\\\" \\ "m" #another comment \\ , &.{ "j", "k", "l", "m" }); try testResponseFileCmdLine( \\ "" q "" \\ "r s # t" "u\" v" #another comment \\ , &.{ "", "q", "", "r s # t", "u\" v" }); try testResponseFileCmdLine( \\ -l"advapi32" a# b#c d# \\e\\\ , &.{ "-ladvapi32", "a#", "b#c", "d#", "e\\\\\\" }); try testResponseFileCmdLine( \\ 'foo' "bar" , &.{ "foo", "bar" }); } fn testResponseFileCmdLine(input_cmd_line: []const u8, expected_args: []const []const u8) !void { var it = try ArgIteratorGeneral(.{ .comments = true, .single_quotes = true }) .init(std.testing.allocator, input_cmd_line); defer it.deinit(); for (expected_args) |expected_arg| { const arg = it.next().?; try testing.expectEqualStrings(expected_arg, arg); } try testing.expect(it.next() == null); } pub const UserInfo = struct { uid: os.uid_t, gid: os.gid_t, }; /// POSIX function which gets a uid from username. pub fn getUserInfo(name: []const u8) !UserInfo { return switch (builtin.os.tag) { .linux, .macos, .watchos, .tvos, .ios, .freebsd, .netbsd, .openbsd, .haiku, .solaris => posixGetUserInfo(name), else => @compileError("Unsupported OS"), }; } /// TODO this reads /etc/passwd. But sometimes the user/id mapping is in something else /// like NIS, AD, etc. See `man nss` or look at an strace for `id myuser`. pub fn posixGetUserInfo(name: []const u8) !UserInfo { const file = try std.fs.openFileAbsolute("/etc/passwd", .{}); defer file.close(); const reader = file.reader(); const State = enum { Start, WaitForNextLine, SkipPassword, ReadUserId, ReadGroupId, }; var buf: [std.mem.page_size]u8 = undefined; var name_index: usize = 0; var state = State.Start; var uid: os.uid_t = 0; var gid: os.gid_t = 0; while (true) { const amt_read = try reader.read(buf[0..]); for (buf[0..amt_read]) |byte| { switch (state) { .Start => switch (byte) { ':' => { state = if (name_index == name.len) State.SkipPassword else State.WaitForNextLine; }, '\n' => return error.CorruptPasswordFile, else => { if (name_index == name.len or name[name_index] != byte) { state = .WaitForNextLine; } name_index += 1; }, }, .WaitForNextLine => switch (byte) { '\n' => { name_index = 0; state = .Start; }, else => continue, }, .SkipPassword => switch (byte) { '\n' => return error.CorruptPasswordFile, ':' => { state = .ReadUserId; }, else => continue, }, .ReadUserId => switch (byte) { ':' => { state = .ReadGroupId; }, '\n' => return error.CorruptPasswordFile, else => { const digit = switch (byte) { '0'...'9' => byte - '0', else => return error.CorruptPasswordFile, }; if (@mulWithOverflow(u32, uid, 10, &uid)) return error.CorruptPasswordFile; if (@addWithOverflow(u32, uid, digit, &uid)) return error.CorruptPasswordFile; }, }, .ReadGroupId => switch (byte) { '\n', ':' => { return UserInfo{ .uid = uid, .gid = gid, }; }, else => { const digit = switch (byte) { '0'...'9' => byte - '0', else => return error.CorruptPasswordFile, }; if (@mulWithOverflow(u32, gid, 10, &gid)) return error.CorruptPasswordFile; if (@addWithOverflow(u32, gid, digit, &gid)) return error.CorruptPasswordFile; }, }, } } if (amt_read < buf.len) return error.UserNotFound; } } pub fn getBaseAddress() usize { switch (builtin.os.tag) { .linux => { const base = os.system.getauxval(std.elf.AT_BASE); if (base != 0) { return base; } const phdr = os.system.getauxval(std.elf.AT_PHDR); return phdr - @sizeOf(std.elf.Ehdr); }, .macos, .freebsd, .netbsd => { return @ptrToInt(&std.c._mh_execute_header); }, .windows => return @ptrToInt(os.windows.kernel32.GetModuleHandleW(null)), else => @compileError("Unsupported OS"), } } /// Caller owns the result value and each inner slice. /// TODO Remove the `Allocator` requirement from this API, which will remove the `Allocator` /// requirement from `std.zig.system.NativeTargetInfo.detect`. Most likely this will require /// introducing a new, lower-level function which takes a callback function, and then this /// function which takes an allocator can exist on top of it. pub fn getSelfExeSharedLibPaths(allocator: Allocator) error{OutOfMemory}![][:0]u8 { switch (builtin.link_mode) { .Static => return &[_][:0]u8{}, .Dynamic => {}, } const List = std.ArrayList([:0]u8); switch (builtin.os.tag) { .linux, .freebsd, .netbsd, .dragonfly, .openbsd, .solaris, => { var paths = List.init(allocator); errdefer { const slice = paths.toOwnedSlice(); for (slice) |item| { allocator.free(item); } allocator.free(slice); } try os.dl_iterate_phdr(&paths, error{OutOfMemory}, struct { fn callback(info: *os.dl_phdr_info, size: usize, list: *List) !void { _ = size; const name = info.dlpi_name orelse return; if (name[0] == '/') { const item = try list.allocator.dupeZ(u8, mem.sliceTo(name, 0)); errdefer list.allocator.free(item); try list.append(item); } } }.callback); return paths.toOwnedSlice(); }, .macos, .ios, .watchos, .tvos => { var paths = List.init(allocator); errdefer { const slice = paths.toOwnedSlice(); for (slice) |item| { allocator.free(item); } allocator.free(slice); } const img_count = std.c._dyld_image_count(); var i: u32 = 0; while (i < img_count) : (i += 1) { const name = std.c._dyld_get_image_name(i); const item = try allocator.dupeZ(u8, mem.sliceTo(name, 0)); errdefer allocator.free(item); try paths.append(item); } return paths.toOwnedSlice(); }, // revisit if Haiku implements dl_iterat_phdr (https://dev.haiku-os.org/ticket/15743) .haiku => { var paths = List.init(allocator); errdefer { const slice = paths.toOwnedSlice(); for (slice) |item| { allocator.free(item); } allocator.free(slice); } var b = "/boot/system/runtime_loader"; const item = try allocator.dupeZ(u8, mem.sliceTo(b, 0)); errdefer allocator.free(item); try paths.append(item); return paths.toOwnedSlice(); }, else => @compileError("getSelfExeSharedLibPaths unimplemented for this target"), } } /// Tells whether calling the `execv` or `execve` functions will be a compile error. pub const can_execv = switch (builtin.os.tag) { .windows, .haiku, .wasi => false, else => true, }; /// Tells whether spawning child processes is supported (e.g. via ChildProcess) pub const can_spawn = switch (builtin.os.tag) { .wasi => false, else => true, }; pub const ExecvError = std.os.ExecveError || error{OutOfMemory}; /// Replaces the current process image with the executed process. /// This function must allocate memory to add a null terminating bytes on path and each arg. /// It must also convert to KEY=VALUE\0 format for environment variables, and include null /// pointers after the args and after the environment variables. /// `argv[0]` is the executable path. /// This function also uses the PATH environment variable to get the full path to the executable. /// Due to the heap-allocation, it is illegal to call this function in a fork() child. /// For that use case, use the `std.os` functions directly. pub fn execv(allocator: mem.Allocator, argv: []const []const u8) ExecvError { return execve(allocator, argv, null); } /// Replaces the current process image with the executed process. /// This function must allocate memory to add a null terminating bytes on path and each arg. /// It must also convert to KEY=VALUE\0 format for environment variables, and include null /// pointers after the args and after the environment variables. /// `argv[0]` is the executable path. /// This function also uses the PATH environment variable to get the full path to the executable. /// Due to the heap-allocation, it is illegal to call this function in a fork() child. /// For that use case, use the `std.os` functions directly. pub fn execve( allocator: mem.Allocator, argv: []const []const u8, env_map: ?*const EnvMap, ) ExecvError { if (!can_execv) @compileError("The target OS does not support execv"); var arena_allocator = std.heap.ArenaAllocator.init(allocator); defer arena_allocator.deinit(); const arena = arena_allocator.allocator(); const argv_buf = try arena.allocSentinel(?[*:0]u8, argv.len, null); for (argv) |arg, i| argv_buf[i] = (try arena.dupeZ(u8, arg)).ptr; const envp = m: { if (env_map) |m| { const envp_buf = try child_process.createNullDelimitedEnvMap(arena, m); break :m envp_buf.ptr; } else if (builtin.link_libc) { break :m std.c.environ; } else if (builtin.output_mode == .Exe) { // Then we have Zig start code and this works. // TODO type-safety for null-termination of `os.environ`. break :m @ptrCast([*:null]?[*:0]u8, os.environ.ptr); } else { // TODO come up with a solution for this. @compileError("missing std lib enhancement: std.process.execv implementation has no way to collect the environment variables to forward to the child process"); } }; return os.execvpeZ_expandArg0(.no_expand, argv_buf.ptr[0].?, argv_buf.ptr, envp); }
lib/std/process.zig
const cam = @import("kira/math/camera.zig"); const mat4x4 = @import("kira/math/mat4x4.zig"); const math = @import("kira/math/common.zig"); const vec2 = @import("kira/math/vec2.zig"); const vec3 = @import("kira/math/vec3.zig"); const glfw = @import("kira/glfw.zig"); const renderer = @import("kira/renderer.zig"); const input = @import("kira/input.zig"); const window = @import("kira/window.zig"); const gl = @import("kira/gl.zig"); const c = @import("kira/c.zig"); const utils = @import("kira/utils.zig"); pub const Mat4x4f = mat4x4.Generic(f32); pub const Vec2f = vec2.Generic(f32); pub const Vec3f = vec3.Generic(f32); pub const Window = window.Info; pub const Input = input.Info; pub const Camera2D = cam.Camera2D; pub const Colour = renderer.ColourGeneric(f32); pub const UColour = renderer.ColourGeneric(u8); /// Private Error set const pError = error{ /// Engine is not initialized, initialize it before using the engine EngineIsNotInitialized, /// Engine is initialized, cannot initialize it again EngineIsInitialized, /// Current batch cannot able to do thing you are just about to do InvalidBatch, /// Failes to load texture FailedToLoadTexture, /// Current batch has filled, cannot able to draw anymore FailedToDraw, /// Texture is not available or corrupted InvalidTexture, /// Custom batch already enabled UnableToEnableCustomBatch, // Merge input errors /// Binding is not available InvalidBinding, /// Binding list has filled, cannot able to bind anymore NoEmptyBinding, // Merge kira errors /// Check has failed(expression was true) CheckFailed, // Merge glfw errors /// GLFW failed to initialize, check logs! GLFWFailedToInitialize, // Merge renderer errors /// OpenGL failes to generate vbo, vao, ebo FailedToGenerateBuffers, /// Object list has been reached it's limits /// and you are trying to write into it ObjectOverflow, /// Vertex list has been reached it's limits /// and you are trying to write into it VertexOverflow, /// Index list has been reached it's limits /// and you are trying to write into it IndexOverflow, /// Submit fn is not initialized /// and you are trying to execute it UnknownSubmitFn, //From utils.Error /// 'thing' already exists in the other 'thing' /// Cannot add one more time Duplicate, /// Unknown 'thing', corrupted or invalid Unknown, /// Failed to add 'thing' FailedToAdd, }; /// Error set pub const Error = pError || input.Error || utils.Error || glfw.Error || renderer.Error; /// Helper type for using MVP's pub const ModelMatrix = struct { model: Mat4x4f = Mat4x4f.identity(), trans: Mat4x4f = Mat4x4f.identity(), rot: Mat4x4f = Mat4x4f.identity(), sc: Mat4x4f = Mat4x4f.identity(), /// Apply the changes were made pub fn update(self: *ModelMatrix) void { self.model = Mat4x4f.mul(self.sc, Mat4x4f.mul(self.trans, self.rot)); } /// Translate the matrix pub fn translate(self: *ModelMatrix, x: f32, y: f32, z: f32) void { self.trans = Mat4x4f.translate(x, y, z); self.update(); } /// Rotate the matrix pub fn rotate(self: *ModelMatrix, x: f32, y: f32, z: f32, angle: f32) void { self.rot = Mat4x4f.rotate(x, y, z, angle); self.update(); } /// Scale the matrix pub fn scale(self: *ModelMatrix, x: f32, y: f32, z: f32) void { self.sc = Mat4x4f.scale(x, y, z); self.update(); } }; pub const Rectangle = struct { x: f32 = 0, y: f32 = 0, width: f32 = 0, height: f32 = 0, /// Get the originated position of the rectangle pub fn getOriginated(self: Rectangle) Vec2f { return .{ .x = self.x + (self.width * 0.5), .y = self.y + (self.height * 0.5), }; } /// Get origin of the rectangle pub fn getOrigin(self: Rectangle) Vec2f { return .{ .x = self.width * 0.5, .y = self.height * 0.5, }; } }; pub const Texture = struct { id: u32 = 0, width: i32 = 0, height: i32 = 0, fn loadSetup(self: *Texture) void { gl.texturesGen(1, @ptrCast([*]u32, &self.id)); gl.textureBind(gl.TextureType.t2D, self.id); gl.textureTexParameteri(gl.TextureType.t2D, gl.TextureParamaterType.min_filter, gl.TextureParamater.filter_nearest); gl.textureTexParameteri(gl.TextureType.t2D, gl.TextureParamaterType.mag_filter, gl.TextureParamater.filter_nearest); gl.textureTexParameteri(gl.TextureType.t2D, gl.TextureParamaterType.wrap_s, gl.TextureParamater.wrap_repeat); gl.textureTexParameteri(gl.TextureType.t2D, gl.TextureParamaterType.wrap_t, gl.TextureParamater.wrap_repeat); } /// Creates a texture from png file pub fn createFromPNG(path: []const u8) Error!Texture { var result = Texture{}; result.loadSetup(); defer gl.textureBind(gl.TextureType.t2D, 0); var nrchannels: i32 = 0; c.stbi_set_flip_vertically_on_load(0); var data: ?*u8 = c.stbi_load(@ptrCast([*c]const u8, path), &result.width, &result.height, &nrchannels, 4); defer c.stbi_image_free(data); if (data == null) { gl.texturesDelete(1, @ptrCast([*]u32, &result.id)); return Error.FailedToLoadTexture; } gl.textureTexImage2D(gl.TextureType.t2D, 0, gl.TextureFormat.rgba8, result.width, result.height, 0, gl.TextureFormat.rgba, u8, data); return result; } /// Creates a texture from png memory pub fn createFromPNGMemory(mem: []const u8) Error!Texture { var result = Texture{}; result.loadSetup(); defer gl.textureBind(gl.TextureType.t2D, 0); var nrchannels: i32 = 0; c.stbi_set_flip_vertically_on_load(0); var data: ?*u8 = c.stbi_load_from_memory(@ptrCast([*c]const u8, mem), @intCast(i32, mem.len), &result.width, &result.height, &nrchannels, 4); defer c.stbi_image_free(data); if (data == null) { gl.texturesDelete(1, @ptrCast([*]u32, &result.id)); return Error.FailedToLoadTexture; } gl.textureTexImage2D(gl.TextureType.t2D, 0, gl.TextureFormat.rgba8, result.width, result.height, 0, gl.TextureFormat.rgba, u8, data); return result; } /// Creates a texture from given colour pub fn createFromColour(colour: [*]UColour, w: i32, h: i32) Texture { var result = Texture{ .width = w, .height = h }; result.loadSetup(); defer gl.textureBind(gl.TextureType.t2D, 0); gl.textureTexImage2D(gl.TextureType.t2D, 0, gl.TextureFormat.rgba8, result.width, result.height, 0, gl.TextureFormat.rgba, u8, @ptrCast(?*c_void, colour)); return result; } /// Destroys the texture pub fn destroy(self: *Texture) void { gl.texturesDelete(1, @ptrCast([*]const u32, &self.id)); self.id = 0; } }; /// Flipbook pub const FlipBook = struct { pub const Properties = struct { frame_size: Vec2f = .{}, max_frame_size: Vec2f = .{}, frame_increase_size: Vec2f = .{}, fps: u32 = 0, current_frame: u32 = 0, is_infinite: bool = true, is_finished: bool = false, play: bool = true, }; properties: Properties = Properties{}, srcrect: *Rectangle = undefined, timer: f32 = 0, /// Creates animated texture pub fn create(self: *FlipBook) void { self.timer = 1.0 / @intToFloat(f32, self.properties.fps); } /// Update animation pub fn update(self: *FlipBook, dt: f32) void { if (!self.properties.play) return; if (self.timer > 0.0) { self.timer -= 1 * dt; return; } self.timer = 1.0 / @intToFloat(f32, self.properties.fps); self.properties.current_frame += 1; if (self.srcrect.x < self.properties.max_frame_size.x) { self.srcrect.x += self.properties.frame_increase_size.x; } else { self.srcrect.x = self.properties.frame_size.x; if (self.srcrect.y < self.properties.max_frame_size.y) { self.srcrect.y += self.properties.frame_increase_size.y; } else { self.srcrect.y = self.properties.frame_size.y; self.properties.current_frame = 0; if (!self.properties.is_infinite) self.properties.play = false; } } } /// Plays animation where it is stopped pub fn play(self: *FlipBook) void { self.properties.play = true; } /// Pauses the animation && resets it pub fn pause(self: *FlipBook) void { self.properties.current_frame = 0; self.properties.play = false; self.srcrect.x = 0; self.srcrect.y = 0; self.timer = 1.0 / @intToFloat(f32, self.properties.fps); } /// Stops the animation pub fn stop(self: *FlipBook) void { self.properties.play = false; } /// Resets the animation pub fn reset(self: *FlipBook) void { self.properties.current_frame = 0; self.srcrect.x = 0; self.srcrect.y = 0; self.timer = 1.0 / @intToFloat(f32, self.properties.fps); } };
src/kiragine/sharedtypes.zig
const std = @import("std"); const utils = @import("../utils.zig"); const Atomic = std.atomic.Atomic; const Futex = utils.Futex; pub const Lock = extern struct { pub const name = "parking_lot"; const UNLOCKED = 0; const LOCKED = 1; const PARKED = 2; state: Atomic(u8) = Atomic(u8).init(UNLOCKED), pl_lock: @import("word_lock.zig").Lock = .{}, pl_queue: ?*Waiter = null, const Waiter = struct { next: ?*Waiter, tail: *Waiter, futex: Atomic(u32), }; pub fn init(self: *Lock) void { self.* = .{}; } pub fn deinit(self: *Lock) void { self.* = undefined; } pub fn acquire(self: *Lock) void { if (self.state.tryCompareAndSwap(UNLOCKED, LOCKED, .Acquire, .Monotonic) == null) return; self.acquireSlow(); } fn acquireSlow(self: *Lock) void { @setCold(true); var spin = utils.SpinWait{}; var state = self.state.load(.Monotonic); while (true) { if (state & LOCKED == 0) { state = self.state.tryCompareAndSwap(state, state | LOCKED, .Acquire, .Monotonic) orelse return; continue; } if (state & PARKED == 0) blk: { if (spin.yield()) { state = self.state.load(.Monotonic); continue; } state = self.state.tryCompareAndSwap(state, state | PARKED, .Monotonic, .Monotonic) orelse break :blk; continue; } wait: { self.pl_lock.acquire(); state = self.state.load(.Monotonic); if (state != (LOCKED | PARKED)) { self.pl_lock.release(); break :wait; } var waiter: Waiter = undefined; waiter.next = null; waiter.tail = &waiter; waiter.futex = Atomic(u32).init(0); if (self.pl_queue) |head| { head.tail.next = &waiter; head.tail = &waiter; } else { self.pl_queue = &waiter; } self.pl_lock.release(); while (waiter.futex.load(.Acquire) == 0) { Futex.wait(&waiter.futex, 0, null) catch unreachable; } } spin.reset(); state = self.state.load(.Monotonic); } } pub fn release(self: *Lock) void { if (self.state.compareAndSwap(LOCKED, UNLOCKED, .Release, .Monotonic) == null) return; self.releaseSlow(); } fn releaseSlow(self: *Lock) void { @setCold(true); self.pl_lock.acquire(); const waiter = self.pl_queue; if (waiter) |w| { self.pl_queue = w.next; if (self.pl_queue) |head| { head.tail = w.tail; } } const new_state = if (waiter == null) @as(u8, UNLOCKED) else PARKED; self.state.store(new_state, .Release); self.pl_lock.release(); if (waiter) |w| { w.futex.store(1, .Release); Futex.wake(&w.futex, 1); } } };
locks/parking_lot.zig
const std = @import("std"); const root = @import("main.zig"); const hzzp = root.hzzp; const libressl = root.libressl; pub const Method = enum { GET, POST, PUT, DELETE, HEAD, OPTIONS, CONNECT, PATCH, TRACE }; // TODO(haze): MultipartForm, pub const BodyKind = enum { JSON, Raw, URLEncodedForm }; const StringList = std.ArrayList([]const u8); pub const HeaderValue = struct { parts: StringList, /// Owner is responsible for the returned memory /// /// Transforms /// Cache-Control: no-cache /// Cache-Control: no-store /// Into /// Cache-Control: no-cache, no-store pub fn value(self: HeaderValue, allocator: std.mem.Allocator) std.mem.Allocator.Error![]u8 { // first, find out how much we need to allocate // 2 = ", " var bytesNeeded = 2 * (self.parts.items.len - 1); for (self.parts.items) |part| bytesNeeded += part.len; var buffer = try allocator.alloc(u8, bytesNeeded); var writer = std.io.fixedBufferStream(buffer).writer(); for (self.parts.items) |part, idx| { writer.writeAll(part) catch unreachable; if (idx != self.parts.items.len - 1) writer.writeAll(", ") catch unreachable; } return buffer; } pub fn init(allocator: std.mem.Allocator) HeaderValue { return .{ .parts = StringList.init(allocator), }; } pub fn deinit(self: *HeaderValue) void { self.parts.deinit(); self.* = undefined; } }; pub const HeaderMap = std.StringArrayHashMap(HeaderValue); pub const Body = struct { kind: BodyKind, bytes: []const u8, }; pub const Request = struct { const Self = @This(); pub const Error = error{MissingScheme}; method: Method, url: []const u8, headers: ?HeaderMap = null, body: ?Body = null, use_global_connection_pool: bool, tls_configuration: ?libressl.TlsConfiguration = null, }; pub const Response = struct { const Self = @This(); headers: HeaderMap, body: ?[]u8 = null, allocator: std.mem.Allocator, statusCode: hzzp.StatusCode, pub fn init(allocator: std.mem.Allocator, statusCode: hzzp.StatusCode) Self { return .{ .headers = HeaderMap.init(allocator), .allocator = allocator, .statusCode = statusCode, }; } pub fn deinit(self: *Self) void { var headerIter = self.headers.iterator(); while (headerIter.next()) |kv| { self.allocator.free(kv.key_ptr.*); for (kv.value_ptr.parts.items) |item| { self.allocator.free(item); } kv.value_ptr.parts.deinit(); } self.headers.deinit(); if (self.body) |body| self.allocator.free(body); self.* = undefined; } };
src/request.zig
const std = @import("std"); const zalgebra = @import("zalgebra"); const objects = @import("didot-objects"); const c = @cImport({ @cDefine("dSINGLE", "1"); @cInclude("ode/ode.h"); }); const Allocator = std.mem.Allocator; const Component = objects.Component; const GameObject = objects.GameObject; const Transform = objects.Transform; const Vec3 = zalgebra.Vec3; var isOdeInit: bool = false; const logger = std.log.scoped(.didot); var odeThread: ?std.Thread.Id = null; fn ensureInit() void { if (!isOdeInit) { _ = c.dInitODE2(0); const conf = @ptrCast([*:0]const u8, c.dGetConfiguration()); logger.debug("Initialized ODE.", .{}); logger.debug("ODE configuration: {s}", .{conf}); isOdeInit = true; } } /// A physical world in which the physics simulation happen. pub const World = struct { /// Internal value (ODE dWorldID) id: c.dWorldID, /// Internal value (ODE dSpaceID) space: c.dSpaceID, /// Internal value (ODE dJointGroupID) /// Used internally as a group for contact joints. contactGroup: c.dJointGroupID, /// The time, in milliseconds, when the last step was executed lastStep: i64, /// The lag-behind of the physics simulation measured in seconds. /// The maximum value is set to 0.1 seconds. accumulatedStep: f64 = 0.0, pub fn create() World { ensureInit(); return World { .id = c.dWorldCreate(), .space = c.dHashSpaceCreate(null), .contactGroup = c.dJointGroupCreate(0), .lastStep = std.time.milliTimestamp() }; } export fn nearCallback(data: ?*c_void, o1: c.dGeomID, o2: c.dGeomID) void { const b1 = c.dGeomGetBody(o1); const b2 = c.dGeomGetBody(o2); const self = @ptrCast(*World, @alignCast(@alignOf(World), data.?)); const b1data = @ptrCast(*Rigidbody, @alignCast(@alignOf(Rigidbody), c.dBodyGetData(b1).?)); const b2data = @ptrCast(*Rigidbody, @alignCast(@alignOf(Rigidbody), c.dBodyGetData(b2).?)); const bounce: f32 = std.math.max(b1data.material.bounciness, b2data.material.bounciness); var contact: c.dContact = undefined; contact.surface.mode = c.dContactBounce | c.dContactMu2; contact.surface.mu = b1data.material.friction; contact.surface.mu2 = b2data.material.friction; contact.surface.rho = b1data.material.friction/10; contact.surface.rho2 = b2data.material.friction/10; contact.surface.bounce = bounce; contact.surface.bounce_vel = 1; contact.surface.soft_cfm = 0.1; const numc = c.dCollide(o1, o2, 1, &contact.geom, @sizeOf(c.dContact)); if (numc != 0) { const joint = c.dJointCreateContact(self.id, self.contactGroup, &contact); c.dJointAttach(joint, b1, b2); } } pub fn setGravity(self: *World, gravity: Vec3) void { c.dWorldSetGravity(self.id, gravity.x, gravity.y, gravity.z); c.dWorldSetAutoDisableFlag(self.id, 1); c.dWorldSetAutoDisableLinearThreshold(self.id, 0.1); c.dWorldSetAutoDisableAngularThreshold(self.id, 0.1); //c.dWorldSetERP(self.id, 0.1); //c.dWorldSetCFM(self.id, 0.0000); } pub fn update(self: *World) void { self.accumulatedStep += @intToFloat(f64, std.time.milliTimestamp())/1000 - @intToFloat(f64, self.lastStep)/1000; if (self.accumulatedStep > 0.1) self.accumulatedStep = 0.1; const timeStep = 0.01; while (self.accumulatedStep > timeStep) { c.dSpaceCollide(self.space, self, nearCallback); _ = c.dWorldStep(self.id, timeStep); c.dJointGroupEmpty(self.contactGroup); self.accumulatedStep -= timeStep; } self.lastStep = std.time.milliTimestamp(); } pub fn deinit(self: *const World) void { c.dWorldDestroy(self.id); } }; pub const KinematicState = enum { Dynamic, Kinematic }; pub const PhysicsMaterial = struct { bounciness: f32 = 0.0, friction: f32 = 10.0 }; pub const SphereCollider = struct { radius: f32 = 0.5 }; pub const BoxCollider = struct { size: Vec3 = Vec3.new(1, 1, 1) }; pub const Collider = union(enum) { Box: BoxCollider, Sphere: SphereCollider }; /// Rigidbody component. /// Add it to a GameObject for it to have physics with other rigidbodies. pub const Rigidbody = struct { /// Set by the Rigidbody component allowing it to know when to initialize internal values. inited: bool = false, /// The pointer to the World **MUST** be set. world: *World, kinematic: KinematicState = .Dynamic, transform: *Transform = undefined, material: PhysicsMaterial = .{}, collider: Collider = .{ .Box = .{} }, /// Internal value (ODE dBodyID) _body: c.dBodyID = undefined, /// Internal value (ODE dGeomID) _geom: c.dGeomID = undefined, /// Internal value (ODE dMass) _mass: c.dMass = undefined, pub fn addForce(self: *Rigidbody, force: Vec3) void { c.dBodyEnable(self._body); c.dBodyAddForce(self._body, force.x, force.y, force.z); } pub fn setPosition(self: *Rigidbody, position: Vec3) void { c.dBodySetPosition(self._body, position.x, position.y, position.z); self.transform.position = position; } }; pub fn rigidbodySystem(query: objects.Query(.{*Rigidbody, *Transform})) !void { var iterator = query.iterator(); while (iterator.next()) |o| { const data = o.rigidbody; const transform = o.transform; if (!data.inited) { // TODO: move to a system that uses the Created() filter data._body = c.dBodyCreate(data.world.id); // const scale = transform.scale; // not used? data._geom = switch (data.collider) { .Box => |box| c.dCreateBox(data.world.space, box.size.x, box.size.y, box.size.z), .Sphere => |sphere| c.dCreateSphere(data.world.space, sphere.radius) }; data.transform = transform; c.dMassSetBox(&data._mass, 1.0, 1.0, 1.0, 1.0); c.dGeomSetBody(data._geom, data._body); data.setPosition(transform.position); c.dBodySetData(data._body, data); c.dBodySetMass(data._body, &data._mass); //c.dBodySetDamping(data._body, 0.005, 0.005); data.inited = true; } if (c.dBodyIsEnabled(data._body) != 0) { switch (data.kinematic) { .Dynamic => c.dBodySetDynamic(data._body), .Kinematic => c.dBodySetKinematic(data._body) } const scale = transform.scale; switch (data.collider) { .Box => |box| { c.dGeomBoxSetLengths(data._geom, box.size.x * scale.x, box.size.y * scale.y, box.size.z * scale.z); }, .Sphere => |sphere| { // TODO: handle that _ = sphere; } } const pos = c.dBodyGetPosition(data._body); const raw = c.dBodyGetQuaternion(data._body); transform.rotation = zalgebra.Quat.new(raw[0], raw[1], raw[2], raw[3]); transform.position = Vec3.new(pos[0], pos[1], pos[2]); } } } comptime { std.testing.refAllDecls(@This()); std.testing.refAllDecls(Rigidbody); std.testing.refAllDecls(World); }
didot-ode/physics.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; pub const AllowResize = union(enum) { /// The fields **dense_to_sparse** and **values** will grow on **add()** and **addValue()**. ResizeAllowed, /// Errors will be generated when adding more elements than **capacity_dense**. NoResize, }; pub const ValueLayout = union(enum) { /// AOS style. InternalArrayOfStructs, /// SOA style. ExternalStructOfArraysSupport, }; pub const ValueInitialization = union(enum) { /// New values added with add() will contain uninitialized/random memory. Untouched, /// New values added with add() will be memset to zero. ZeroInitialized, }; pub const SparseSetConfig = struct { /// The type used for the sparse handle. SparseT: type, /// The type used for dense indices. DenseT: type, /// Optional: The type used for values when using **InternalArrayOfStructs**. ValueT: type = void, /// If you only have a single array of structs - AOS - letting SparseSet handle it /// with **InternalArrayOfStructs** is convenient. If you want to manage the data /// yourself or if you're using SOA, use **ExternalStructOfArraysSupport**. value_layout: ValueLayout, /// Set to **ZeroInitialized** to make values created with add() be zero initialized. /// Only valid with **value_layout == .InternalArrayOfStructs**. /// Defaults to **Untouched**. value_init: ValueInitialization = .Untouched, /// Whether or not the amount of dense indices (and values) can grow. allow_resize: AllowResize = .NoResize, }; /// Creates a specific Sparse Set type based on the config. pub fn SparseSet(comptime config: SparseSetConfig) type { comptime const SparseT = config.SparseT; comptime const DenseT = config.DenseT; comptime const ValueT = config.ValueT; comptime const allow_resize = config.allow_resize; comptime const value_layout = config.value_layout; comptime const value_init = config.value_init; assert((value_layout == .ExternalStructOfArraysSupport) or (ValueT != @TypeOf(void))); return struct { const Self = @This(); /// Allocator used for allocating, growing and freeing **dense_to_sparse**, **sparse_to_dense**, and **values**. allocator: *Allocator, /// Mapping from dense indices to sparse handles. dense_to_sparse: []SparseT, /// Mapping from sparse handles to dense indices (and values). sparse_to_dense: []DenseT, /// Optional: A list of **ValueT** that is used with **InternalArrayOfStructs**. values: if (value_layout == .InternalArrayOfStructs) []ValueT else void, /// Current amount of used handles. dense_count: DenseT, /// Amount of dense indices that can be stored. capacity_dense: DenseT, /// Amount of sparse handles that can be used for lookups. capacity_sparse: SparseT, /// You can think of **capacity_sparse** as how many entities you want to support, and /// **capacity_dense** as how many components. pub fn init(allocator: *Allocator, capacity_sparse: SparseT, capacity_dense: DenseT) !Self { // Could be <= but I'm not sure why'd you use a sparse_set if you don't have more sparse // indices than dense... assert(capacity_dense < capacity_sparse); var dense_to_sparse = try allocator.alloc(SparseT, capacity_dense); errdefer allocator.free(dense_to_sparse); var sparse_to_dense = try allocator.alloc(DenseT, capacity_sparse); errdefer allocator.free(sparse_to_dense); var self: Self = undefined; if (value_layout == .InternalArrayOfStructs) { var values = try allocator.alloc(ValueT, capacity_dense); errdefer allocator.free(values); self = Self{ .allocator = allocator, .dense_to_sparse = dense_to_sparse, .sparse_to_dense = sparse_to_dense, .values = values, .capacity_dense = capacity_dense, .capacity_sparse = capacity_sparse, .dense_count = 0, }; } else { self = Self{ .allocator = allocator, .dense_to_sparse = dense_to_sparse, .sparse_to_dense = sparse_to_dense, .values = {}, .capacity_dense = capacity_dense, .capacity_sparse = capacity_sparse, .dense_count = 0, }; } // Ensure Valgrind doesn't complain about hasSparse _ = std.valgrind.memcheck.makeMemDefined(std.mem.asBytes(&self.sparse_to_dense)); return self; } /// Deallocates **dense_to_sparse**, **sparse_to_dense**, and optionally **values**. pub fn deinit(self: Self) void { self.allocator.free(self.dense_to_sparse); self.allocator.free(self.sparse_to_dense); if (value_layout == .InternalArrayOfStructs) { self.allocator.free(self.values); } } /// Resets the set cheaply. pub fn clear(self: *Self) void { self.dense_count = 0; } /// Returns the amount of allocated handles. pub fn len(self: Self) DenseT { return self.dense_count; } /// Returns a slice that can be used to loop over the sparse handles. pub fn toSparseSlice(self: Self) []SparseT { return self.dense_to_sparse[0..self.dense_count]; } // A bit of a hack to comptime add a function // TODO: Rewrite after https://github.com/ziglang/zig/issues/1717 pub usingnamespace switch (value_layout) { .InternalArrayOfStructs => struct { /// Returns a slice that can be used to loop over the values. pub fn toValueSlice(self: Self) []ValueT { return self.values[0..self.dense_count]; } }, else => struct {}, }; /// Returns how many dense indices are still available pub fn remainingCapacity(self: Self) DenseT { return self.capacity_dense - self.dense_count; } /// Registers the sparse value and matches it to a dense index. /// Grows .dense_to_sparse and .values if needed and resizing is allowed. /// Note: If resizing is allowed, you must use an allocator that you are sure /// will never fail for your use cases. /// If that is not an option, use addOrError. pub fn add(self: *Self, sparse: SparseT) DenseT { if (allow_resize == .ResizeAllowed) { if (self.dense_count == self.capacity_dense) { self.capacity_dense = self.capacity_dense * 2; self.dense_to_sparse = self.allocator.realloc(self.dense_to_sparse, self.capacity_dense) catch unreachable; if (value_layout == .InternalArrayOfStructs) { self.values = self.allocator.realloc(self.values, self.capacity_dense) catch unreachable; } } } assert(sparse < self.capacity_sparse); assert(self.dense_count < self.capacity_dense); assert(!self.hasSparse(sparse)); self.dense_to_sparse[self.dense_count] = sparse; self.sparse_to_dense[sparse] = self.dense_count; if (value_layout == .InternalArrayOfStructs and value_init == .ZeroInitialized) { self.values[self.dense_count] = mem.zeroes(ValueT); } self.dense_count += 1; return self.dense_count - 1; } /// May return error.OutOfBounds or error.AlreadyRegistered, otherwise calls add. /// Grows .dense_to_sparse and .values if needed and resizing is allowed. pub fn addOrError(self: *Self, sparse: SparseT) !DenseT { if (sparse >= self.capacity_sparse) { return error.OutOfBounds; } if (try self.hasSparseOrError(sparse)) { return error.AlreadyRegistered; } if (self.dense_count == self.capacity_dense) { if (allow_resize == .ResizeAllowed) { self.capacity_dense = self.capacity_dense * 2; self.dense_to_sparse = try self.allocator.realloc(self.dense_to_sparse, self.capacity_dense); if (value_layout == .InternalArrayOfStructs) { self.values = try self.allocator.realloc(self.values, self.capacity_dense); } } else { return error.OutOfBounds; } } return self.add(sparse); } // TODO: Rewrite after https://github.com/ziglang/zig/issues/1717 pub usingnamespace switch (value_layout) { .InternalArrayOfStructs => struct { /// Registers the sparse value and matches it to a dense index /// Grows .dense_to_sparse and .values if needed and resizing is allowed. /// Note: If resizing is allowed, you must use an allocator that you are sure /// will never fail for your use cases. /// If that is not an option, use addOrError. pub fn addValue(self: *Self, sparse: SparseT, value: ValueT) DenseT { if (allow_resize == .ResizeAllowed) { if (self.dense_count == self.capacity_dense) { self.capacity_dense = self.capacity_dense * 2; self.dense_to_sparse = self.allocator.realloc(self.dense_to_sparse, self.capacity_dense) catch unreachable; if (value_layout == .InternalArrayOfStructs) { self.values = self.allocator.realloc(self.values, self.capacity_dense) catch unreachable; } } } assert(sparse < self.capacity_sparse); assert(self.dense_count < self.capacity_dense); assert(!self.hasSparse(sparse)); self.dense_to_sparse[self.dense_count] = sparse; self.sparse_to_dense[sparse] = self.dense_count; self.values[self.dense_count] = value; self.dense_count += 1; return self.dense_count - 1; } /// May return error.OutOfBounds or error.AlreadyRegistered, otherwise calls add. /// Grows .dense_to_sparse and .values if needed and resizing is allowed. pub fn addValueOrError(self: *Self, sparse: SparseT, value: ValueT) !DenseT { if (sparse >= self.capacity_sparse) { return error.OutOfBounds; } if (try self.hasSparseOrError(sparse)) { return error.AlreadyRegistered; } if (self.dense_count == self.capacity_dense) { if (allow_resize == .ResizeAllowed) { self.capacity_dense = self.capacity_dense * 2; self.dense_to_sparse = try self.allocator.realloc(self.dense_to_sparse, self.capacity_dense); if (value_layout == .InternalArrayOfStructs) { self.values = try self.allocator.realloc(self.values, self.capacity_dense); } } else { return error.OutOfBounds; } } return self.addValue(sparse, value); } }, else => struct {}, }; /// Removes the sparse/dense index, and replaces it with the last ones. /// dense_old and dense_new is pub fn removeWithInfo(self: *Self, sparse: SparseT, dense_old: *DenseT, dense_new: *DenseT) void { assert(self.dense_count > 0); assert(self.hasSparse(sparse)); const last_dense = self.dense_count - 1; const last_sparse = self.dense_to_sparse[last_dense]; const dense = self.sparse_to_dense[sparse]; self.dense_to_sparse[dense] = last_sparse; self.sparse_to_dense[last_sparse] = dense; if (value_layout == .InternalArrayOfStructs) { self.values[dense] = self.values[last_dense]; } self.dense_count -= 1; dense_old.* = last_dense; dense_new.* = dense; } /// May return error.OutOfBounds, otherwise calls removeWithInfo. pub fn removeWithInfoOrError(self: *Self, sparse: SparseT, dense_old: *DenseT, dense_new: *DenseT) !void { if (self.dense_count == 0) { return error.OutOfBounds; } if (!try self.hasSparseOrError(sparse)) { return error.NotRegistered; } return self.removeWithInfo(sparse, dense_old, dense_new); } /// Like removeWithInfo info, but slightly faster, in case you don't care about the switch. pub fn remove(self: *Self, sparse: SparseT) void { assert(self.dense_count > 0); assert(self.hasSparse(sparse)); const last_dense = self.dense_count - 1; const last_sparse = self.dense_to_sparse[last_dense]; const dense = self.sparse_to_dense[sparse]; self.dense_to_sparse[dense] = last_sparse; self.sparse_to_dense[last_sparse] = dense; if (value_layout == .InternalArrayOfStructs) { self.values[dense] = self.values[last_dense]; } self.dense_count -= 1; } /// May return error.OutOfBounds or error.NotRegistered, otherwise calls remove. pub fn removeOrError(self: *Self, sparse: SparseT) !void { if (self.dense_count == 0) { return error.OutOfBounds; } if (!try self.hasSparseOrError(sparse)) { return error.NotRegistered; } self.remove(sparse); } /// Returns true if the sparse is registered to a dense index. pub fn hasSparse(self: Self, sparse: SparseT) bool { // Unsure if this call to disable runtime safety is needed - can add later if so. // Related: https://github.com/ziglang/zig/issues/978 // @setRuntimeSafety(false); assert(sparse < self.capacity_sparse); const dense = self.sparse_to_dense[sparse]; return dense < self.dense_count and self.dense_to_sparse[dense] == sparse; } /// May return error.OutOfBounds, otherwise calls hasSparse. pub fn hasSparseOrError(self: Self, sparse: SparseT) !bool { if (sparse >= self.capacity_sparse) { return error.OutOfBounds; } return self.hasSparse(sparse); } /// Returns corresponding dense index. pub fn getBySparse(self: Self, sparse: SparseT) DenseT { assert(self.hasSparse(sparse)); return self.sparse_to_dense[sparse]; } /// Tries hasSparseOrError, then returns getBySparse. pub fn getBySparseOrError(self: Self, sparse: SparseT) !DenseT { _ = try self.hasSparseOrError(sparse); return self.getBySparse(sparse); } /// Returns corresponding sparse index. pub fn getByDense(self: Self, dense: DenseT) SparseT { assert(dense < self.dense_count); return self.dense_to_sparse[dense]; } /// Returns OutOfBounds or getByDense. pub fn getByDenseOrError(self: Self, dense: DenseT) !SparseT { if (dense >= self.dense_count) { return error.OutOfBounds; } return self.getByDense(dense); } // TODO: Rewrite after https://github.com/ziglang/zig/issues/1717 pub usingnamespace switch (value_layout) { .InternalArrayOfStructs => struct { /// Returns a pointer to the SOA value corresponding to the sparse parameter. pub fn getValueBySparse(self: Self, sparse: SparseT) *ValueT { assert(self.hasSparse(sparse)); const dense = self.sparse_to_dense[sparse]; return &self.values[dense]; } /// First tries hasSparse, then returns getValueBySparse(). pub fn getValueBySparseOrError(self: Self, sparse: SparseT) !*ValueT { _ = try self.hasSparseOrError(sparse); return self.getValueBySparse(sparse); } /// Returns a pointer to the SOA value corresponding to the sparse parameter. pub fn getValueByDense(self: Self, dense: DenseT) *ValueT { assert(dense < self.dense_count); return &self.values[dense]; } /// Returns error.OutOfBounds or getValueByDense(). pub fn getValueByDenseOrError(self: Self, dense: DenseT) !*ValueT { if (dense >= self.dense_count) { return error.OutOfBounds; } return self.getValueByDense(dense); } }, else => struct {}, }; }; } test "docs" { const Entity = u32; const DenseT = u8; const DocValueT = i32; const DocsSparseSet = SparseSet(.{ .SparseT = Entity, .DenseT = DenseT, .ValueT = DocValueT, .allow_resize = .NoResize, .value_layout = .InternalArrayOfStructs, }); var ss = DocsSparseSet.init(std.testing.allocator, 128, 8) catch unreachable; defer ss.deinit(); var ent1: Entity = 1; var ent2: Entity = 2; _ = try ss.addOrError(ent1); _ = try ss.addValueOrError(ent2, 2); std.testing.expectEqual(@as(DenseT, 2), ss.len()); try ss.removeOrError(ent1); var old: DenseT = undefined; var new: DenseT = undefined; try ss.removeWithInfoOrError(ent2, &old, &new); _ = ss.toSparseSlice(); _ = ss.toValueSlice(); std.testing.expectEqual(@as(DenseT, 0), ss.len()); ss.clear(); std.testing.expectEqual(@as(DenseT, 8), ss.remainingCapacity()); _ = try ss.addValueOrError(ent1, 10); std.testing.expectEqual(@as(DenseT, 0), try ss.getBySparseOrError(ent1)); std.testing.expectEqual(@as(DocValueT, 10), (try ss.getValueBySparseOrError(ent1)).*); std.testing.expectEqual(@as(Entity, ent1), try ss.getByDenseOrError(0)); std.testing.expectEqual(@as(DocValueT, 10), (try ss.getValueByDenseOrError(0)).*); }
src/sparse_set.zig
const std = @import("std"); const assert = std.debug.assert; const zbs = std.build; const fs = std.fs; const mem = std.mem; const ScanProtocolsStep = @import("deps/zig-wayland/build.zig").ScanProtocolsStep; /// While a waylock release is in development, this string should contain the version in /// development with the "-dev" suffix. /// When a release is tagged, the "-dev" suffix should be removed for the commit that gets tagged. /// Directly after the tagged commit, the version should be bumped and the "-dev" suffix added. const version = "0.5.0-dev"; pub fn build(b: *zbs.Builder) !void { const target = b.standardTargetOptions(.{}); const mode = b.standardReleaseOptions(); const strip = b.option(bool, "strip", "Omit debug information") orelse false; const pie = b.option(bool, "pie", "Build a Position Independent Executable") orelse false; const man_pages = b.option( bool, "man-pages", "Set to true to build man pages. Requires scdoc. Defaults to true if scdoc is found.", ) orelse scdoc_found: { _ = b.findProgram(&[_][]const u8{"scdoc"}, &[_][]const u8{}) catch |err| switch (err) { error.FileNotFound => break :scdoc_found false, else => return err, }; break :scdoc_found true; }; if (man_pages) { const scdoc_step = try ScdocStep.create(b); try scdoc_step.install(); } const install_prefix = try std.fs.path.resolve(b.allocator, &[_][]const u8{b.install_prefix}); if (std.mem.eql(u8, install_prefix, "/usr")) { b.installFile("pam.d/waylock", "../etc/pam.d/waylock"); } else { b.installFile("pam.d/waylock", "etc/pam.d/waylock"); } const full_version = blk: { if (mem.endsWith(u8, version, "-dev")) { var ret: u8 = undefined; const git_describe_long = b.execAllowFail( &[_][]const u8{ "git", "-C", b.build_root, "describe", "--long" }, &ret, .Inherit, ) catch break :blk version; var it = mem.split(u8, mem.trim(u8, git_describe_long, &std.ascii.spaces), "-"); _ = it.next().?; // previous tag const commit_count = it.next().?; const commit_hash = it.next().?; assert(it.next() == null); assert(commit_hash[0] == 'g'); // Follow semantic versioning, e.g. 0.2.0-dev.42+d1cf95b break :blk try std.fmt.allocPrintZ(b.allocator, version ++ ".{s}+{s}", .{ commit_count, commit_hash[1..], }); } else { break :blk version; } }; const options = b.addOptions(); options.addOption([]const u8, "version", full_version); const scanner = ScanProtocolsStep.create(b); scanner.addSystemProtocol("staging/ext-session-lock/ext-session-lock-v1.xml"); scanner.addSystemProtocol("stable/viewporter/viewporter.xml"); scanner.generate("wl_compositor", 4); scanner.generate("wl_shm", 1); scanner.generate("wl_output", 3); scanner.generate("wl_seat", 5); scanner.generate("ext_session_lock_manager_v1", 1); scanner.generate("wp_viewporter", 1); const waylock = b.addExecutable("waylock", "src/main.zig"); waylock.setTarget(target); waylock.setBuildMode(mode); waylock.addOptions("build_options", options); waylock.addPackage(.{ .name = "wayland", .path = .{ .generated = &scanner.result }, }); waylock.step.dependOn(&scanner.step); waylock.addPackagePath("xkbcommon", "deps/zig-xkbcommon/src/xkbcommon.zig"); waylock.linkLibC(); waylock.linkSystemLibrary("wayland-client"); waylock.linkSystemLibrary("xkbcommon"); waylock.linkSystemLibrary("pam"); scanner.addCSource(waylock); waylock.strip = strip; waylock.pie = pie; waylock.install(); } const ScdocStep = struct { builder: *zbs.Builder, step: zbs.Step, fn create(builder: *zbs.Builder) !*ScdocStep { const self = try builder.allocator.create(ScdocStep); self.* = .{ .builder = builder, .step = zbs.Step.init(.custom, "Generate man pages", builder.allocator, make), }; return self; } fn make(step: *zbs.Step) !void { const self = @fieldParentPtr(ScdocStep, "step", step); _ = try self.builder.exec( &[_][]const u8{ "sh", "-c", "scdoc < doc/waylock.1.scd > doc/waylock.1" }, ); } fn install(self: *ScdocStep) !void { self.builder.getInstallStep().dependOn(&self.step); self.builder.installFile("doc/waylock.1", "share/man/man1/waylock.1"); } };
build.zig
const std = @import("std"); const build_options = @import("build_options"); const debug = std.debug; const mem = std.mem; const testing = std.testing; const c = @cImport({ @cInclude("sqlite3.h"); }); usingnamespace @import("query.zig"); usingnamespace @import("error.zig"); const logger = std.log.scoped(.sqlite); /// ThreadingMode controls the threading mode used by SQLite. /// /// See https://sqlite.org/threadsafe.html pub const ThreadingMode = enum { /// SingleThread makes SQLite unsafe to use with more than a single thread at once. SingleThread, /// MultiThread makes SQLite safe to use with multiple threads at once provided that /// a single database connection is not by more than a single thread at once. MultiThread, /// Serialized makes SQLite safe to use with multiple threads at once with no restriction. Serialized, }; pub const InitOptions = struct { /// mode controls how the database is opened. /// /// Defaults to a in-memory database. mode: Db.Mode = .Memory, /// open_flags controls the flags used when opening a database. /// /// Defaults to a read only database. open_flags: Db.OpenFlags = .{}, /// threading_mode controls the threading mode used by SQLite. /// /// Defaults to Serialized. threading_mode: ThreadingMode = .Serialized, }; /// DetailedError contains a SQLite error code and error message. pub const DetailedError = struct { code: usize, message: []const u8, }; fn isThreadSafe() bool { return c.sqlite3_threadsafe() > 0; } fn getDetailedErrorFromResultCode(code: c_int) DetailedError { return .{ .code = @intCast(usize, code), .message = blk: { const msg = c.sqlite3_errstr(code); break :blk mem.spanZ(msg); }, }; } fn getLastDetailedErrorFromDb(db: *c.sqlite3) DetailedError { return .{ .code = @intCast(usize, c.sqlite3_extended_errcode(db)), .message = blk: { const msg = c.sqlite3_errmsg(db); break :blk mem.spanZ(msg); }, }; } /// Db is a wrapper around a SQLite database, providing high-level functions for executing queries. /// A Db can be opened with a file database or a in-memory database: /// /// // File database /// var db: sqlite.Db = undefined; /// try db.init(.{ .mode = { .File = "/tmp/data.db" } }); /// /// // In memory database /// var db: sqlite.Db = undefined; /// try db.init(.{ .mode = { .Memory = {} } }); /// pub const Db = struct { const Self = @This(); db: *c.sqlite3, /// Mode determines how the database will be opened. pub const Mode = union(enum) { File: [:0]const u8, Memory, }; /// OpenFlags contains various flags used when opening a SQLite databse. pub const OpenFlags = struct { write: bool = false, create: bool = false, }; /// init creates a database with the provided `mode`. pub fn init(self: *Self, options: InitOptions) !void { // Validate the threading mode if (options.threading_mode != .SingleThread and !isThreadSafe()) { return error.CannotUseSingleThreadedSQLite; } // Compute the flags var flags: c_int = 0; flags |= @as(c_int, if (options.open_flags.write) c.SQLITE_OPEN_READWRITE else c.SQLITE_OPEN_READONLY); if (options.open_flags.create) { flags |= c.SQLITE_OPEN_CREATE; } switch (options.threading_mode) { .MultiThread => flags |= c.SQLITE_OPEN_NOMUTEX, .Serialized => flags |= c.SQLITE_OPEN_FULLMUTEX, else => {}, } switch (options.mode) { .File => |path| { logger.info("opening {}", .{path}); var db: ?*c.sqlite3 = undefined; const result = c.sqlite3_open_v2(path, &db, flags, null); if (result != c.SQLITE_OK or db == null) { return errorFromResultCode(result); } self.db = db.?; }, .Memory => { logger.info("opening in memory", .{}); flags |= c.SQLITE_OPEN_MEMORY; var db: ?*c.sqlite3 = undefined; const result = c.sqlite3_open_v2(":memory:", &db, flags, null); if (result != c.SQLITE_OK or db == null) { return errorFromResultCode(result); } self.db = db.?; }, } } /// deinit closes the database. pub fn deinit(self: *Self) void { _ = c.sqlite3_close(self.db); } // getDetailedError returns the detailed error for the last API call if it failed. pub fn getDetailedError(self: *Self) DetailedError { return getLastDetailedErrorFromDb(self.db); } fn getPragmaQuery(comptime buf: []u8, comptime name: []const u8, comptime arg: anytype) []const u8 { return if (arg.len == 1) blk: { break :blk try std.fmt.bufPrint(buf, "PRAGMA {s} = {s}", .{ name, arg[0] }); } else blk: { break :blk try std.fmt.bufPrint(buf, "PRAGMA {s}", .{name}); }; } /// pragmaAlloc is like `pragma` but can allocate memory. /// /// Useful when the pragma command returns text, for example: /// /// const journal_mode = try db.pragma([]const u8, allocator, .{}, "journal_mode", .{}); /// pub fn pragmaAlloc(self: *Self, comptime Type: type, allocator: *mem.Allocator, options: anytype, comptime name: []const u8, comptime arg: anytype) !?Type { comptime var buf: [1024]u8 = undefined; comptime var query = getPragmaQuery(&buf, name, arg); var stmt = try self.prepare(query); defer stmt.deinit(); return try stmt.oneAlloc(Type, allocator, options, .{}); } /// pragma is a convenience function to use the PRAGMA statement. /// /// Here is how to set a pragma value: /// /// try db.pragma(void, "foreign_keys", .{}, .{1}); /// /// Here is how to query a pragama value: /// /// const journal_mode = try db.pragma([128:0]const u8, .{}, "journal_mode", .{}); /// /// The pragma name must be known at comptime. /// /// This cannot allocate memory. If your pragma command returns text you must use an array or call `pragmaAlloc`. pub fn pragma(self: *Self, comptime Type: type, options: anytype, comptime name: []const u8, arg: anytype) !?Type { comptime var buf: [1024]u8 = undefined; comptime var query = getPragmaQuery(&buf, name, arg); var stmt = try self.prepare(query); defer stmt.deinit(); return try stmt.one(Type, options, .{}); } /// exec is a convenience function which prepares a statement and executes it directly. pub fn exec(self: *Self, comptime query: []const u8, values: anytype) !void { var stmt = try self.prepare(query); defer stmt.deinit(); try stmt.exec(values); } /// one is a convenience function which prepares a statement and reads a single row from the result set. pub fn one(self: *Self, comptime Type: type, comptime query: []const u8, options: anytype, values: anytype) !?Type { var stmt = try self.prepare(query); defer stmt.deinit(); return try stmt.one(Type, options, values); } /// oneAlloc is like `one` but can allocate memory. pub fn oneAlloc(self: *Self, comptime Type: type, allocator: *mem.Allocator, comptime query: []const u8, options: anytype, values: anytype) !?Type { var stmt = try self.prepare(query); defer stmt.deinit(); return try stmt.oneAlloc(Type, allocator, options, values); } /// prepare prepares a statement for the `query` provided. /// /// The query is analysed at comptime to search for bind markers. /// prepare enforces having as much fields in the `values` tuple as there are bind markers. /// /// Example usage: /// /// var stmt = try db.prepare("INSERT INTO foo(id, name) VALUES(?, ?)"); /// defer stmt.deinit(); /// /// The statement returned is only compatible with the number of bind markers in the input query. /// This is done because we type check the bind parameters when executing the statement later. /// pub fn prepare(self: *Self, comptime query: []const u8) !Statement(.{}, ParsedQuery.from(query)) { @setEvalBranchQuota(10000); const parsed_query = ParsedQuery.from(query); return Statement(.{}, comptime parsed_query).prepare(self, 0); } /// rowsAffected returns the number of rows affected by the last statement executed. pub fn rowsAffected(self: *Self) usize { return @intCast(usize, c.sqlite3_changes(self.db)); } }; /// Iterator allows iterating over a result set. /// /// Each call to `next` returns the next row of the result set, or null if the result set is exhausted. /// Each row will have the type `Type` so the columns returned in the result set must be compatible with this type. /// /// Here is an example of how to use the iterator: /// /// const User = struct { /// name: Text, /// age: u16, /// }; /// /// var stmt = try db.prepare("SELECT name, age FROM user"); /// defer stmt.deinit(); /// /// var iter = try stmt.iterator(User, .{}); /// while (true) { /// const row: User = (try iter.next(.{})) orelse break; /// ... /// } /// /// The iterator _must not_ outlive the statement. pub fn Iterator(comptime Type: type) type { return struct { const Self = @This(); const TypeInfo = @typeInfo(Type); stmt: *c.sqlite3_stmt, // next scans the next row using the prepared statement. // If it returns null iterating is done. // // This cannot allocate memory. If you need to read TEXT or BLOB columns you need to use arrays or alternatively call nextAlloc. pub fn next(self: *Self, options: anytype) !?Type { var result = c.sqlite3_step(self.stmt); if (result == c.SQLITE_DONE) { return null; } if (result != c.SQLITE_ROW) { return errorFromResultCode(result); } const columns = c.sqlite3_column_count(self.stmt); switch (TypeInfo) { .Int => { debug.assert(columns == 1); return try self.readInt(Type, 0); }, .Float => { debug.assert(columns == 1); return try self.readFloat(Type, 0); }, .Bool => { debug.assert(columns == 1); return try self.readBool(0); }, .Void => { debug.assert(columns == 1); }, .Array => { debug.assert(columns == 1); return try self.readArray(Type, 0); }, .Struct => { std.debug.assert(columns == TypeInfo.Struct.fields.len); return try self.readStruct(.{}); }, else => @compileError("cannot read into type " ++ @typeName(Type) ++ " ; if dynamic memory allocation is required use nextAlloc"), } } // nextAlloc is like `next` but can allocate memory. pub fn nextAlloc(self: *Self, allocator: *mem.Allocator, options: anytype) !?Type { var result = c.sqlite3_step(self.stmt); if (result == c.SQLITE_DONE) { return null; } if (result != c.SQLITE_ROW) { return errorFromResultCode(result); } const columns = c.sqlite3_column_count(self.stmt); switch (Type) { []const u8, []u8 => { debug.assert(columns == 1); return try self.readBytes(Type, allocator, 0, .Text); }, Blob => { debug.assert(columns == 1); return try self.readBytes(Blob, allocator, 0, .Blob); }, Text => { debug.assert(columns == 1); return try self.readBytes(Text, allocator, 0, .Text); }, else => {}, } switch (TypeInfo) { .Int => { debug.assert(columns == 1); return try self.readInt(Type, 0); }, .Float => { debug.assert(columns == 1); return try self.readFloat(Type, 0); }, .Bool => { debug.assert(columns == 1); return try self.readBool(0); }, .Void => { debug.assert(columns == 1); }, .Array => { debug.assert(columns == 1); return try self.readArray(Type, 0); }, .Pointer => { debug.assert(columns == 1); return try self.readPointer(Type, allocator, 0); }, .Struct => { std.debug.assert(columns == TypeInfo.Struct.fields.len); return try self.readStruct(.{ .allocator = allocator, }); }, else => @compileError("cannot read into type " ++ @typeName(Type)), } } // readArray reads a sqlite BLOB or TEXT column into an array of u8. // // We also require the array to have a sentinel because otherwise we have no way // of communicating the end of the data to the caller. // // If the array is too small for the data an error will be returned. fn readArray(self: *Self, comptime ArrayType: type, _i: usize) error{ArrayTooSmall}!ArrayType { const i = @intCast(c_int, _i); const type_info = @typeInfo(ArrayType); var ret: ArrayType = undefined; switch (type_info) { .Array => |arr| { comptime if (arr.sentinel == null) { @compileError("cannot populate array of " ++ @typeName(arr.child) ++ ", arrays must have a sentinel"); }; switch (arr.child) { u8 => { const data = c.sqlite3_column_blob(self.stmt, i); const size = @intCast(usize, c.sqlite3_column_bytes(self.stmt, i)); if (size >= @as(usize, arr.len)) return error.ArrayTooSmall; const ptr = @ptrCast([*c]const u8, data)[0..size]; mem.copy(u8, ret[0..], ptr); ret[size] = arr.sentinel.?; }, else => @compileError("cannot populate field " ++ field.name ++ " of type array of " ++ @typeName(arr.child)), } }, else => @compileError("cannot populate field " ++ field.name ++ " of type array of " ++ @typeName(arr.child)), } return ret; } // readInt reads a sqlite INTEGER column into an integer. fn readInt(self: *Self, comptime IntType: type, i: usize) !IntType { const n = c.sqlite3_column_int64(self.stmt, @intCast(c_int, i)); return @intCast(IntType, n); } // readFloat reads a sqlite REAL column into a float. fn readFloat(self: *Self, comptime FloatType: type, i: usize) !FloatType { const d = c.sqlite3_column_double(self.stmt, @intCast(c_int, i)); return @floatCast(FloatType, d); } // readFloat reads a sqlite INTEGER column into a bool (true is anything > 0, false is anything <= 0). fn readBool(self: *Self, i: usize) !bool { const d = c.sqlite3_column_int64(self.stmt, @intCast(c_int, i)); return d > 0; } const ReadBytesMode = enum { Blob, Text, }; // dupeWithSentinel is like dupe/dupeZ but allows for any sentinel value. fn dupeWithSentinel(comptime SliceType: type, allocator: *mem.Allocator, data: []const u8) !SliceType { const type_info = @typeInfo(SliceType); switch (type_info) { .Pointer => |ptr_info| { if (ptr_info.sentinel) |sentinel| { const slice = try allocator.alloc(u8, data.len + 1); mem.copy(u8, slice, data); slice[data.len] = sentinel; return slice[0..data.len :sentinel]; } else { return try allocator.dupe(u8, data); } }, else => @compileError("cannot dupe type " ++ @typeName(SliceType)), } } // readBytes reads a sqlite BLOB or TEXT column. // // The mode controls which sqlite function is used to retrieve the data: // * .Blob uses sqlite3_column_blob // * .Text uses sqlite3_column_text // // When using .Blob you can only read into either []const u8, []u8 or Blob. // When using .Text you can only read into either []const u8, []u8 or Text. // // The options must contain an `allocator` field which will be used to create a copy of the data. fn readBytes(self: *Self, comptime BytesType: type, allocator: *mem.Allocator, _i: usize, comptime mode: ReadBytesMode) !BytesType { const i = @intCast(c_int, _i); const type_info = @typeInfo(BytesType); var ret: BytesType = switch (BytesType) { Text, Blob => .{ .data = "" }, else => try dupeWithSentinel(BytesType, allocator, ""), }; switch (mode) { .Blob => { const data = c.sqlite3_column_blob(self.stmt, i); if (data == null) { return switch (BytesType) { Text, Blob => .{ .data = try allocator.dupe(u8, "") }, else => try dupeWithSentinel(BytesType, allocator, ""), }; } const size = @intCast(usize, c.sqlite3_column_bytes(self.stmt, i)); const ptr = @ptrCast([*c]const u8, data)[0..size]; if (BytesType == Blob) { return Blob{ .data = try allocator.dupe(u8, ptr) }; } return try dupeWithSentinel(BytesType, allocator, ptr); }, .Text => { const data = c.sqlite3_column_text(self.stmt, i); if (data == null) { return switch (BytesType) { Text, Blob => .{ .data = try allocator.dupe(u8, "") }, else => try dupeWithSentinel(BytesType, allocator, ""), }; } const size = @intCast(usize, c.sqlite3_column_bytes(self.stmt, i)); const ptr = @ptrCast([*c]const u8, data)[0..size]; if (BytesType == Text) { return Text{ .data = try allocator.dupe(u8, ptr) }; } return try dupeWithSentinel(BytesType, allocator, ptr); }, } } fn readPointer(self: *Self, comptime PointerType: type, allocator: *mem.Allocator, i: usize) !PointerType { const type_info = @typeInfo(PointerType); var ret: PointerType = undefined; switch (type_info) { .Pointer => |ptr| { switch (ptr.size) { .One => unreachable, .Slice => switch (ptr.child) { u8 => ret = try self.readBytes(PointerType, allocator, i, .Text), else => @compileError("cannot read pointer of type " ++ @typeName(PointerType)), }, else => @compileError("cannot read pointer of type " ++ @typeName(PointerType)), } }, else => @compileError("cannot read pointer of type " ++ @typeName(PointerType)), } return ret; } // readStruct reads an entire sqlite row into a struct. // // Each field correspond to a column; its position in the struct determines the column used for it. // For example, given the following query: // // SELECT id, name, age FROM user // // The struct must have the following fields: // // struct { // id: usize, // name: []const u8, // age: u16, // } // // The field `id` will be associated with the column `id` and so on. // // This function relies on the fact that there are the same number of fields than columns and // that the order is correct. // // TODO(vincent): add comptime checks for the fields/columns. fn readStruct(self: *Self, options: anytype) !Type { var value: Type = undefined; inline for (@typeInfo(Type).Struct.fields) |field, _i| { const i = @as(usize, _i); const field_type_info = @typeInfo(field.field_type); const ret = switch (field.field_type) { Blob => try self.readBytes(Blob, options.allocator, i, .Blob), Text => try self.readBytes(Text, options.allocator, i, .Text), else => switch (field_type_info) { .Int => try self.readInt(field.field_type, i), .Float => try self.readFloat(field.field_type, i), .Bool => try self.readBool(i), .Void => {}, .Array => try self.readArray(field.field_type, i), .Pointer => try self.readPointer(field.field_type, options.allocator, i), else => @compileError("cannot populate field " ++ field.name ++ " of type " ++ @typeName(field.field_type)), }, }; @field(value, field.name) = ret; } return value; } }; } pub const StatementOptions = struct {}; /// Statement is a wrapper around a SQLite statement, providing high-level functions to execute /// a statement and retrieve rows for SELECT queries. /// /// The exec function can be used to execute a query which does not return rows: /// /// var stmt = try db.prepare("UPDATE foo SET id = ? WHERE name = ?"); /// defer stmt.deinit(); /// /// try stmt.exec(.{ /// .id = 200, /// .name = "José", /// }); /// /// The one function can be used to select a single row: /// /// var stmt = try db.prepare("SELECT name FROM foo WHERE id = ?"); /// defer stmt.deinit(); /// /// const name = try stmt.one([]const u8, .{}, .{ .id = 200 }); /// /// The all function can be used to select all rows: /// /// var stmt = try db.prepare("SELECT id, name FROM foo"); /// defer stmt.deinit(); /// /// const Row = struct { /// id: usize, /// name: []const u8, /// }; /// const rows = try stmt.all(Row, .{ .allocator = allocator }, .{}); /// /// Look at each function for more complete documentation. /// pub fn Statement(comptime opts: StatementOptions, comptime query: ParsedQuery) type { return struct { const Self = @This(); stmt: *c.sqlite3_stmt, fn prepare(db: *Db, flags: c_uint) !Self { var stmt = blk: { const real_query = query.getQuery(); var tmp: ?*c.sqlite3_stmt = undefined; const result = c.sqlite3_prepare_v3( db.db, real_query.ptr, @intCast(c_int, real_query.len), flags, &tmp, null, ); if (result != c.SQLITE_OK) { return errorFromResultCode(result); } break :blk tmp.?; }; return Self{ .stmt = stmt, }; } /// deinit releases the prepared statement. /// /// After a call to `deinit` the statement must not be used. pub fn deinit(self: *Self) void { const result = c.sqlite3_finalize(self.stmt); if (result != c.SQLITE_OK) { logger.err("unable to finalize prepared statement, result: {}", .{result}); } } /// reset resets the prepared statement to make it reusable. pub fn reset(self: *Self) void { const result = c.sqlite3_clear_bindings(self.stmt); if (result != c.SQLITE_OK) { logger.err("unable to clear prepared statement bindings, result: {}", .{result}); } const result2 = c.sqlite3_reset(self.stmt); if (result2 != c.SQLITE_OK) { logger.err("unable to reset prepared statement, result: {}", .{result2}); } } /// bind binds values to every bind marker in the prepared statement. /// /// The `values` variable must be a struct where each field has the type of the corresponding bind marker. /// For example this query: /// SELECT 1 FROM user WHERE name = ?{text} AND age < ?{u32} /// /// Has two bind markers, so `values` must have at least the following fields: /// struct { /// name: Text, /// age: u32 /// } /// /// The types are checked at comptime. fn bind(self: *Self, values: anytype) void { const StructType = @TypeOf(values); const StructTypeInfo = @typeInfo(StructType).Struct; if (comptime query.nb_bind_markers != StructTypeInfo.fields.len) { @compileError("number of bind markers not equal to number of fields"); } inline for (StructTypeInfo.fields) |struct_field, _i| { const bind_marker = query.bind_markers[_i]; switch (bind_marker) { .Typed => |typ| if (struct_field.field_type != typ) { @compileError("value type " ++ @typeName(struct_field.field_type) ++ " is not the bind marker type " ++ @typeName(typ)); }, .Untyped => {}, } const field_value = @field(values, struct_field.name); self.bindField(struct_field.field_type, struct_field.name, _i, field_value); } } fn bindField(self: *Self, comptime FieldType: type, comptime field_name: []const u8, i: c_int, field: FieldType) void { const field_type_info = @typeInfo(FieldType); const column = i + 1; switch (FieldType) { Text => _ = c.sqlite3_bind_text(self.stmt, column, field.data.ptr, @intCast(c_int, field.data.len), null), Blob => _ = c.sqlite3_bind_blob(self.stmt, column, field.data.ptr, @intCast(c_int, field.data.len), null), else => switch (field_type_info) { .Int, .ComptimeInt => _ = c.sqlite3_bind_int64(self.stmt, column, @intCast(c_longlong, field)), .Float, .ComptimeFloat => _ = c.sqlite3_bind_double(self.stmt, column, field), .Bool => _ = c.sqlite3_bind_int64(self.stmt, column, @boolToInt(field)), .Pointer => |ptr| switch (ptr.size) { .One => self.bindField(ptr.child, field_name, i, field.*), .Slice => switch (ptr.child) { u8 => { _ = c.sqlite3_bind_text(self.stmt, column, field.ptr, @intCast(c_int, field.len), null); }, else => @compileError("cannot bind field " ++ field_name ++ " of type " ++ @typeName(FieldType)), }, else => @compileError("cannot bind field " ++ field_name ++ " of type " ++ @typeName(FieldType)), }, .Array => |arr| { switch (arr.child) { u8 => { const data: []const u8 = field[0..field.len]; _ = c.sqlite3_bind_text(self.stmt, column, data.ptr, @intCast(c_int, data.len), null); }, else => @compileError("cannot bind field " ++ field_name ++ " of type array of " ++ @typeName(arr.child)), } }, else => @compileError("cannot bind field " ++ field_name ++ " of type " ++ @typeName(FieldType)), }, } } /// exec executes a statement which does not return data. /// /// The `values` variable is used for the bind parameters. It must have as many fields as there are bind markers /// in the input query string. /// pub fn exec(self: *Self, values: anytype) !void { self.bind(values); const result = c.sqlite3_step(self.stmt); switch (result) { c.SQLITE_DONE => {}, c.SQLITE_BUSY => return errorFromResultCode(result), else => std.debug.panic("invalid result {}", .{result}), } } /// iterator returns an iterator to read data from the result set, one row at a time. /// /// The data in the row is used to populate a value of the type `Type`. /// This means that `Type` must have as many fields as is returned in the query /// executed by this statement. /// This also means that the type of each field must be compatible with the SQLite type. /// /// Here is an example of how to use the iterator: /// /// var iter = try stmt.iterator(usize, .{}); /// while (true) { /// const row = (try iter.next(.{})) orelse break; /// ... /// } /// /// The `values` tuple is used for the bind parameters. It must have as many fields as there are bind markers /// in the input query string. /// /// The iterator _must not_ outlive the statement. pub fn iterator(self: *Self, comptime Type: type, values: anytype) !Iterator(Type) { self.bind(values); var res: Iterator(Type) = undefined; res.stmt = self.stmt; return res; } /// one reads a single row from the result set of this statement. /// /// The data in the row is used to populate a value of the type `Type`. /// This means that `Type` must have as many fields as is returned in the query /// executed by this statement. /// This also means that the type of each field must be compatible with the SQLite type. /// /// Here is an example of how to use an anonymous struct type: /// /// const row = try stmt.one( /// struct { /// id: usize, /// name: [400]u8, /// age: usize, /// }, /// .{}, /// .{ .foo = "bar", .age = 500 }, /// ); /// /// The `options` tuple is used to provide additional state in some cases. /// /// The `values` tuple is used for the bind parameters. It must have as many fields as there are bind markers /// in the input query string. /// /// This cannot allocate memory. If you need to read TEXT or BLOB columns you need to use arrays or alternatively call `oneAlloc`. pub fn one(self: *Self, comptime Type: type, options: anytype, values: anytype) !?Type { if (!comptime std.meta.trait.is(.Struct)(@TypeOf(options))) { @compileError("options passed to iterator must be a struct"); } var iter = try self.iterator(Type, values); const row = (try iter.next(options)) orelse return null; return row; } /// oneAlloc is like `one` but can allocate memory. pub fn oneAlloc(self: *Self, comptime Type: type, allocator: *mem.Allocator, options: anytype, values: anytype) !?Type { if (!comptime std.meta.trait.is(.Struct)(@TypeOf(options))) { @compileError("options passed to iterator must be a struct"); } var iter = try self.iterator(Type, values); const row = (try iter.nextAlloc(allocator, options)) orelse return null; return row; } /// all reads all rows from the result set of this statement. /// /// The data in each row is used to populate a value of the type `Type`. /// This means that `Type` must have as many fields as is returned in the query /// executed by this statement. /// This also means that the type of each field must be compatible with the SQLite type. /// /// Here is an example of how to use an anonymous struct type: /// /// const rows = try stmt.all( /// struct { /// id: usize, /// name: []const u8, /// age: usize, /// }, /// allocator, /// .{}, /// .{ .foo = "bar", .age = 500 }, /// ); /// /// The `options` tuple is used to provide additional state in some cases. /// /// The `values` tuple is used for the bind parameters. It must have as many fields as there are bind markers /// in the input query string. /// /// Note that this allocates all rows into a single slice: if you read a lot of data this can use a lot of memory. pub fn all(self: *Self, comptime Type: type, allocator: *mem.Allocator, options: anytype, values: anytype) ![]Type { if (!comptime std.meta.trait.is(.Struct)(@TypeOf(options))) { @compileError("options passed to iterator must be a struct"); } var iter = try self.iterator(Type, values); var rows = std.ArrayList(Type).init(allocator); while (true) { const row = (try iter.nextAlloc(allocator, options)) orelse break; try rows.append(row); } return rows.toOwnedSlice(); } }; } const TestUser = struct { id: usize, name: []const u8, age: usize, weight: f32, }; const test_users = &[_]TestUser{ .{ .id = 20, .name = "Vincent", .age = 33, .weight = 85.4 }, .{ .id = 40, .name = "Julien", .age = 35, .weight = 100.3 }, .{ .id = 60, .name = "José", .age = 40, .weight = 240.2 }, }; fn addTestData(db: *Db) !void { const AllDDL = &[_][]const u8{ \\CREATE TABLE user( \\ id integer PRIMARY KEY, \\ name text, \\ age integer, \\ weight real \\) , \\CREATE TABLE article( \\ id integer PRIMARY KEY, \\ author_id integer, \\ data text, \\ is_published integer, \\ FOREIGN KEY(author_id) REFERENCES user(id) \\) }; // Create the tables inline for (AllDDL) |ddl| { try db.exec(ddl, .{}); } for (test_users) |user| { try db.exec("INSERT INTO user(id, name, age, weight) VALUES(?{usize}, ?{[]const u8}, ?{usize}, ?{f32})", user); const rows_inserted = db.rowsAffected(); testing.expectEqual(@as(usize, 1), rows_inserted); } } test "sqlite: db init" { var db: Db = undefined; try db.init(initOptions()); try db.init(.{}); } test "sqlite: db pragma" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); var db: Db = undefined; try db.init(initOptions()); const foreign_keys = try db.pragma(usize, .{}, "foreign_keys", .{}); testing.expect(foreign_keys != null); testing.expectEqual(@as(usize, 0), foreign_keys.?); const arg = .{"wal"}; if (build_options.in_memory) { { const journal_mode = try db.pragma([128:0]u8, .{}, "journal_mode", arg); testing.expect(journal_mode != null); testing.expectEqualStrings("memory", mem.spanZ(&journal_mode.?)); } { const journal_mode = try db.pragmaAlloc([]const u8, &arena.allocator, .{}, "journal_mode", arg); testing.expect(journal_mode != null); testing.expectEqualStrings("memory", journal_mode.?); } } else { { const journal_mode = try db.pragma([128:0]u8, .{}, "journal_mode", arg); testing.expect(journal_mode != null); testing.expectEqualStrings("wal", mem.spanZ(&journal_mode.?)); } { const journal_mode = try db.pragmaAlloc([]const u8, &arena.allocator, .{}, "journal_mode", arg); testing.expect(journal_mode != null); testing.expectEqualStrings("wal", journal_mode.?); } } } test "sqlite: statement exec" { var db: Db = undefined; try db.init(initOptions()); try addTestData(&db); // Test with a Blob struct { try db.exec("INSERT INTO user(id, name, age) VALUES(?{usize}, ?{blob}, ?{u32})", .{ .id = @as(usize, 200), .name = Blob{ .data = "hello" }, .age = @as(u32, 20), }); } // Test with a Text struct { try db.exec("INSERT INTO user(id, name, age) VALUES(?{usize}, ?{text}, ?{u32})", .{ .id = @as(usize, 201), .name = Text{ .data = "hello" }, .age = @as(u32, 20), }); } } test "sqlite: read a single user into a struct" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); var db: Db = undefined; try db.init(initOptions()); try addTestData(&db); var stmt = try db.prepare("SELECT id, name, age, weight FROM user WHERE id = ?{usize}"); defer stmt.deinit(); var rows = try stmt.all(TestUser, &arena.allocator, .{}, .{ .id = @as(usize, 20), }); for (rows) |row| { testing.expectEqual(test_users[0].id, row.id); testing.expectEqualStrings(test_users[0].name, row.name); testing.expectEqual(test_users[0].age, row.age); } // Read a row with db.one() { var row = try db.one( struct { id: usize, name: [128:0]u8, age: usize, }, "SELECT id, name, age FROM user WHERE id = ?{usize}", .{}, .{@as(usize, 20)}, ); testing.expect(row != null); const exp = test_users[0]; testing.expectEqual(exp.id, row.?.id); testing.expectEqualStrings(exp.name, mem.spanZ(&row.?.name)); testing.expectEqual(exp.age, row.?.age); } // Read a row with db.oneAlloc() { var row = try db.oneAlloc( struct { id: usize, name: Text, age: usize, }, &arena.allocator, "SELECT id, name, age FROM user WHERE id = ?{usize}", .{}, .{@as(usize, 20)}, ); testing.expect(row != null); const exp = test_users[0]; testing.expectEqual(exp.id, row.?.id); testing.expectEqualStrings(exp.name, row.?.name.data); testing.expectEqual(exp.age, row.?.age); } } test "sqlite: read all users into a struct" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); var db: Db = undefined; try db.init(initOptions()); try addTestData(&db); var stmt = try db.prepare("SELECT id, name, age, weight FROM user"); defer stmt.deinit(); var rows = try stmt.all(TestUser, &arena.allocator, .{}, .{}); testing.expectEqual(@as(usize, 3), rows.len); for (rows) |row, i| { const exp = test_users[i]; testing.expectEqual(exp.id, row.id); testing.expectEqualStrings(exp.name, row.name); testing.expectEqual(exp.age, row.age); testing.expectEqual(exp.weight, row.weight); } } test "sqlite: read in an anonymous struct" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); var db: Db = undefined; try db.init(initOptions()); try addTestData(&db); var stmt = try db.prepare("SELECT id, name, name, age, id, weight FROM user WHERE id = ?{usize}"); defer stmt.deinit(); var row = try stmt.oneAlloc( struct { id: usize, name: []const u8, name_2: [200:0xAD]u8, age: usize, is_id: bool, weight: f64, }, &arena.allocator, .{}, .{ .id = @as(usize, 20) }, ); testing.expect(row != null); const exp = test_users[0]; testing.expectEqual(exp.id, row.?.id); testing.expectEqualStrings(exp.name, row.?.name); testing.expectEqualStrings(exp.name, mem.spanZ(&row.?.name_2)); testing.expectEqual(exp.age, row.?.age); testing.expect(row.?.is_id); testing.expectEqual(exp.weight, @floatCast(f32, row.?.weight)); } test "sqlite: read in a Text struct" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); var db: Db = undefined; try db.init(initOptions()); try addTestData(&db); var stmt = try db.prepare("SELECT id, name, age FROM user WHERE id = ?{usize}"); defer stmt.deinit(); var row = try stmt.oneAlloc( struct { id: usize, name: Text, age: usize, }, &arena.allocator, .{}, .{@as(usize, 20)}, ); testing.expect(row != null); const exp = test_users[0]; testing.expectEqual(exp.id, row.?.id); testing.expectEqualStrings(exp.name, row.?.name.data); testing.expectEqual(exp.age, row.?.age); } test "sqlite: read a single text value" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); var db: Db = undefined; try db.init(initOptions()); try addTestData(&db); const types = &[_]type{ // Slices []const u8, []u8, [:0]const u8, [:0]u8, [:0xAD]const u8, [:0xAD]u8, // Array [8:0]u8, [8:0xAD]u8, // Specific text or blob Text, Blob, }; inline for (types) |typ| { const query = "SELECT name FROM user WHERE id = ?{usize}"; var stmt: Statement(.{}, ParsedQuery.from(query)) = try db.prepare(query); defer stmt.deinit(); const name = try stmt.oneAlloc(typ, &arena.allocator, .{}, .{ .id = @as(usize, 20), }); testing.expect(name != null); switch (typ) { Text, Blob => { testing.expectEqualStrings("Vincent", name.?.data); }, else => { const span = blk: { const type_info = @typeInfo(typ); break :blk switch (type_info) { .Pointer => name.?, .Array => mem.spanZ(&(name.?)), else => @compileError("invalid type " ++ @typeName(typ)), }; }; testing.expectEqualStrings("Vincent", span); }, } } } test "sqlite: read a single integer value" { var db: Db = undefined; try db.init(initOptions()); try addTestData(&db); const types = &[_]type{ u8, u16, u32, u64, u128, usize, f16, f32, f64, f128, }; inline for (types) |typ| { const query = "SELECT age FROM user WHERE id = ?{usize}"; @setEvalBranchQuota(5000); var stmt: Statement(.{}, ParsedQuery.from(query)) = try db.prepare(query); defer stmt.deinit(); var age = try stmt.one(typ, .{}, .{ .id = @as(usize, 20), }); testing.expect(age != null); testing.expectEqual(@as(typ, 33), age.?); } } test "sqlite: read a single value into void" { var db: Db = undefined; try db.init(initOptions()); try addTestData(&db); const query = "SELECT age FROM user WHERE id = ?{usize}"; var stmt: Statement(.{}, ParsedQuery.from(query)) = try db.prepare(query); defer stmt.deinit(); _ = try stmt.one(void, .{}, .{ .id = @as(usize, 20), }); } test "sqlite: read a single value into bool" { var db: Db = undefined; try db.init(initOptions()); try addTestData(&db); const query = "SELECT id FROM user WHERE id = ?{usize}"; var stmt: Statement(.{}, ParsedQuery.from(query)) = try db.prepare(query); defer stmt.deinit(); const b = try stmt.one(bool, .{}, .{ .id = @as(usize, 20), }); testing.expect(b != null); testing.expect(b.?); } test "sqlite: insert bool and bind bool" { var db: Db = undefined; try db.init(initOptions()); try addTestData(&db); try db.exec("INSERT INTO article(id, author_id, is_published) VALUES(?{usize}, ?{usize}, ?{bool})", .{ .id = @as(usize, 1), .author_id = @as(usize, 20), .is_published = true, }); const query = "SELECT id FROM article WHERE is_published = ?{bool}"; var stmt: Statement(.{}, ParsedQuery.from(query)) = try db.prepare(query); defer stmt.deinit(); const b = try stmt.one(bool, .{}, .{ .is_published = true, }); testing.expect(b != null); testing.expect(b.?); } test "sqlite: bind string literal" { var db: Db = undefined; try db.init(initOptions()); try addTestData(&db); try db.exec("INSERT INTO article(id, data) VALUES(?, ?)", .{ @as(usize, 10), "foobar", }); const query = "SELECT id FROM article WHERE data = ?"; var stmt = try db.prepare(query); defer stmt.deinit(); const b = try stmt.one(usize, .{}, .{"foobar"}); testing.expect(b != null); testing.expectEqual(@as(usize, 10), b.?); } test "sqlite: bind pointer" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); var db: Db = undefined; try db.init(initOptions()); try addTestData(&db); const query = "SELECT name FROM user WHERE id = ?"; var stmt = try db.prepare(query); defer stmt.deinit(); for (test_users) |test_user, i| { stmt.reset(); const name = try stmt.oneAlloc([]const u8, &arena.allocator, .{}, .{&test_user.id}); testing.expect(name != null); testing.expectEqualStrings(test_users[i].name, name.?); } } test "sqlite: statement reset" { var db: Db = undefined; try db.init(initOptions()); try addTestData(&db); // Add data var stmt = try db.prepare("INSERT INTO user(id, name, age, weight) VALUES(?{usize}, ?{[]const u8}, ?{usize}, ?{f32})"); defer stmt.deinit(); const users = &[_]TestUser{ .{ .id = 200, .name = "Vincent", .age = 33, .weight = 10.0 }, .{ .id = 400, .name = "Julien", .age = 35, .weight = 12.0 }, .{ .id = 600, .name = "José", .age = 40, .weight = 14.0 }, }; for (users) |user| { stmt.reset(); try stmt.exec(user); const rows_inserted = db.rowsAffected(); testing.expectEqual(@as(usize, 1), rows_inserted); } } test "sqlite: statement iterator" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); var allocator = &arena.allocator; var db: Db = undefined; try db.init(initOptions()); try addTestData(&db); // Cleanup first try db.exec("DELETE FROM user", .{}); // Add data var stmt = try db.prepare("INSERT INTO user(id, name, age, weight) VALUES(?{usize}, ?{[]const u8}, ?{usize}, ?{f32})"); defer stmt.deinit(); var expected_rows = std.ArrayList(TestUser).init(allocator); var i: usize = 0; while (i < 20) : (i += 1) { const name = try std.fmt.allocPrint(allocator, "Vincent {d}", .{i}); const user = TestUser{ .id = i, .name = name, .age = i + 200, .weight = @intToFloat(f32, i + 200) }; try expected_rows.append(user); stmt.reset(); try stmt.exec(user); const rows_inserted = db.rowsAffected(); testing.expectEqual(@as(usize, 1), rows_inserted); } // Get data with a non-allocating iterator. { var stmt2 = try db.prepare("SELECT name, age FROM user"); defer stmt2.deinit(); const RowType = struct { name: [128:0]u8, age: usize, }; var iter = try stmt2.iterator(RowType, .{}); var rows = std.ArrayList(RowType).init(allocator); while (true) { const row = (try iter.next(.{})) orelse break; try rows.append(row); } // Check the data testing.expectEqual(expected_rows.items.len, rows.items.len); for (rows.items) |row, j| { const exp_row = expected_rows.items[j]; testing.expectEqualStrings(exp_row.name, mem.spanZ(&row.name)); testing.expectEqual(exp_row.age, row.age); } } // Get data with an iterator { var stmt2 = try db.prepare("SELECT name, age FROM user"); defer stmt2.deinit(); const RowType = struct { name: Text, age: usize, }; var iter = try stmt2.iterator(RowType, .{}); var rows = std.ArrayList(RowType).init(allocator); while (true) { const row = (try iter.nextAlloc(allocator, .{})) orelse break; try rows.append(row); } // Check the data testing.expectEqual(expected_rows.items.len, rows.items.len); for (rows.items) |row, j| { const exp_row = expected_rows.items[j]; testing.expectEqualStrings(exp_row.name, row.name.data); testing.expectEqual(exp_row.age, row.age); } } } test "sqlite: failing open" { var db: Db = undefined; const res = db.init(.{ .open_flags = .{}, .mode = .{ .File = "/tmp/not_existing.db" }, }); testing.expectError(error.SQLiteCantOpen, res); } test "sqlite: failing prepare statement" { var db: Db = undefined; try db.init(initOptions()); const result = db.prepare("SELECT id FROM foobar"); testing.expectError(error.SQLiteError, result); const detailed_err = db.getDetailedError(); testing.expectEqual(@as(usize, 1), detailed_err.code); testing.expectEqualStrings("no such table: foobar", detailed_err.message); } fn initOptions() InitOptions { return .{ .open_flags = .{ .write = true, .create = true, }, .mode = dbMode(), }; } fn dbMode() Db.Mode { return if (build_options.in_memory) blk: { break :blk .{ .Memory = {} }; } else blk: { const path = "/tmp/zig-sqlite.db"; std.fs.cwd().deleteFile(path) catch {}; break :blk .{ .File = path }; }; }
sqlite.zig
const std = @import("std"); const assert = std.debug.assert; const tools = @import("tools"); const Vec3 = struct { x: i32, y: i32, z: i32 }; const zero3 = Vec3{ .x = 0, .y = 0, .z = 0 }; const Bot = struct { p: Vec3, r: u31 }; fn dist(a: Vec3, b: Vec3) u32 { return @intCast(u32, (std.math.absInt(a.x - b.x) catch unreachable) + (std.math.absInt(a.y - b.y) catch unreachable) + (std.math.absInt(a.z - b.z) catch unreachable)); } fn axisRangeDist(p: i32, min: i32, max: i32) u32 { if (p > max) return @intCast(u32, p - max); if (p < min) return @intCast(u32, min - p); return 0; } fn countBots(corner: Vec3, size: u31, bots: []const Bot) u32 { const box_min = corner; const box_max = Vec3{ .x = corner.x + size - 1, .y = corner.y + size - 1, .z = corner.z + size - 1 }; var count: u32 = 0; for (bots) |b| { //const bot_min = Vec3{ .x = b.p.x - b.r, .y = b.p.y - b.r, .z = b.p.z - b.r }; //const bot_max = Vec3{ .x = b.p.x + b.r, .y = b.p.y + b.r, .z = b.p.z + b.r }; //if (bbox_min.x > bot_max.x or bbox_max.x < bot_min.x) continue; //if (bbox_min.y > bot_max.y or bbox_max.y < bot_min.y) continue; //if (bbox_min.z > bot_max.z or bbox_max.z < bot_min.z) continue; // cf "Graphics Gems" AABB intersects with a solid sphere <NAME> const d = axisRangeDist(b.p.x, box_min.x, box_max.x) + axisRangeDist(b.p.y, box_min.y, box_max.y) + axisRangeDist(b.p.z, box_min.z, box_max.z); if (d <= b.r) count += 1; } return count; } const Cell = struct { size: u31, corner: Vec3, population: u32, fn betterThan(_: void, a: @This(), b: @This()) std.math.Order { if (a.population > b.population) return .lt; if (a.population < b.population) return .gt; if (a.size < b.size) return .lt; if (a.size > b.size) return .gt; if (dist(zero3, a.corner) < dist(zero3, b.corner)) return .lt; return .gt; } }; pub fn run(input_text: []const u8, allocator: std.mem.Allocator) ![2][]const u8 { var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); const param: struct { bots: []Bot, largest_idx: usize, } = param: { var bots = std.ArrayList(Bot).init(arena.allocator()); var large_idx: usize = 0; var large_radius: u32 = 0; var it = std.mem.tokenize(u8, input_text, "\n\r"); while (it.next()) |line| { if (tools.match_pattern("pos=<{},{},{}>, r={}", line)) |fields| { const b = Bot{ .p = Vec3{ .x = @intCast(i32, fields[0].imm), .y = @intCast(i32, fields[1].imm), .z = @intCast(i32, fields[2].imm) }, .r = @intCast(u31, fields[3].imm), }; if (b.r > large_radius) { large_radius = b.r; large_idx = bots.items.len; } try bots.append(b); } else unreachable; } break :param .{ .bots = bots.items, .largest_idx = large_idx }; }; //std.debug.print("got {} bots, largest at {}\n", .{ param.bots.len, param.largest_idx }); const ans1 = ans: { var count: usize = 0; const center = param.bots[param.largest_idx]; for (param.bots) |b| { const d = dist(b.p, center.p); //std.debug.print(" dist= {} b.p={}, center.p={}, r={} \n", .{ d, b.p, center.p, center.r }); if (d <= center.r) count += 1; } break :ans count; }; const ans2 = ans: { //nb cet algo ne marche pas (bien du tout) si les sphres sont reparties de façon homogène (vu ue du coup il faut tout explorer en parallèle...) const global_size = 1024 * 1024 * 256; // à la louche, on pourrait examiner les données pour avoir la bbox précise var workqueue = std.PriorityQueue(Cell, void, Cell.betterThan).init(allocator, {}); defer workqueue.deinit(); { var cell0 = Cell{ .size = global_size, .corner = Vec3{ .x = -global_size / 2, .y = -global_size / 2, .z = -global_size / 2 }, .population = undefined, }; cell0.population = countBots(cell0.corner, cell0.size, param.bots); try workqueue.add(cell0); } while (workqueue.removeOrNull()) |cell| { //std.debug.print("examining {}...\n", .{cell}); if (cell.size == 1) break :ans dist(zero3, cell.corner); const step = (cell.size + 1) / 2; var subcell_idx: u32 = 0; while (subcell_idx < 8) : (subcell_idx += 1) { var x = subcell_idx % 2; var y = (subcell_idx / 2) % 2; var z = (subcell_idx / 4) % 2; const corner = Vec3{ .x = cell.corner.x + @intCast(i32, x * step), .y = cell.corner.y + @intCast(i32, y * step), .z = cell.corner.z + @intCast(i32, z * step) }; const count = countBots(corner, step, param.bots); try workqueue.add(Cell{ .size = step, .corner = corner, .population = count }); } } unreachable; }; return [_][]const u8{ try std.fmt.allocPrint(allocator, "{}", .{ans1}), try std.fmt.allocPrint(allocator, "{}", .{ans2}), }; } pub const main = tools.defaultMain("2018/input_day23.txt", run);
2018/day23.zig
const std = @import("std"); const assert = std.debug.assert; const print = std.debug.print; const tools = @import("tools"); const Property = enum { bludgeoning, radiation, cold, slashing, fire }; const Group = struct { unit_count: u16, unit_hp: u16, weak: []const Property, immune: []const Property, attack_prop: Property, attack_damage: u16, initiative: u8, }; fn computePotentialDamage(att: Group, tgt: Group) u32 { if (std.mem.indexOfScalar(Property, tgt.immune, att.attack_prop)) |_| return 0; const weak = std.mem.indexOfScalar(Property, tgt.weak, att.attack_prop) != null; const dmg = @as(u32, att.attack_damage) * att.unit_count; return if (weak) 2 * dmg else dmg; } fn betterEffectivePower(_: void, a: Group, b: Group) bool { const eff_a = @as(u32, a.attack_damage) * a.unit_count; const eff_b = @as(u32, b.attack_damage) * b.unit_count; if (eff_a > eff_b) return true; if (eff_a < eff_b) return false; if (a.initiative > b.initiative) return true; if (a.initiative < b.initiative) return false; unreachable; } fn doOneFight(armies: [2][]Group, allocator: std.mem.Allocator) ![2]u32 { //print("-- new fight ---\n", .{}); var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); const Attack = struct { army: u1, group: u8, initiative: u8, target: u8, fn betterInitiative(_: void, a: @This(), b: @This()) bool { return a.initiative > b.initiative; } }; // phase1 for (armies) |army| { std.sort.sort(Group, army, {}, betterEffectivePower); } var attacks = std.ArrayList(Attack).init(arena.allocator()); defer attacks.deinit(); for (armies) |army, i| { var potential_targets = std.ArrayList(?Group).init(arena.allocator()); defer potential_targets.deinit(); for (armies[1 - i]) |g| try potential_targets.append(if (g.unit_count > 0) g else null); for (army) |att, j| { // print("army {}, group {}, units: {}\n", .{ i, j, att.unit_count }); var best_tgt: ?usize = null; var best_potential_damage: u32 = 0; for (potential_targets.items) |tgt, k| { if (tgt) |t| { const damage = computePotentialDamage(att, t); if (damage > best_potential_damage) { best_potential_damage = damage; best_tgt = k; } } } if (best_tgt) |idx| { try attacks.append(Attack{ .army = @intCast(u1, i), .group = @intCast(u8, j), .initiative = att.initiative, .target = @intCast(u8, idx), }); potential_targets.items[idx] = null; } } } //phase 2 std.sort.sort(Attack, attacks.items, {}, Attack.betterInitiative); for (attacks.items) |attack| { const target = &armies[1 - attack.army][attack.target]; const dmg = computePotentialDamage(armies[attack.army][attack.group], target.*); const kills = @intCast(u16, dmg / target.unit_hp); // print(" attack: {}.{} -> {}, does {} damage: kills {} units\n", .{ attack.army, attack.group, attack.target, dmg, kills }); target.unit_count = if (target.unit_count > kills) target.unit_count - kills else 0; } var finalcounts = [2]u32{ 0, 0 }; for (armies) |army, i| { for (army) |group| finalcounts[i] += group.unit_count; } return finalcounts; } pub fn run(input_text: []const u8, allocator: std.mem.Allocator) ![2][]const u8 { var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); _ = input_text; const param: struct { immunesys: []const Group, infection: []const Group, } = .{ .immunesys = &[_]Group{ .{ .unit_count = 889, .unit_hp = 3275, .weak = &[_]Property{ .bludgeoning, .radiation }, .immune = &[_]Property{.cold}, .attack_damage = 36, .attack_prop = .bludgeoning, .initiative = 12 }, .{ .unit_count = 94, .unit_hp = 1336, .weak = &[_]Property{ .radiation, .cold }, .immune = &[_]Property{}, .attack_damage = 127, .attack_prop = .bludgeoning, .initiative = 7 }, .{ .unit_count = 1990, .unit_hp = 5438, .weak = &[_]Property{}, .immune = &[_]Property{}, .attack_damage = 25, .attack_prop = .slashing, .initiative = 20 }, .{ .unit_count = 1211, .unit_hp = 6640, .weak = &[_]Property{}, .immune = &[_]Property{}, .attack_damage = 54, .attack_prop = .fire, .initiative = 19 }, .{ .unit_count = 3026, .unit_hp = 7938, .weak = &[_]Property{.bludgeoning}, .immune = &[_]Property{.cold}, .attack_damage = 26, .attack_prop = .bludgeoning, .initiative = 16 }, .{ .unit_count = 6440, .unit_hp = 9654, .weak = &[_]Property{}, .immune = &[_]Property{}, .attack_damage = 14, .attack_prop = .fire, .initiative = 4 }, .{ .unit_count = 2609, .unit_hp = 8218, .weak = &[_]Property{.bludgeoning}, .immune = &[_]Property{}, .attack_damage = 28, .attack_prop = .cold, .initiative = 3 }, .{ .unit_count = 3232, .unit_hp = 11865, .weak = &[_]Property{.radiation}, .immune = &[_]Property{}, .attack_damage = 30, .attack_prop = .slashing, .initiative = 14 }, .{ .unit_count = 2835, .unit_hp = 7220, .weak = &[_]Property{}, .immune = &[_]Property{ .fire, .radiation }, .attack_damage = 18, .attack_prop = .bludgeoning, .initiative = 2 }, .{ .unit_count = 2570, .unit_hp = 4797, .weak = &[_]Property{.cold}, .immune = &[_]Property{}, .attack_damage = 15, .attack_prop = .radiation, .initiative = 17 }, }, .infection = &[_]Group{ .{ .unit_count = 333, .unit_hp = 44943, .weak = &[_]Property{.bludgeoning}, .immune = &[_]Property{}, .attack_damage = 223, .attack_prop = .slashing, .initiative = 13 }, .{ .unit_count = 1038, .unit_hp = 10867, .weak = &[_]Property{}, .immune = &[_]Property{ .bludgeoning, .slashing, .fire }, .attack_damage = 16, .attack_prop = .cold, .initiative = 8 }, .{ .unit_count = 57, .unit_hp = 50892, .weak = &[_]Property{}, .immune = &[_]Property{}, .attack_damage = 1732, .attack_prop = .cold, .initiative = 5 }, .{ .unit_count = 196, .unit_hp = 36139, .weak = &[_]Property{.cold}, .immune = &[_]Property{}, .attack_damage = 334, .attack_prop = .fire, .initiative = 6 }, .{ .unit_count = 2886, .unit_hp = 45736, .weak = &[_]Property{.slashing}, .immune = &[_]Property{.cold}, .attack_damage = 25, .attack_prop = .cold, .initiative = 1 }, .{ .unit_count = 4484, .unit_hp = 37913, .weak = &[_]Property{.bludgeoning}, .immune = &[_]Property{ .fire, .radiation, .slashing }, .attack_damage = 16, .attack_prop = .fire, .initiative = 18 }, .{ .unit_count = 1852, .unit_hp = 49409, .weak = &[_]Property{.radiation}, .immune = &[_]Property{.bludgeoning}, .attack_damage = 52, .attack_prop = .radiation, .initiative = 9 }, .{ .unit_count = 3049, .unit_hp = 18862, .weak = &[_]Property{.radiation}, .immune = &[_]Property{}, .attack_damage = 12, .attack_prop = .fire, .initiative = 10 }, .{ .unit_count = 1186, .unit_hp = 23898, .weak = &[_]Property{}, .immune = &[_]Property{.fire}, .attack_damage = 34, .attack_prop = .bludgeoning, .initiative = 15 }, .{ .unit_count = 6003, .unit_hp = 12593, .weak = &[_]Property{}, .immune = &[_]Property{}, .attack_damage = 2, .attack_prop = .cold, .initiative = 11 }, }, }; const param_example: struct { immunesys: []const Group, infection: []const Group, } = .{ .immunesys = &[_]Group{ .{ .unit_count = 17, .unit_hp = 5390, .weak = &[_]Property{ .bludgeoning, .radiation }, .immune = &[_]Property{}, .attack_damage = 4507, .attack_prop = .fire, .initiative = 2 }, .{ .unit_count = 989, .unit_hp = 1274, .weak = &[_]Property{ .bludgeoning, .slashing }, .immune = &[_]Property{}, .attack_damage = 25, .attack_prop = .slashing, .initiative = 3 }, }, .infection = &[_]Group{ .{ .unit_count = 801, .unit_hp = 4706, .weak = &[_]Property{.radiation}, .immune = &[_]Property{}, .attack_damage = 116, .attack_prop = .bludgeoning, .initiative = 1 }, .{ .unit_count = 4485, .unit_hp = 2961, .weak = &[_]Property{ .fire, .cold }, .immune = &[_]Property{.radiation}, .attack_damage = 12, .attack_prop = .slashing, .initiative = 4 }, }, }; _ = param_example; const ans1 = ans: { // 18531 toolow const armies = [2][]Group{ try arena.allocator().dupe(Group, param.immunesys), try arena.allocator().dupe(Group, param.infection), }; while (true) { const units_left = try doOneFight(armies, allocator); if (units_left[0] == 0) break :ans units_left[1]; if (units_left[1] == 0) break :ans units_left[0]; } }; const ans2 = ans: { var bracket_min: u16 = 0; var bracket_max: u16 = 50000; var immune_left: u32 = undefined; while (bracket_min + 1 < bracket_max) { const armies = [2][]Group{ try arena.allocator().dupe(Group, param.immunesys), try arena.allocator().dupe(Group, param.infection), }; defer arena.allocator().free(armies[0]); defer arena.allocator().free(armies[1]); const boost = (bracket_min + bracket_max + 1) / 2; for (armies[0]) |*it| it.attack_damage += boost; var prev: u32 = 0; const units_left = while (true) { const res = try doOneFight(armies, allocator); if (res[0] == 0 or res[1] == 0) break res; if (res[0] + res[1] == prev) break res; prev = res[0] + res[1]; } else unreachable; // print("boost: {} -> unitsleft:{} vs {}\n", .{ boost, units_left[0], units_left[1] }); if (units_left[1] != 0) { bracket_min = boost; } else { immune_left = units_left[0]; bracket_max = boost; } } break :ans immune_left; }; return [_][]const u8{ try std.fmt.allocPrint(allocator, "{}", .{ans1}), try std.fmt.allocPrint(allocator, "{}", .{ans2}), }; } pub const main = tools.defaultMain("2018/input_day23.txt", run);
2018/day24.zig
const std = @import("std"); const testing = std.testing; const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const FixedSieve = struct { const Self = @This(); allocator: *Allocator, arr: []bool, fn init(allocator: *Allocator, size: u32) !FixedSieve { var arr = try allocator.alloc(bool, size); var i: u32 = 0; while (i < size) : (i += 1) { arr[i] = i >= 2; } i = 2; while (i * i < size) : (i += 1) { var j: u32 = i * i; while (j < size) : (j += i) { arr[j] = false; } } return FixedSieve{ .allocator = allocator, .arr = arr, }; } fn deinit(self: *Self) void { self.allocator.free(self.arr); } fn is_prime(self: *Self, n: u32) SieveErr!bool { if (n >= self.arr.len) return SieveErr.OutOfBounds; return self.arr[n]; } }; const SieveErr = error{ OutOfBounds, }; const DynamicSieve = struct { const Self = @This(); arr: ArrayList(bool), fn init(allocator: *Allocator) DynamicSieve { return DynamicSieve{ .arr = ArrayList(bool).init(allocator), }; } fn deinit(self: *Self) void { self.arr.deinit(); } fn is_prime(self: *Self, n: u32) !bool { try self.expand(n); return self.arr.items[n]; } fn expand(self: *Self, n: u32) !void { if (n < self.arr.items.len) return; try self.arr.appendNTimes(true, n - self.arr.items.len + 1); var i: u32 = 2; while (i * i <= n) : (i += 1) { if (self.arr.items[i]) { var j: u32 = i * i; while (j <= n) : (j += i) { self.arr.items[j] = false; } } } } }; test "fixed smoke test" { var sieve = try FixedSieve.init(testing.allocator, 20); defer sieve.deinit(); const primes = [_]u32{ 2, 3, 5, 7, 11, 13, 17, 19 }; const composites = [_]u32{ 4, 6, 8, 9, 10, 12, 14, 15, 16, 18 }; for (primes) |p| { try testing.expect(try sieve.is_prime(p)); } for (composites) |c| { try testing.expect(!try sieve.is_prime(c)); } } test "fixed sieve has a limited range" { var sieve = try FixedSieve.init(testing.allocator, 20); defer sieve.deinit(); try std.testing.expectEqual(sieve.is_prime(50), SieveErr.OutOfBounds); } test "dynamic smoke test" { var sieve = DynamicSieve.init(testing.allocator); defer sieve.deinit(); const primes = [_]u32{ 2, 3, 5, 7, 11, 13, 17, 19 }; const composites = [_]u32{ 4, 6, 8, 9, 10, 12, 14, 15, 16, 18 }; for (primes) |p| { try testing.expect(try sieve.is_prime(p)); } for (composites) |c| { try testing.expect(!try sieve.is_prime(c)); } } test "dynamic sieve large numbers" { var sieve = DynamicSieve.init(testing.allocator); defer sieve.deinit(); try testing.expect(!try sieve.is_prime(1_000_000)); try testing.expect(try sieve.is_prime(999_983)); }
eratosthenes/src/main.zig
const std = @import("std"); pub const Mustache = struct { // TODO allow custom tags outside of {{}} const Self = @This(); pub const Error = error{ CouldNotFindFile, FileError, ArgsMustBeStruct, FileNotFound, MalformedFile, ExpectedOpenCurlyBrace, ExpectedCloseCurlyBrace, ExpectedEndSection, UnexpectedEOF, UnexpectedEndSection, UnexpectedNewline, MemoryError, }; const Value = struct { name: []const u8, }; const Section = struct { exists: bool, name: []const u8, contents: []const u8, pieces: Pieces, }; const Text = struct { contents: []const u8, }; const Include = struct { file: []const u8, }; const Piece = union(enum) { Text: Text, Value: Value, Section: Section, Include: Include, }; const Pieces = std.TailQueue(Piece); const File = struct { contents: []const u8, pieces: Pieces, }; allocator: *std.mem.Allocator, files: std.StringHashMap(File), line: usize = 1, column: usize = 0, pub fn init(allocator: *std.mem.Allocator) Self { return Self{ .allocator = allocator, .files = std.StringHashMap(File).init(allocator), .line = 1, .column = 0, }; } pub fn deinit(self: Self) void { var it = self.files.iterator(); while (it.next()) |file| { self.deinitPieces(&file.value.pieces); self.allocator.free(file.value.contents); } self.files.deinit(); } fn deinitPieces(self: Self, pieces: *Pieces) void { var it = pieces.first; while (it) |node| { var next = node.next; if (node.data == .Section) { self.deinitPieces(&node.data.Section.pieces); } pieces.destroyNode(node, self.allocator); it = next; } } fn errToString(err: anyerror) []const u8 { return switch (err) { Self.Error.ExpectedOpenCurlyBrace => "expected open curly brace", Self.Error.ExpectedCloseCurlyBrace => "expected close curly brace", Self.Error.ExpectedEndSection => "expected end of a section", Self.Error.UnexpectedEOF => "unexpected end of file", Self.Error.UnexpectedEndSection => "unexpected end of a section", Self.Error.UnexpectedNewline => "unexpected newline", else => @errorName(err), }; } pub fn printError(self: *Self, comptime OutStream: type, out: OutStream, err: anyerror) !void { try out.print("[{}:{}] {}\n", .{ self.line, self.column, Self.errToString(err) }); } pub fn render(self: *Self, comptime OutStream: type, out: OutStream, template: []const u8, args: var) Mustache.Error!void { var file = try self.retrieveFile(template); if (@typeInfo(@TypeOf(args)) != .Struct) { return Mustache.Error.ArgsMustBeStruct; } try self.renderPieces(OutStream, out, file.pieces, args); } fn renderPiece(self: *Self, comptime OutStream: type, out: OutStream, section: Section, global: var, value: var) Mustache.Error!void { const FieldInfo = @typeInfo(@TypeOf(value)); switch (FieldInfo) { .Pointer => |pointer| { if (pointer.size == .Slice) { if (pointer.child != u8) { for (value) |child| { const ChildInfo = @typeInfo(@TypeOf(child)); if (ChildInfo == .Struct) { try self.renderPieces(OutStream, out, section.pieces, child); } else { try self.renderPiece(OutStream, out, section.pieces, child); } } } else { // Assume a []u8 is a string try self.renderPieces(OutStream, out, section.pieces, global); } } else { try self.renderPiece(OutStream, out, section, global, value.*); } }, .Array => |array| { if (array.child != u8) { for (value) |child| { const ChildInfo = @typeInfo(@TypeOf(child)); if (ChildInfo == .Struct) { try self.renderPieces(OutStream, out, section.pieces, child); } else { try self.renderPiece(OutStream, out, section.pieces, child); } } } else { // Assume a []u8 is a string try self.renderPieces(OutStream, out, section.pieces, global); } }, .Fn => { try self.renderPieces(OutStream, out, section.pieces, field(section.contents)); }, .Bool => { if (value) { try self.renderPieces(OutStream, out, section.pieces, global); } }, .Optional => |opt| { if (value) |val| { const OptInfo = @typeInfo(opt.child); if (OptInfo == .Struct) { try self.renderPieces(OutStream, out, section.pieces, val); } else if ((OptInfo == .Pointer and OptInfo.Pointer.size == .Slice) or (OptInfo == .Array)) { try self.renderPiece(OutStream, out, section, global, val); } else { try self.renderPiece(OutStream, out, section, global, global); } } }, else => { try self.renderPieces(OutStream, out, section.pieces, value); }, } } fn renderPieces(self: *Self, comptime OutStream: type, out: OutStream, pieces: Pieces, args: var) Mustache.Error!void { // if (@typeInfo(@TypeOf(args)) != .Struct) { // return Mustache.Error.ArgsMustBeStruct; // } var it = pieces.first; piece_loop: while (it) |piece| : (it = piece.next) { switch (piece.data) { .Value => |value| { const ArgsInfo = @typeInfo(@TypeOf(args)); switch (ArgsInfo) { .Struct => { inline for (ArgsInfo.Struct.fields) |field| { if (std.mem.eql(u8, field.name, value.name)) { const field_value = @field(args, field.name); const field_type = @TypeOf(field_value); const field_info = @typeInfo(field_type); switch (field_info) { .Optional => { if (field_value) |data| { out.print("{}", .{data}) catch return Mustache.Error.FileError; } }, else => { out.print("{}", .{field_value}) catch return Mustache.Error.FileError; }, } // FIXME uncommenting this segfaults the compiler // continue :piece_loop; } } }, else => { out.print("{}", .{args}) catch return Mustache.Error.FileError; }, } }, .Text => |text| { out.writeAll(text.contents) catch return Mustache.Error.FileError; }, .Include => |include| { try self.render(OutStream, out, include.file, args); }, .Section => |section| { // Sections only work for structs const ArgsInfo = @typeInfo(@TypeOf(args)); if (ArgsInfo == .Struct) { var has_field = false; inline for (ArgsInfo.Struct.fields) |field| { if (std.mem.eql(u8, field.name, section.name)) { has_field = true; } } if (!section.exists) { if (!has_field) { try self.renderPieces(OutStream, out, section.pieces, args); } else { // Render if the field exists and is a false bool inline for (ArgsInfo.Struct.fields) |field| { if (std.mem.eql(u8, field.name, section.name)) { const field_info = @typeInfo(field.field_type); switch (field_info) { .Bool => { if (!@field(args, field.name)) { try self.renderPieces(OutStream, out, section.pieces, args); } }, else => {}, } } } } } else if (section.exists and has_field) { inline for (ArgsInfo.Struct.fields) |_field| { if (std.mem.eql(u8, _field.name, section.name)) { const field = @field(args, _field.name); try self.renderPiece(OutStream, out, section, args, field); } } } } }, } } } fn retrieveFile(self: *Self, template: []const u8) Mustache.Error!Mustache.File { var file: Mustache.File = undefined; if (self.files.get(template)) |parsed_file| { file = parsed_file.value; } else { var files = [_][]const u8{template}; try self.parse(files[0..]); var parsed_file = self.files.get(template).?; file = parsed_file.value; } return file; } // Parses all specified files and saves them in the object's cache // Useful for parsing all files before server is initialized to catch any syntax errors pub fn parse(self: *Self, files: [][]const u8) Mustache.Error!void { var line: usize = 1; var column: usize = 0; for (files) |file_name| { var file = std.fs.cwd().openFile(file_name, .{}) catch return Mustache.Error.CouldNotFindFile; defer file.close(); const contents = file.inStream().readAllAlloc(self.allocator, 1024 * 1024) catch return Mustache.Error.MemoryError; var pieces = try Mustache.innerParse(self.allocator, contents[0..], &line, &column); var parsed_file = File{ .contents = contents[0..], .pieces = pieces, }; _ = self.files.put(file_name, parsed_file) catch return Mustache.Error.MemoryError; } } fn innerParse(allocator: *std.mem.Allocator, contents: []const u8, line: *usize, column: *usize) Mustache.Error!Mustache.Pieces { var pieces = Mustache.Pieces.init(); var i: usize = 0; var start: usize = i; var end: usize = 0; while (i < contents.len) { if (contents[i] == '{') { end = i; i += 1; if (i < contents.len and contents[i] == '{') { column.* += 2; if (end - start > 0) { var part = pieces.createNode(Piece{ .Text = .{ .contents = contents[start..end], }, }, allocator) catch return Mustache.Error.MemoryError; pieces.append(part); for (contents[start..end]) |c| { if (c == '\n') { line.* += 1; column.* = 0; } column.* += 1; } } i += 1; if (i >= contents.len) { return Mustache.Error.UnexpectedEOF; } if (contents[i] == '#' or contents[i] == '^') { var exists: bool = contents[i] == '#'; i += 1; column.* += 1; var end_tag: usize = 0; var identifier = getIdentifier(contents[i..], 2, &end_tag) catch |err| { column.* += end_tag; return err; }; i += end_tag; column.* += end_tag; if (i < contents.len and (contents[i] == '\n' or contents[i] == '\r')) { if (contents[i] == '\r') { i += 1; } i += 1; line.* += 1; column.* = 1; if (i >= contents.len) { return Mustache.Error.UnexpectedEOF; } } start = i; var end_section: usize = 0; end = getSectionEnd(identifier, contents[start..], &end_section) catch |err| { column.* += end; return err; }; end += start; var parsed_section = innerParse(allocator, contents[start..end], line, column) catch |err| { return err; }; var new_section = Piece{ .Section = .{ .exists = exists, .name = identifier, .contents = contents[start..end], .pieces = parsed_section, }, }; var new_node = pieces.createNode(new_section, allocator) catch return Mustache.Error.MemoryError; pieces.append(new_node); i += end_section; if (i < contents.len and (contents[i] == '\n' or contents[i] == '\r')) { if (contents[i] == '\r') { i += 1; } i += 1; line.* += 1; column.* = 1; } start = i; continue; } else if (contents[i] == '!') { // Parse comment until it reaches }} var has_curly = false; i += 1; column.* += 1; while (i < contents.len) { if (contents[i] == '}') { i += 1; if (i < contents.len and contents[i] == '}') { i += 1; column.* += 1; has_curly = true; break; } } else if (contents[i] == '\n') { line.* += 1; column.* = 0; } i += 1; column.* += 1; } if (!has_curly) { return Mustache.Error.ExpectedCloseCurlyBrace; } start = i; } else if (contents[i] == '/') { column.* += 1; return Mustache.Error.UnexpectedEndSection; } else if (contents[i] == '>') { i += 1; column.* += 1; var end_tag: usize = 0; var identifier = getIdentifier(contents[i..], 2, &end_tag) catch |err| { column.* += end_tag; return err; }; column.* += end_tag; var file = Piece{ .Include = .{ .file = identifier } }; var node = pieces.createNode(file, allocator) catch return Mustache.Error.MemoryError; pieces.append(node); if (i < contents.len and (contents[i] == '\n' or contents[i] == '\r')) { if (contents[i] == '\r') { i += 1; } i += 1; line.* += 1; column.* = 1; } start = i + end_tag; } else { var end_tag: usize = 0; var identifier = getIdentifier(contents[i..], 2, &end_tag) catch |err| { column.* += end_tag; return err; }; column.* += end_tag; var value = Piece{ .Value = .{ .name = identifier } }; var node = pieces.createNode(value, allocator) catch return Mustache.Error.MemoryError; pieces.append(node); if (i < contents.len and (contents[i] == '\n' or contents[i] == '\r')) { if (contents[i] == '\r') { i += 1; } i += 1; line.* += 1; column.* = 1; } start = i + end_tag; } } else { column.* += 1; return Mustache.Error.ExpectedOpenCurlyBrace; } } column.* += 1; i += 1; } if (end == 0 or end != contents.len) { var part = Piece{ .Text = .{ .contents = contents[start..] } }; var node = pieces.createNode(part, allocator) catch return Mustache.Error.MemoryError; pieces.append(node); } return pieces; } }; fn getIdentifier(content: []const u8, amount_of_closing: usize, ending: ?*usize) Mustache.Error![]const u8 { var num: usize = 0; var start: usize = 0; var has_ident = false; var end: usize = 0; var i: usize = 0; while (i < content.len) : (i += 1) { if (content[i] == '}') { if (end == 0) { end = i; } num = 0; while (num != amount_of_closing) : (num += 1) { if (i + num >= content.len or content[i + num] != '}') { if (ending) |val| { val.* = i + num; } return Mustache.Error.ExpectedCloseCurlyBrace; } } break; } else if (content[i] == '\n') { if (ending) |val| { val.* = i + num; } return Mustache.Error.UnexpectedNewline; } else if (content[i] == ' ') { if (has_ident and end == 0) { end = i; } } else if (!has_ident) { has_ident = true; start = i; } } if (i >= content.len and num != amount_of_closing) { return Mustache.Error.ExpectedCloseCurlyBrace; } if (ending) |val| { val.* = i + num; } return content[start..end]; } test "getIdentifier" { var ident = try getIdentifier("foo }}", 2, null); std.testing.expect(std.mem.eql(u8, ident, "foo")); var ident2 = try getIdentifier("foo}}", 2, null); std.testing.expect(std.mem.eql(u8, ident2, "foo")); } fn getSectionEnd(identifier: []const u8, content: []const u8, end: *usize) Mustache.Error!usize { var needed: usize = 1; var start: usize = 0; var i: usize = 0; while (i < content.len) { if (content[i] == '{') { start = i; if (i + 1 >= content.len or content[i + 1] != '{') { end.* = i + 1; return Mustache.Error.ExpectedOpenCurlyBrace; } i += 1; if (i + 1 >= content.len) { end.* = i; return Mustache.Error.UnexpectedEOF; } i += 1; if (content[i] == '#') { i += 1; var end_tag: usize = i; var ident = try getIdentifier(content[i..], 2, &end_tag); i += end_tag; if (std.mem.eql(u8, ident, identifier)) { needed += 1; } continue; } else if (content[i] == '/') { i += 1; var end_tag: usize = 0; var ident = try getIdentifier(content[i..], 2, &end_tag); i += end_tag; if (std.mem.eql(u8, ident, identifier)) { needed -= 1; if (needed == 0) { end.* = i; return start; } } continue; } } i += 1; } return Mustache.Error.ExpectedEndSection; } test "Mustache" { std.meta.refAllDecls(Mustache); var result = std.ArrayList(u8).init(std.testing.allocator); defer result.deinit(); var out_stream = result.outStream(); var mustache = Mustache.init(std.testing.allocator); defer mustache.deinit(); try mustache.render(@TypeOf(out_stream), out_stream, "tests/test1.must", .{ .foo = 69, .bar = .{ .thing = 10 }, .not_bar = false }); var expect = \\foo \\69 \\42 \\30 \\ ; std.testing.expect(std.mem.eql(u8, result.items[0..], expect)); }
src/mustache.zig
const std = @import("std"); const pike = @import("pike"); const clap = @import("clap"); const ray = @import("ray.zig"); const udev = @import("udev.zig"); const mt = @import("multitouch.zig"); const dim = @import("dimensions.zig"); const MAGENTA = ray.Color{ .r = 255, .g = 0, .b = 182, .a = 255 }; const TEAL = ray.Color{ .r = 0, .g = 213, .b = 255, .a = 255 }; const ORANGE = ray.Color{ .r = 255, .g = 101, .b = 0, .a = 255 }; const YELLOW = ray.Color{ .r = 245, .g = 215, .b = 0, .a = 255 }; const HISTORY_MAX = 20; var machine = mt.MTStateMachine{}; var touch_history: [HISTORY_MAX][mt.MAX_TOUCH_POINTS]mt.TouchData = [1][mt.MAX_TOUCH_POINTS]mt.TouchData{[1]mt.TouchData{std.mem.zeroes(mt.TouchData)} ** mt.MAX_TOUCH_POINTS} ** HISTORY_MAX; var dims = dim.Dimensions{ .screen_width = 672, .screen_height = 432, .touchpad_max_extent_x = 1345.0, .touchpad_max_extent_y = 865.0, .margin = 15, }; const Opts = struct { trails: u32, top_window: bool, verbose: bool, }; var opts = Opts{ .trails = 20, .top_window = true, .verbose = false, }; pub fn main() !void { const params = comptime [_]clap.Param(clap.Help){ clap.parseParam("-h, --help Display this help and exit.") catch unreachable, clap.parseParam("-t, --trails <NUM> Show trails per touch point (default: 20)") catch unreachable, clap.parseParam("-w, --top-window <t|f> Set topmost window flag (default: t)") catch unreachable, clap.parseParam("-v, --verbose Show all kernel multitouch events") catch unreachable, }; var diag = clap.Diagnostic{}; var args = clap.parse(clap.Help, &params, .{ .diagnostic = &diag }) catch |err| { diag.report(std.io.getStdErr().writer(), err) catch {}; return err; }; defer args.deinit(); if (args.flag("--help")) { try clap.help(std.io.getStdErr().writer(), &params); std.os.exit(1); } if (args.option("--trails")) |n| { opts.trails = try std.fmt.parseInt(u32, n, 10); if (opts.trails > HISTORY_MAX) opts.trails = HISTORY_MAX; } if (args.option("--top-window")) |b| { opts.top_window = std.mem.eql(u8, b, "t") or std.mem.eql(u8, b, "true"); } if (args.flag("--verbose")) { opts.verbose = true; } try pike.init(); defer pike.deinit(); const notifier = try pike.Notifier.init(); defer notifier.deinit(); const fd: std.os.fd_t = udev.open_touchpad() catch |err| { std.debug.print("Unable to open touchpad: {s}\n", .{err}); std.os.exit(1); }; defer udev.close_touchpad(fd); // Initialize visual initWindow(dims.screen_width, dims.screen_height, opts.top_window); defer ray.CloseWindow(); const handle: pike.Handle = .{ .inner = fd, .wake_fn = wake }; try notifier.register(&handle, .{ .read = true, .write = false }); var grabbed: bool = false; while (true) { if (ray.IsWindowResized()) { dims.screen_width = @intToFloat(f32, ray.GetScreenWidth()); dims.screen_height = @intToFloat(f32, ray.GetScreenHeight()); } // Max poll time must be less than 16.6ms so we can animate at 60fps try notifier.poll(10); if (ray.IsKeyPressed(ray.KEY_ENTER) and !grabbed) { try udev.grab(fd); grabbed = true; ray.SetExitKey(0); } else if (ray.IsKeyPressed(ray.KEY_ESCAPE) and grabbed) { try udev.ungrab(fd); grabbed = false; ray.SetExitKey(ray.KEY_ESCAPE); } else if (ray.WindowShouldClose()) { break; } { const scale = dims.getTouchpadScale(); const corner = dims.getTouchpadCorner(scale); // Get max extents first for (machine.touches) |touch| { const pos = getPosFromTouch(&touch); dims.maybeGrowTouchpadExtent(pos.x, pos.y); } ray.BeginDrawing(); defer ray.EndDrawing(); ray.ClearBackground(ray.WHITE); ray.DrawRectangleLines( @floatToInt(c_int, corner.x), @floatToInt(c_int, corner.y), @floatToInt(c_int, dims.touchpad_max_extent_x * scale), @floatToInt(c_int, dims.touchpad_max_extent_y * scale), ORANGE, ); // Draw historical touch data for (touch_history) |touches, h| { if (h >= opts.trails) break; for (touches) |touch, i| { if (!touch.used) continue; var pos = getPosFromTouch(&touch); pos.x = corner.x + pos.x * scale; pos.y = corner.y + pos.y * scale; const cscale = std.math.clamp(scale, 0.5, 2); ray.DrawRing( pos, 1, 36 * cscale, 0, 360, 64, if (i == 0) ray.Fade(MAGENTA, 0.2) else ray.Fade(TEAL, 0.2), ); } } // Draw current touch data for (machine.touches) |touch, i| { if (!touch.used) continue; var pos = getPosFromTouch(&touch); pos.x = corner.x + pos.x * scale; pos.y = corner.y + pos.y * scale; const cscale = std.math.clamp(scale, 0.5, 2); ray.DrawCircleV( pos, 34 * cscale, if (i == 0) MAGENTA else TEAL, ); if (touch.pressed_double) { ray.DrawRing( pos, 14 * cscale, // inner radius 20 * cscale, // outer radius 0, // arc begin 360, // arc end 64, // line segments ray.BLACK, ); } if (touch.pressed) { ray.DrawCircleV(pos, 8 * cscale, ray.BLACK); } ray.DrawText( ray.TextFormat("%d", i), @floatToInt(c_int, pos.x - 10 * cscale), @floatToInt(c_int, pos.y - 70 * cscale), @floatToInt(c_int, 40.0 * cscale), ray.BLACK, ); } // Pump history { var i: usize = HISTORY_MAX - 1; while (i > 0) : (i -= 1) { std.mem.copy( mt.TouchData, touch_history[i][0..], touch_history[i - 1][0..], ); } std.mem.copy( mt.TouchData, touch_history[0][0..], machine.touches[0..], ); } if (ray.IsWindowFocused()) { const width = @intToFloat(f32, ray.MeasureText("Press ENTER to grab touchpad", 30)); const font_size: i32 = if (width + dims.margin * 2 > dims.touchpad_max_extent_x * scale) 10 else 30; if (grabbed) { ray.DrawTextCentered( "Press ESC to restore focus", @floatToInt(c_int, dims.screen_width / 2), @floatToInt(c_int, dims.screen_height / 2), font_size, ray.GRAY, ); } else { ray.DrawTextCentered( "Press ENTER to grab touchpad", @floatToInt(c_int, dims.screen_width / 2), @floatToInt(c_int, dims.screen_height / 2), font_size, ray.GRAY, ); } } } } } fn wake(handle: *pike.Handle, batch: *pike.Batch, pike_opts: pike.WakeOptions) void { var events: [100]mt.InputEvent = undefined; if (pike_opts.read_ready) { const bytes = std.os.read( handle.inner, std.mem.sliceAsBytes(events[0..]), ) catch 0; if (bytes == 0) { std.debug.print("read 0 bytes\n", .{}); return; } const inputEventSize: usize = @intCast(usize, @sizeOf(mt.InputEvent)); const eventCount: usize = @divExact(bytes, inputEventSize); if (opts.verbose) std.debug.print("Received {} bytes:", .{bytes}); for (events[0..eventCount]) |event| { if (opts.verbose) event.print(); machine.process(&event) catch |err| { std.debug.print("can't process: {}\n", .{err}); }; } } _ = batch; } fn getPosFromTouch(touch: *const mt.TouchData) ray.Vector2 { return ray.Vector2{ .x = @intToFloat(f32, touch.position_x), .y = @intToFloat(f32, touch.position_y), }; } fn initWindow(screen_width: f32, screen_height: f32, top_window: bool) void { var flags: c_uint = // ray.FLAG_WINDOW_RESIZABLE | ray.FLAG_VSYNC_HINT | ray.FLAG_MSAA_4X_HINT; if (top_window) flags |= ray.FLAG_WINDOW_TOPMOST; ray.SetConfigFlags(flags); ray.InitWindow( @floatToInt(c_int, screen_width), @floatToInt(c_int, screen_height), "Cleartouch - Touchpad Visualizer", ); ray.SetWindowMinSize(320, 240); ray.SetTargetFPS(60); }
src/main.zig
const std = @import("std"); const builtin = @import("builtin"); const stdx = @import("stdx.zig"); extern "stdx" fn jsWarn(ptr: [*]const u8, len: usize) void; extern "stdx" fn jsLog(ptr: [*]const u8, len: usize) void; extern "stdx" fn jsErr(ptr: [*]const u8, len: usize) void; pub fn scoped(comptime Scope: @Type(.EnumLiteral)) type { return struct { pub fn debug( comptime format: []const u8, args: anytype, ) void { if (builtin.mode == .Debug) { const prefix = if (Scope == .default) ": " else "(" ++ @tagName(Scope) ++ "): "; const js_buf = &stdx.wasm.js_buffer; js_buf.output_buf.clearRetainingCapacity(); std.fmt.format(js_buf.output_writer, "debug" ++ prefix ++ format, args) catch unreachable; jsLog(js_buf.output_buf.items.ptr, js_buf.output_buf.items.len); } } pub fn info( comptime format: []const u8, args: anytype, ) void { const prefix = if (Scope == .default) ": " else "(" ++ @tagName(Scope) ++ "): "; const js_buf = &stdx.wasm.js_buffer; js_buf.output_buf.clearRetainingCapacity(); std.fmt.format(js_buf.output_writer, prefix ++ format, args) catch unreachable; jsLog(js_buf.output_buf.items.ptr, js_buf.output_buf.items.len); } pub fn warn( comptime format: []const u8, args: anytype, ) void { const prefix = if (Scope == .default) ": " else "(" ++ @tagName(Scope) ++ "): "; const js_buf = &stdx.wasm.js_buffer; js_buf.output_buf.clearRetainingCapacity(); std.fmt.format(js_buf.output_writer, prefix ++ format, args) catch unreachable; jsWarn(js_buf.output_buf.items.ptr, js_buf.output_buf.items.len); } pub fn err( comptime format: []const u8, args: anytype, ) void { const prefix = if (Scope == .default) ": " else "(" ++ @tagName(Scope) ++ "): "; const js_buf = &stdx.wasm.js_buffer; js_buf.output_buf.clearRetainingCapacity(); std.fmt.format(js_buf.output_writer, prefix ++ format, args) catch unreachable; jsErr(js_buf.output_buf.items.ptr, js_buf.output_buf.items.len); } }; }
stdx/log_wasm.zig
const builtin = @import("builtin"); const std = @import("../../std.zig"); const assert = std.debug.assert; const maxInt = std.math.maxInt; pub const ERROR = @import("error.zig"); pub const STATUS = @import("status.zig"); pub const LANG = @import("lang.zig"); pub const SUBLANG = @import("sublang.zig"); /// The standard input device. Initially, this is the console input buffer, CONIN$. pub const STD_INPUT_HANDLE = maxInt(DWORD) - 10 + 1; /// The standard output device. Initially, this is the active console screen buffer, CONOUT$. pub const STD_OUTPUT_HANDLE = maxInt(DWORD) - 11 + 1; /// The standard error device. Initially, this is the active console screen buffer, CONOUT$. pub const STD_ERROR_HANDLE = maxInt(DWORD) - 12 + 1; pub const BOOL = c_int; pub const BOOLEAN = BYTE; pub const BYTE = u8; pub const CHAR = u8; pub const DWORD = u32; pub const FLOAT = f32; pub const HANDLE = *c_void; pub const HCRYPTPROV = ULONG_PTR; pub const HINSTANCE = *@OpaqueType(); pub const HMODULE = *@OpaqueType(); pub const FARPROC = *@OpaqueType(); pub const INT = c_int; pub const LPBYTE = *BYTE; pub const LPCH = *CHAR; pub const LPCSTR = [*:0]const CHAR; pub const LPCTSTR = [*:0]const TCHAR; pub const LPCVOID = *const c_void; pub const LPDWORD = *DWORD; pub const LPSTR = [*:0]CHAR; pub const LPTSTR = if (UNICODE) LPWSTR else LPSTR; pub const LPVOID = *c_void; pub const LPWSTR = [*:0]WCHAR; pub const LPCWSTR = [*:0]const WCHAR; pub const PVOID = *c_void; pub const PWSTR = [*:0]WCHAR; pub const SIZE_T = usize; pub const TCHAR = if (UNICODE) WCHAR else u8; pub const UINT = c_uint; pub const ULONG_PTR = usize; pub const DWORD_PTR = ULONG_PTR; pub const UNICODE = false; pub const WCHAR = u16; pub const WORD = u16; pub const LARGE_INTEGER = i64; pub const USHORT = u16; pub const SHORT = i16; pub const ULONG = u32; pub const LONG = i32; pub const ULONGLONG = u64; pub const LONGLONG = i64; pub const HLOCAL = HANDLE; pub const LANGID = c_ushort; pub const NTSTATUS = ULONG; pub const va_list = *@OpaqueType(); pub const TRUE = 1; pub const FALSE = 0; pub const DEVICE_TYPE = ULONG; pub const FILE_DEVICE_BEEP: DEVICE_TYPE = 0x0001; pub const FILE_DEVICE_CD_ROM: DEVICE_TYPE = 0x0002; pub const FILE_DEVICE_CD_ROM_FILE_SYSTEM: DEVICE_TYPE = 0x0003; pub const FILE_DEVICE_CONTROLLER: DEVICE_TYPE = 0x0004; pub const FILE_DEVICE_DATALINK: DEVICE_TYPE = 0x0005; pub const FILE_DEVICE_DFS: DEVICE_TYPE = 0x0006; pub const FILE_DEVICE_DISK: DEVICE_TYPE = 0x0007; pub const FILE_DEVICE_DISK_FILE_SYSTEM: DEVICE_TYPE = 0x0008; pub const FILE_DEVICE_FILE_SYSTEM: DEVICE_TYPE = 0x0009; pub const FILE_DEVICE_INPORT_PORT: DEVICE_TYPE = 0x000a; pub const FILE_DEVICE_KEYBOARD: DEVICE_TYPE = 0x000b; pub const FILE_DEVICE_MAILSLOT: DEVICE_TYPE = 0x000c; pub const FILE_DEVICE_MIDI_IN: DEVICE_TYPE = 0x000d; pub const FILE_DEVICE_MIDI_OUT: DEVICE_TYPE = 0x000e; pub const FILE_DEVICE_MOUSE: DEVICE_TYPE = 0x000f; pub const FILE_DEVICE_MULTI_UNC_PROVIDER: DEVICE_TYPE = 0x0010; pub const FILE_DEVICE_NAMED_PIPE: DEVICE_TYPE = 0x0011; pub const FILE_DEVICE_NETWORK: DEVICE_TYPE = 0x0012; pub const FILE_DEVICE_NETWORK_BROWSER: DEVICE_TYPE = 0x0013; pub const FILE_DEVICE_NETWORK_FILE_SYSTEM: DEVICE_TYPE = 0x0014; pub const FILE_DEVICE_NULL: DEVICE_TYPE = 0x0015; pub const FILE_DEVICE_PARALLEL_PORT: DEVICE_TYPE = 0x0016; pub const FILE_DEVICE_PHYSICAL_NETCARD: DEVICE_TYPE = 0x0017; pub const FILE_DEVICE_PRINTER: DEVICE_TYPE = 0x0018; pub const FILE_DEVICE_SCANNER: DEVICE_TYPE = 0x0019; pub const FILE_DEVICE_SERIAL_MOUSE_PORT: DEVICE_TYPE = 0x001a; pub const FILE_DEVICE_SERIAL_PORT: DEVICE_TYPE = 0x001b; pub const FILE_DEVICE_SCREEN: DEVICE_TYPE = 0x001c; pub const FILE_DEVICE_SOUND: DEVICE_TYPE = 0x001d; pub const FILE_DEVICE_STREAMS: DEVICE_TYPE = 0x001e; pub const FILE_DEVICE_TAPE: DEVICE_TYPE = 0x001f; pub const FILE_DEVICE_TAPE_FILE_SYSTEM: DEVICE_TYPE = 0x0020; pub const FILE_DEVICE_TRANSPORT: DEVICE_TYPE = 0x0021; pub const FILE_DEVICE_UNKNOWN: DEVICE_TYPE = 0x0022; pub const FILE_DEVICE_VIDEO: DEVICE_TYPE = 0x0023; pub const FILE_DEVICE_VIRTUAL_DISK: DEVICE_TYPE = 0x0024; pub const FILE_DEVICE_WAVE_IN: DEVICE_TYPE = 0x0025; pub const FILE_DEVICE_WAVE_OUT: DEVICE_TYPE = 0x0026; pub const FILE_DEVICE_8042_PORT: DEVICE_TYPE = 0x0027; pub const FILE_DEVICE_NETWORK_REDIRECTOR: DEVICE_TYPE = 0x0028; pub const FILE_DEVICE_BATTERY: DEVICE_TYPE = 0x0029; pub const FILE_DEVICE_BUS_EXTENDER: DEVICE_TYPE = 0x002a; pub const FILE_DEVICE_MODEM: DEVICE_TYPE = 0x002b; pub const FILE_DEVICE_VDM: DEVICE_TYPE = 0x002c; pub const FILE_DEVICE_MASS_STORAGE: DEVICE_TYPE = 0x002d; pub const FILE_DEVICE_SMB: DEVICE_TYPE = 0x002e; pub const FILE_DEVICE_KS: DEVICE_TYPE = 0x002f; pub const FILE_DEVICE_CHANGER: DEVICE_TYPE = 0x0030; pub const FILE_DEVICE_SMARTCARD: DEVICE_TYPE = 0x0031; pub const FILE_DEVICE_ACPI: DEVICE_TYPE = 0x0032; pub const FILE_DEVICE_DVD: DEVICE_TYPE = 0x0033; pub const FILE_DEVICE_FULLSCREEN_VIDEO: DEVICE_TYPE = 0x0034; pub const FILE_DEVICE_DFS_FILE_SYSTEM: DEVICE_TYPE = 0x0035; pub const FILE_DEVICE_DFS_VOLUME: DEVICE_TYPE = 0x0036; pub const FILE_DEVICE_SERENUM: DEVICE_TYPE = 0x0037; pub const FILE_DEVICE_TERMSRV: DEVICE_TYPE = 0x0038; pub const FILE_DEVICE_KSEC: DEVICE_TYPE = 0x0039; pub const FILE_DEVICE_FIPS: DEVICE_TYPE = 0x003a; pub const FILE_DEVICE_INFINIBAND: DEVICE_TYPE = 0x003b; // TODO: missing values? pub const FILE_DEVICE_VMBUS: DEVICE_TYPE = 0x003e; pub const FILE_DEVICE_CRYPT_PROVIDER: DEVICE_TYPE = 0x003f; pub const FILE_DEVICE_WPD: DEVICE_TYPE = 0x0040; pub const FILE_DEVICE_BLUETOOTH: DEVICE_TYPE = 0x0041; pub const FILE_DEVICE_MT_COMPOSITE: DEVICE_TYPE = 0x0042; pub const FILE_DEVICE_MT_TRANSPORT: DEVICE_TYPE = 0x0043; pub const FILE_DEVICE_BIOMETRIC: DEVICE_TYPE = 0x0044; pub const FILE_DEVICE_PMI: DEVICE_TYPE = 0x0045; pub const FILE_DEVICE_EHSTOR: DEVICE_TYPE = 0x0046; pub const FILE_DEVICE_DEVAPI: DEVICE_TYPE = 0x0047; pub const FILE_DEVICE_GPIO: DEVICE_TYPE = 0x0048; pub const FILE_DEVICE_USBEX: DEVICE_TYPE = 0x0049; pub const FILE_DEVICE_CONSOLE: DEVICE_TYPE = 0x0050; pub const FILE_DEVICE_NFP: DEVICE_TYPE = 0x0051; pub const FILE_DEVICE_SYSENV: DEVICE_TYPE = 0x0052; pub const FILE_DEVICE_VIRTUAL_BLOCK: DEVICE_TYPE = 0x0053; pub const FILE_DEVICE_POINT_OF_SERVICE: DEVICE_TYPE = 0x0054; pub const FILE_DEVICE_STORAGE_REPLICATION: DEVICE_TYPE = 0x0055; pub const FILE_DEVICE_TRUST_ENV: DEVICE_TYPE = 0x0056; pub const FILE_DEVICE_UCM: DEVICE_TYPE = 0x0057; pub const FILE_DEVICE_UCMTCPCI: DEVICE_TYPE = 0x0058; pub const FILE_DEVICE_PERSISTENT_MEMORY: DEVICE_TYPE = 0x0059; pub const FILE_DEVICE_NVDIMM: DEVICE_TYPE = 0x005a; pub const FILE_DEVICE_HOLOGRAPHIC: DEVICE_TYPE = 0x005b; pub const FILE_DEVICE_SDFXHCI: DEVICE_TYPE = 0x005c; /// https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/buffer-descriptions-for-i-o-control-codes pub const TransferType = enum(u2) { METHOD_BUFFERED = 0, METHOD_IN_DIRECT = 1, METHOD_OUT_DIRECT = 2, METHOD_NEITHER = 3, }; pub const FILE_ANY_ACCESS = 0; pub const FILE_READ_ACCESS = 1; pub const FILE_WRITE_ACCESS = 2; /// https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/defining-i-o-control-codes pub fn CTL_CODE(deviceType: u16, function: u12, method: TransferType, access: u2) DWORD { return (@as(DWORD, deviceType) << 16) | (@as(DWORD, access) << 14) | (@as(DWORD, function) << 2) | @enumToInt(method); } pub const INVALID_HANDLE_VALUE = @intToPtr(HANDLE, maxInt(usize)); pub const INVALID_FILE_ATTRIBUTES = @as(DWORD, maxInt(DWORD)); pub const FILE_ALL_INFORMATION = extern struct { BasicInformation: FILE_BASIC_INFORMATION, StandardInformation: FILE_STANDARD_INFORMATION, InternalInformation: FILE_INTERNAL_INFORMATION, EaInformation: FILE_EA_INFORMATION, AccessInformation: FILE_ACCESS_INFORMATION, PositionInformation: FILE_POSITION_INFORMATION, ModeInformation: FILE_MODE_INFORMATION, AlignmentInformation: FILE_ALIGNMENT_INFORMATION, NameInformation: FILE_NAME_INFORMATION, }; pub const FILE_BASIC_INFORMATION = extern struct { CreationTime: LARGE_INTEGER, LastAccessTime: LARGE_INTEGER, LastWriteTime: LARGE_INTEGER, ChangeTime: LARGE_INTEGER, FileAttributes: ULONG, }; pub const FILE_STANDARD_INFORMATION = extern struct { AllocationSize: LARGE_INTEGER, EndOfFile: LARGE_INTEGER, NumberOfLinks: ULONG, DeletePending: BOOLEAN, Directory: BOOLEAN, }; pub const FILE_INTERNAL_INFORMATION = extern struct { IndexNumber: LARGE_INTEGER, }; pub const FILE_EA_INFORMATION = extern struct { EaSize: ULONG, }; pub const FILE_ACCESS_INFORMATION = extern struct { AccessFlags: ACCESS_MASK, }; pub const FILE_POSITION_INFORMATION = extern struct { CurrentByteOffset: LARGE_INTEGER, }; pub const FILE_MODE_INFORMATION = extern struct { Mode: ULONG, }; pub const FILE_ALIGNMENT_INFORMATION = extern struct { AlignmentRequirement: ULONG, }; pub const FILE_NAME_INFORMATION = extern struct { FileNameLength: ULONG, FileName: [1]WCHAR, }; pub const IO_STATUS_BLOCK = extern struct { // "DUMMYUNIONNAME" expands to "u" u: extern union { Status: NTSTATUS, Pointer: ?*c_void, }, Information: ULONG_PTR, }; pub const FILE_INFORMATION_CLASS = extern enum { FileDirectoryInformation = 1, FileFullDirectoryInformation, FileBothDirectoryInformation, FileBasicInformation, FileStandardInformation, FileInternalInformation, FileEaInformation, FileAccessInformation, FileNameInformation, FileRenameInformation, FileLinkInformation, FileNamesInformation, FileDispositionInformation, FilePositionInformation, FileFullEaInformation, FileModeInformation, FileAlignmentInformation, FileAllInformation, FileAllocationInformation, FileEndOfFileInformation, FileAlternateNameInformation, FileStreamInformation, FilePipeInformation, FilePipeLocalInformation, FilePipeRemoteInformation, FileMailslotQueryInformation, FileMailslotSetInformation, FileCompressionInformation, FileObjectIdInformation, FileCompletionInformation, FileMoveClusterInformation, FileQuotaInformation, FileReparsePointInformation, FileNetworkOpenInformation, FileAttributeTagInformation, FileTrackingInformation, FileIdBothDirectoryInformation, FileIdFullDirectoryInformation, FileValidDataLengthInformation, FileShortNameInformation, FileIoCompletionNotificationInformation, FileIoStatusBlockRangeInformation, FileIoPriorityHintInformation, FileSfioReserveInformation, FileSfioVolumeInformation, FileHardLinkInformation, FileProcessIdsUsingFileInformation, FileNormalizedNameInformation, FileNetworkPhysicalNameInformation, FileIdGlobalTxDirectoryInformation, FileIsRemoteDeviceInformation, FileUnusedInformation, FileNumaNodeInformation, FileStandardLinkInformation, FileRemoteProtocolInformation, FileRenameInformationBypassAccessCheck, FileLinkInformationBypassAccessCheck, FileVolumeNameInformation, FileIdInformation, FileIdExtdDirectoryInformation, FileReplaceCompletionInformation, FileHardLinkFullIdInformation, FileIdExtdBothDirectoryInformation, FileDispositionInformationEx, FileRenameInformationEx, FileRenameInformationExBypassAccessCheck, FileDesiredStorageClassInformation, FileStatInformation, FileMemoryPartitionInformation, FileStatLxInformation, FileCaseSensitiveInformation, FileLinkInformationEx, FileLinkInformationExBypassAccessCheck, FileStorageReserveIdInformation, FileCaseSensitiveInformationForceAccessCheck, FileMaximumInformation, }; pub const OVERLAPPED = extern struct { Internal: ULONG_PTR, InternalHigh: ULONG_PTR, Offset: DWORD, OffsetHigh: DWORD, hEvent: ?HANDLE, }; pub const LPOVERLAPPED = *OVERLAPPED; pub const MAX_PATH = 260; // TODO issue #305 pub const FILE_INFO_BY_HANDLE_CLASS = u32; pub const FileBasicInfo = 0; pub const FileStandardInfo = 1; pub const FileNameInfo = 2; pub const FileRenameInfo = 3; pub const FileDispositionInfo = 4; pub const FileAllocationInfo = 5; pub const FileEndOfFileInfo = 6; pub const FileStreamInfo = 7; pub const FileCompressionInfo = 8; pub const FileAttributeTagInfo = 9; pub const FileIdBothDirectoryInfo = 10; pub const FileIdBothDirectoryRestartInfo = 11; pub const FileIoPriorityHintInfo = 12; pub const FileRemoteProtocolInfo = 13; pub const FileFullDirectoryInfo = 14; pub const FileFullDirectoryRestartInfo = 15; pub const FileStorageInfo = 16; pub const FileAlignmentInfo = 17; pub const FileIdInfo = 18; pub const FileIdExtdDirectoryInfo = 19; pub const FileIdExtdDirectoryRestartInfo = 20; pub const BY_HANDLE_FILE_INFORMATION = extern struct { dwFileAttributes: DWORD, ftCreationTime: FILETIME, ftLastAccessTime: FILETIME, ftLastWriteTime: FILETIME, dwVolumeSerialNumber: DWORD, nFileSizeHigh: DWORD, nFileSizeLow: DWORD, nNumberOfLinks: DWORD, nFileIndexHigh: DWORD, nFileIndexLow: DWORD, }; pub const FILE_NAME_INFO = extern struct { FileNameLength: DWORD, FileName: [1]WCHAR, }; /// Return the normalized drive name. This is the default. pub const FILE_NAME_NORMALIZED = 0x0; /// Return the opened file name (not normalized). pub const FILE_NAME_OPENED = 0x8; /// Return the path with the drive letter. This is the default. pub const VOLUME_NAME_DOS = 0x0; /// Return the path with a volume GUID path instead of the drive name. pub const VOLUME_NAME_GUID = 0x1; /// Return the path with no drive information. pub const VOLUME_NAME_NONE = 0x4; /// Return the path with the volume device path. pub const VOLUME_NAME_NT = 0x2; pub const SECURITY_ATTRIBUTES = extern struct { nLength: DWORD, lpSecurityDescriptor: ?*c_void, bInheritHandle: BOOL, }; pub const PSECURITY_ATTRIBUTES = *SECURITY_ATTRIBUTES; pub const LPSECURITY_ATTRIBUTES = *SECURITY_ATTRIBUTES; pub const GENERIC_READ = 0x80000000; pub const GENERIC_WRITE = 0x40000000; pub const GENERIC_EXECUTE = 0x20000000; pub const GENERIC_ALL = 0x10000000; pub const FILE_SHARE_DELETE = 0x00000004; pub const FILE_SHARE_READ = 0x00000001; pub const FILE_SHARE_WRITE = 0x00000002; pub const DELETE = 0x00010000; pub const READ_CONTROL = 0x00020000; pub const WRITE_DAC = 0x00040000; pub const WRITE_OWNER = 0x00080000; pub const SYNCHRONIZE = 0x00100000; pub const STANDARD_RIGHTS_READ = READ_CONTROL; pub const STANDARD_RIGHTS_WRITE = READ_CONTROL; pub const STANDARD_RIGHTS_EXECUTE = READ_CONTROL; pub const STANDARD_RIGHTS_REQUIRED = DELETE | READ_CONTROL | WRITE_DAC | WRITE_OWNER; // disposition for NtCreateFile pub const FILE_SUPERSEDE = 0; pub const FILE_OPEN = 1; pub const FILE_CREATE = 2; pub const FILE_OPEN_IF = 3; pub const FILE_OVERWRITE = 4; pub const FILE_OVERWRITE_IF = 5; pub const FILE_MAXIMUM_DISPOSITION = 5; // flags for NtCreateFile and NtOpenFile pub const FILE_READ_DATA = 0x00000001; pub const FILE_LIST_DIRECTORY = 0x00000001; pub const FILE_WRITE_DATA = 0x00000002; pub const FILE_ADD_FILE = 0x00000002; pub const FILE_APPEND_DATA = 0x00000004; pub const FILE_ADD_SUBDIRECTORY = 0x00000004; pub const FILE_CREATE_PIPE_INSTANCE = 0x00000004; pub const FILE_READ_EA = 0x00000008; pub const FILE_WRITE_EA = 0x00000010; pub const FILE_EXECUTE = 0x00000020; pub const FILE_TRAVERSE = 0x00000020; pub const FILE_DELETE_CHILD = 0x00000040; pub const FILE_READ_ATTRIBUTES = 0x00000080; pub const FILE_WRITE_ATTRIBUTES = 0x00000100; pub const FILE_DIRECTORY_FILE = 0x00000001; pub const FILE_WRITE_THROUGH = 0x00000002; pub const FILE_SEQUENTIAL_ONLY = 0x00000004; pub const FILE_NO_INTERMEDIATE_BUFFERING = 0x00000008; pub const FILE_SYNCHRONOUS_IO_ALERT = 0x00000010; pub const FILE_SYNCHRONOUS_IO_NONALERT = 0x00000020; pub const FILE_NON_DIRECTORY_FILE = 0x00000040; pub const FILE_CREATE_TREE_CONNECTION = 0x00000080; pub const FILE_COMPLETE_IF_OPLOCKED = 0x00000100; pub const FILE_NO_EA_KNOWLEDGE = 0x00000200; pub const FILE_OPEN_FOR_RECOVERY = 0x00000400; pub const FILE_RANDOM_ACCESS = 0x00000800; pub const FILE_DELETE_ON_CLOSE = 0x00001000; pub const FILE_OPEN_BY_FILE_ID = 0x00002000; pub const FILE_OPEN_FOR_BACKUP_INTENT = 0x00004000; pub const FILE_NO_COMPRESSION = 0x00008000; pub const FILE_RESERVE_OPFILTER = 0x00100000; pub const FILE_TRANSACTED_MODE = 0x00200000; pub const FILE_OPEN_OFFLINE_FILE = 0x00400000; pub const FILE_OPEN_FOR_FREE_SPACE_QUERY = 0x00800000; pub const CREATE_ALWAYS = 2; pub const CREATE_NEW = 1; pub const OPEN_ALWAYS = 4; pub const OPEN_EXISTING = 3; pub const TRUNCATE_EXISTING = 5; pub const FILE_ATTRIBUTE_ARCHIVE = 0x20; pub const FILE_ATTRIBUTE_COMPRESSED = 0x800; pub const FILE_ATTRIBUTE_DEVICE = 0x40; pub const FILE_ATTRIBUTE_DIRECTORY = 0x10; pub const FILE_ATTRIBUTE_ENCRYPTED = 0x4000; pub const FILE_ATTRIBUTE_HIDDEN = 0x2; pub const FILE_ATTRIBUTE_INTEGRITY_STREAM = 0x8000; pub const FILE_ATTRIBUTE_NORMAL = 0x80; pub const FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 0x2000; pub const FILE_ATTRIBUTE_NO_SCRUB_DATA = 0x20000; pub const FILE_ATTRIBUTE_OFFLINE = 0x1000; pub const FILE_ATTRIBUTE_READONLY = 0x1; pub const FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS = 0x400000; pub const FILE_ATTRIBUTE_RECALL_ON_OPEN = 0x40000; pub const FILE_ATTRIBUTE_REPARSE_POINT = 0x400; pub const FILE_ATTRIBUTE_SPARSE_FILE = 0x200; pub const FILE_ATTRIBUTE_SYSTEM = 0x4; pub const FILE_ATTRIBUTE_TEMPORARY = 0x100; pub const FILE_ATTRIBUTE_VIRTUAL = 0x10000; // flags for CreateEvent pub const CREATE_EVENT_INITIAL_SET = 0x00000002; pub const CREATE_EVENT_MANUAL_RESET = 0x00000001; pub const EVENT_ALL_ACCESS = 0x1F0003; pub const EVENT_MODIFY_STATE = 0x0002; pub const PROCESS_INFORMATION = extern struct { hProcess: HANDLE, hThread: HANDLE, dwProcessId: DWORD, dwThreadId: DWORD, }; pub const STARTUPINFOW = extern struct { cb: DWORD, lpReserved: ?LPWSTR, lpDesktop: ?LPWSTR, lpTitle: ?LPWSTR, dwX: DWORD, dwY: DWORD, dwXSize: DWORD, dwYSize: DWORD, dwXCountChars: DWORD, dwYCountChars: DWORD, dwFillAttribute: DWORD, dwFlags: DWORD, wShowWindow: WORD, cbReserved2: WORD, lpReserved2: ?LPBYTE, hStdInput: ?HANDLE, hStdOutput: ?HANDLE, hStdError: ?HANDLE, }; pub const STARTF_FORCEONFEEDBACK = 0x00000040; pub const STARTF_FORCEOFFFEEDBACK = 0x00000080; pub const STARTF_PREVENTPINNING = 0x00002000; pub const STARTF_RUNFULLSCREEN = 0x00000020; pub const STARTF_TITLEISAPPID = 0x00001000; pub const STARTF_TITLEISLINKNAME = 0x00000800; pub const STARTF_UNTRUSTEDSOURCE = 0x00008000; pub const STARTF_USECOUNTCHARS = 0x00000008; pub const STARTF_USEFILLATTRIBUTE = 0x00000010; pub const STARTF_USEHOTKEY = 0x00000200; pub const STARTF_USEPOSITION = 0x00000004; pub const STARTF_USESHOWWINDOW = 0x00000001; pub const STARTF_USESIZE = 0x00000002; pub const STARTF_USESTDHANDLES = 0x00000100; pub const INFINITE = 4294967295; pub const MAXIMUM_WAIT_OBJECTS = 64; pub const WAIT_ABANDONED = 0x00000080; pub const WAIT_ABANDONED_0 = WAIT_ABANDONED + 0; pub const WAIT_OBJECT_0 = 0x00000000; pub const WAIT_TIMEOUT = 0x00000102; pub const WAIT_FAILED = 0xFFFFFFFF; pub const HANDLE_FLAG_INHERIT = 0x00000001; pub const HANDLE_FLAG_PROTECT_FROM_CLOSE = 0x00000002; pub const MOVEFILE_COPY_ALLOWED = 2; pub const MOVEFILE_CREATE_HARDLINK = 16; pub const MOVEFILE_DELAY_UNTIL_REBOOT = 4; pub const MOVEFILE_FAIL_IF_NOT_TRACKABLE = 32; pub const MOVEFILE_REPLACE_EXISTING = 1; pub const MOVEFILE_WRITE_THROUGH = 8; pub const FILE_BEGIN = 0; pub const FILE_CURRENT = 1; pub const FILE_END = 2; pub const HEAP_CREATE_ENABLE_EXECUTE = 0x00040000; pub const HEAP_GENERATE_EXCEPTIONS = 0x00000004; pub const HEAP_NO_SERIALIZE = 0x00000001; // AllocationType values pub const MEM_COMMIT = 0x1000; pub const MEM_RESERVE = 0x2000; pub const MEM_RESET = 0x80000; pub const MEM_RESET_UNDO = 0x1000000; pub const MEM_LARGE_PAGES = 0x20000000; pub const MEM_PHYSICAL = 0x400000; pub const MEM_TOP_DOWN = 0x100000; pub const MEM_WRITE_WATCH = 0x200000; // Protect values pub const PAGE_EXECUTE = 0x10; pub const PAGE_EXECUTE_READ = 0x20; pub const PAGE_EXECUTE_READWRITE = 0x40; pub const PAGE_EXECUTE_WRITECOPY = 0x80; pub const PAGE_NOACCESS = 0x01; pub const PAGE_READONLY = 0x02; pub const PAGE_READWRITE = 0x04; pub const PAGE_WRITECOPY = 0x08; pub const PAGE_TARGETS_INVALID = 0x40000000; pub const PAGE_TARGETS_NO_UPDATE = 0x40000000; // Same as PAGE_TARGETS_INVALID pub const PAGE_GUARD = 0x100; pub const PAGE_NOCACHE = 0x200; pub const PAGE_WRITECOMBINE = 0x400; // FreeType values pub const MEM_COALESCE_PLACEHOLDERS = 0x1; pub const MEM_RESERVE_PLACEHOLDERS = 0x2; pub const MEM_DECOMMIT = 0x4000; pub const MEM_RELEASE = 0x8000; pub const PTHREAD_START_ROUTINE = extern fn (LPVOID) DWORD; pub const LPTHREAD_START_ROUTINE = PTHREAD_START_ROUTINE; pub const WIN32_FIND_DATAW = extern struct { dwFileAttributes: DWORD, ftCreationTime: FILETIME, ftLastAccessTime: FILETIME, ftLastWriteTime: FILETIME, nFileSizeHigh: DWORD, nFileSizeLow: DWORD, dwReserved0: DWORD, dwReserved1: DWORD, cFileName: [260]u16, cAlternateFileName: [14]u16, }; pub const FILETIME = extern struct { dwLowDateTime: DWORD, dwHighDateTime: DWORD, }; pub const SYSTEM_INFO = extern struct { anon1: extern union { dwOemId: DWORD, anon2: extern struct { wProcessorArchitecture: WORD, wReserved: WORD, }, }, dwPageSize: DWORD, lpMinimumApplicationAddress: LPVOID, lpMaximumApplicationAddress: LPVOID, dwActiveProcessorMask: DWORD_PTR, dwNumberOfProcessors: DWORD, dwProcessorType: DWORD, dwAllocationGranularity: DWORD, wProcessorLevel: WORD, wProcessorRevision: WORD, }; pub const HRESULT = c_long; pub const KNOWNFOLDERID = GUID; pub const GUID = extern struct { Data1: c_ulong, Data2: c_ushort, Data3: c_ushort, Data4: [8]u8, pub fn parse(str: []const u8) GUID { var guid: GUID = undefined; var index: usize = 0; assert(str[index] == '{'); index += 1; guid.Data1 = std.fmt.parseUnsigned(c_ulong, str[index .. index + 8], 16) catch unreachable; index += 8; assert(str[index] == '-'); index += 1; guid.Data2 = std.fmt.parseUnsigned(c_ushort, str[index .. index + 4], 16) catch unreachable; index += 4; assert(str[index] == '-'); index += 1; guid.Data3 = std.fmt.parseUnsigned(c_ushort, str[index .. index + 4], 16) catch unreachable; index += 4; assert(str[index] == '-'); index += 1; guid.Data4[0] = std.fmt.parseUnsigned(u8, str[index .. index + 2], 16) catch unreachable; index += 2; guid.Data4[1] = std.fmt.parseUnsigned(u8, str[index .. index + 2], 16) catch unreachable; index += 2; assert(str[index] == '-'); index += 1; var i: usize = 2; while (i < guid.Data4.len) : (i += 1) { guid.Data4[i] = std.fmt.parseUnsigned(u8, str[index .. index + 2], 16) catch unreachable; index += 2; } assert(str[index] == '}'); index += 1; return guid; } }; pub const FOLDERID_LocalAppData = GUID.parse("{F1B32785-6FBA-4FCF-9D55-7B8E7F157091}"); pub const KF_FLAG_DEFAULT = 0; pub const KF_FLAG_NO_APPCONTAINER_REDIRECTION = 65536; pub const KF_FLAG_CREATE = 32768; pub const KF_FLAG_DONT_VERIFY = 16384; pub const KF_FLAG_DONT_UNEXPAND = 8192; pub const KF_FLAG_NO_ALIAS = 4096; pub const KF_FLAG_INIT = 2048; pub const KF_FLAG_DEFAULT_PATH = 1024; pub const KF_FLAG_NOT_PARENT_RELATIVE = 512; pub const KF_FLAG_SIMPLE_IDLIST = 256; pub const KF_FLAG_ALIAS_ONLY = -2147483648; pub const S_OK = 0; pub const E_NOTIMPL = @bitCast(c_long, @as(c_ulong, 0x80004001)); pub const E_NOINTERFACE = @bitCast(c_long, @as(c_ulong, 0x80004002)); pub const E_POINTER = @bitCast(c_long, @as(c_ulong, 0x80004003)); pub const E_ABORT = @bitCast(c_long, @as(c_ulong, 0x80004004)); pub const E_FAIL = @bitCast(c_long, @as(c_ulong, 0x80004005)); pub const E_UNEXPECTED = @bitCast(c_long, @as(c_ulong, 0x8000FFFF)); pub const E_ACCESSDENIED = @bitCast(c_long, @as(c_ulong, 0x80070005)); pub const E_HANDLE = @bitCast(c_long, @as(c_ulong, 0x80070006)); pub const E_OUTOFMEMORY = @bitCast(c_long, @as(c_ulong, 0x8007000E)); pub const E_INVALIDARG = @bitCast(c_long, @as(c_ulong, 0x80070057)); pub const FILE_FLAG_BACKUP_SEMANTICS = 0x02000000; pub const FILE_FLAG_DELETE_ON_CLOSE = 0x04000000; pub const FILE_FLAG_NO_BUFFERING = 0x20000000; pub const FILE_FLAG_OPEN_NO_RECALL = 0x00100000; pub const FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000; pub const FILE_FLAG_OVERLAPPED = 0x40000000; pub const FILE_FLAG_POSIX_SEMANTICS = 0x0100000; pub const FILE_FLAG_RANDOM_ACCESS = 0x10000000; pub const FILE_FLAG_SESSION_AWARE = 0x00800000; pub const FILE_FLAG_SEQUENTIAL_SCAN = 0x08000000; pub const FILE_FLAG_WRITE_THROUGH = 0x80000000; pub const SMALL_RECT = extern struct { Left: SHORT, Top: SHORT, Right: SHORT, Bottom: SHORT, }; pub const COORD = extern struct { X: SHORT, Y: SHORT, }; pub const CREATE_UNICODE_ENVIRONMENT = 1024; pub const TLS_OUT_OF_INDEXES = 4294967295; pub const IMAGE_TLS_DIRECTORY = extern struct { StartAddressOfRawData: usize, EndAddressOfRawData: usize, AddressOfIndex: usize, AddressOfCallBacks: usize, SizeOfZeroFill: u32, Characteristics: u32, }; pub const IMAGE_TLS_DIRECTORY64 = IMAGE_TLS_DIRECTORY; pub const IMAGE_TLS_DIRECTORY32 = IMAGE_TLS_DIRECTORY; pub const PIMAGE_TLS_CALLBACK = ?extern fn (PVOID, DWORD, PVOID) void; pub const PROV_RSA_FULL = 1; pub const REGSAM = ACCESS_MASK; pub const ACCESS_MASK = DWORD; pub const PHKEY = *HKEY; pub const HKEY = *HKEY__; pub const HKEY__ = extern struct { unused: c_int, }; pub const LSTATUS = LONG; pub const FILE_NOTIFY_INFORMATION = extern struct { NextEntryOffset: DWORD, Action: DWORD, FileNameLength: DWORD, FileName: [1]WCHAR, }; pub const FILE_ACTION_ADDED = 0x00000001; pub const FILE_ACTION_REMOVED = 0x00000002; pub const FILE_ACTION_MODIFIED = 0x00000003; pub const FILE_ACTION_RENAMED_OLD_NAME = 0x00000004; pub const FILE_ACTION_RENAMED_NEW_NAME = 0x00000005; pub const LPOVERLAPPED_COMPLETION_ROUTINE = ?extern fn (DWORD, DWORD, *OVERLAPPED) void; pub const FILE_NOTIFY_CHANGE_CREATION = 64; pub const FILE_NOTIFY_CHANGE_SIZE = 8; pub const FILE_NOTIFY_CHANGE_SECURITY = 256; pub const FILE_NOTIFY_CHANGE_LAST_ACCESS = 32; pub const FILE_NOTIFY_CHANGE_LAST_WRITE = 16; pub const FILE_NOTIFY_CHANGE_DIR_NAME = 2; pub const FILE_NOTIFY_CHANGE_FILE_NAME = 1; pub const FILE_NOTIFY_CHANGE_ATTRIBUTES = 4; pub const CONSOLE_SCREEN_BUFFER_INFO = extern struct { dwSize: COORD, dwCursorPosition: COORD, wAttributes: WORD, srWindow: SMALL_RECT, dwMaximumWindowSize: COORD, }; pub const FOREGROUND_BLUE = 1; pub const FOREGROUND_GREEN = 2; pub const FOREGROUND_RED = 4; pub const FOREGROUND_INTENSITY = 8; pub const LIST_ENTRY = extern struct { Flink: *LIST_ENTRY, Blink: *LIST_ENTRY, }; pub const RTL_CRITICAL_SECTION_DEBUG = extern struct { Type: WORD, CreatorBackTraceIndex: WORD, CriticalSection: *RTL_CRITICAL_SECTION, ProcessLocksList: LIST_ENTRY, EntryCount: DWORD, ContentionCount: DWORD, Flags: DWORD, CreatorBackTraceIndexHigh: WORD, SpareWORD: WORD, }; pub const RTL_CRITICAL_SECTION = extern struct { DebugInfo: *RTL_CRITICAL_SECTION_DEBUG, LockCount: LONG, RecursionCount: LONG, OwningThread: HANDLE, LockSemaphore: HANDLE, SpinCount: ULONG_PTR, }; pub const CRITICAL_SECTION = RTL_CRITICAL_SECTION; pub const INIT_ONCE = RTL_RUN_ONCE; pub const INIT_ONCE_STATIC_INIT = RTL_RUN_ONCE_INIT; pub const INIT_ONCE_FN = extern fn (InitOnce: *INIT_ONCE, Parameter: ?*c_void, Context: ?*c_void) BOOL; pub const RTL_RUN_ONCE = extern struct { Ptr: ?*c_void, }; pub const RTL_RUN_ONCE_INIT = RTL_RUN_ONCE{ .Ptr = null }; pub const COINIT_APARTMENTTHREADED = COINIT.COINIT_APARTMENTTHREADED; pub const COINIT_MULTITHREADED = COINIT.COINIT_MULTITHREADED; pub const COINIT_DISABLE_OLE1DDE = COINIT.COINIT_DISABLE_OLE1DDE; pub const COINIT_SPEED_OVER_MEMORY = COINIT.COINIT_SPEED_OVER_MEMORY; pub const COINIT = extern enum { COINIT_APARTMENTTHREADED = 2, COINIT_MULTITHREADED = 0, COINIT_DISABLE_OLE1DDE = 4, COINIT_SPEED_OVER_MEMORY = 8, }; /// > The maximum path of 32,767 characters is approximate, because the "\\?\" /// > prefix may be expanded to a longer string by the system at run time, and /// > this expansion applies to the total length. /// from https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#maximum-path-length-limitation pub const PATH_MAX_WIDE = 32767; pub const FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100; pub const FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000; pub const FORMAT_MESSAGE_FROM_HMODULE = 0x00000800; pub const FORMAT_MESSAGE_FROM_STRING = 0x00000400; pub const FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; pub const FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; pub const FORMAT_MESSAGE_MAX_WIDTH_MASK = 0x000000FF; pub const EXCEPTION_DATATYPE_MISALIGNMENT = 0x80000002; pub const EXCEPTION_ACCESS_VIOLATION = 0xc0000005; pub const EXCEPTION_ILLEGAL_INSTRUCTION = 0xc000001d; pub const EXCEPTION_STACK_OVERFLOW = 0xc00000fd; pub const EXCEPTION_CONTINUE_SEARCH = 0; pub const EXCEPTION_RECORD = extern struct { ExceptionCode: u32, ExceptionFlags: u32, ExceptionRecord: *EXCEPTION_RECORD, ExceptionAddress: *c_void, NumberParameters: u32, ExceptionInformation: [15]usize, }; pub const EXCEPTION_POINTERS = extern struct { ExceptionRecord: *EXCEPTION_RECORD, ContextRecord: *c_void, }; pub const VECTORED_EXCEPTION_HANDLER = fn (ExceptionInfo: *EXCEPTION_POINTERS) callconv(.Stdcall) c_long; pub const OBJECT_ATTRIBUTES = extern struct { Length: ULONG, RootDirectory: ?HANDLE, ObjectName: *UNICODE_STRING, Attributes: ULONG, SecurityDescriptor: ?*c_void, SecurityQualityOfService: ?*c_void, }; pub const OBJ_INHERIT = 0x00000002; pub const OBJ_PERMANENT = 0x00000010; pub const OBJ_EXCLUSIVE = 0x00000020; pub const OBJ_CASE_INSENSITIVE = 0x00000040; pub const OBJ_OPENIF = 0x00000080; pub const OBJ_OPENLINK = 0x00000100; pub const OBJ_KERNEL_HANDLE = 0x00000200; pub const OBJ_VALID_ATTRIBUTES = 0x000003F2; pub const UNICODE_STRING = extern struct { Length: c_ushort, MaximumLength: c_ushort, Buffer: [*]WCHAR, }; pub const PEB = extern struct { Reserved1: [2]BYTE, BeingDebugged: BYTE, Reserved2: [1]BYTE, Reserved3: [2]PVOID, Ldr: *PEB_LDR_DATA, ProcessParameters: *RTL_USER_PROCESS_PARAMETERS, Reserved4: [3]PVOID, AtlThunkSListPtr: PVOID, Reserved5: PVOID, Reserved6: ULONG, Reserved7: PVOID, Reserved8: ULONG, AtlThunkSListPtr32: ULONG, Reserved9: [45]PVOID, Reserved10: [96]BYTE, PostProcessInitRoutine: PPS_POST_PROCESS_INIT_ROUTINE, Reserved11: [128]BYTE, Reserved12: [1]PVOID, SessionId: ULONG, }; pub const PEB_LDR_DATA = extern struct { Reserved1: [8]BYTE, Reserved2: [3]PVOID, InMemoryOrderModuleList: LIST_ENTRY, }; pub const RTL_USER_PROCESS_PARAMETERS = extern struct { AllocationSize: ULONG, Size: ULONG, Flags: ULONG, DebugFlags: ULONG, ConsoleHandle: HANDLE, ConsoleFlags: ULONG, hStdInput: HANDLE, hStdOutput: HANDLE, hStdError: HANDLE, CurrentDirectory: CURDIR, DllPath: UNICODE_STRING, ImagePathName: UNICODE_STRING, CommandLine: UNICODE_STRING, Environment: [*]WCHAR, dwX: ULONG, dwY: ULONG, dwXSize: ULONG, dwYSize: ULONG, dwXCountChars: ULONG, dwYCountChars: ULONG, dwFillAttribute: ULONG, dwFlags: ULONG, dwShowWindow: ULONG, WindowTitle: UNICODE_STRING, Desktop: UNICODE_STRING, ShellInfo: UNICODE_STRING, RuntimeInfo: UNICODE_STRING, DLCurrentDirectory: [0x20]RTL_DRIVE_LETTER_CURDIR, }; pub const RTL_DRIVE_LETTER_CURDIR = extern struct { Flags: c_ushort, Length: c_ushort, TimeStamp: ULONG, DosPath: UNICODE_STRING, }; pub const PPS_POST_PROCESS_INIT_ROUTINE = ?extern fn () void; pub const FILE_BOTH_DIR_INFORMATION = extern struct { NextEntryOffset: ULONG, FileIndex: ULONG, CreationTime: LARGE_INTEGER, LastAccessTime: LARGE_INTEGER, LastWriteTime: LARGE_INTEGER, ChangeTime: LARGE_INTEGER, EndOfFile: LARGE_INTEGER, AllocationSize: LARGE_INTEGER, FileAttributes: ULONG, FileNameLength: ULONG, EaSize: ULONG, ShortNameLength: CHAR, ShortName: [12]WCHAR, FileName: [1]WCHAR, }; pub const FILE_BOTH_DIRECTORY_INFORMATION = FILE_BOTH_DIR_INFORMATION; pub const IO_APC_ROUTINE = extern fn (PVOID, *IO_STATUS_BLOCK, ULONG) void; pub const CURDIR = extern struct { DosPath: UNICODE_STRING, Handle: HANDLE, }; pub const DUPLICATE_SAME_ACCESS = 2;
lib/std/os/windows/bits.zig
const std = @import("std"); const builtin = @import("builtin"); const native_endian = builtin.target.cpu.arch.endian(); const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const expectEqualSlices = std.testing.expectEqualSlices; const maxInt = std.math.maxInt; const StructWithNoFields = struct { fn add(a: i32, b: i32) i32 { return a + b; } }; test "call struct static method" { const result = StructWithNoFields.add(3, 4); try expect(result == 7); } const should_be_11 = StructWithNoFields.add(5, 6); test "invoke static method in global scope" { try expect(should_be_11 == 11); } const empty_global_instance = StructWithNoFields{}; test "return empty struct instance" { _ = returnEmptyStructInstance(); } fn returnEmptyStructInstance() StructWithNoFields { return empty_global_instance; } const StructFoo = struct { a: i32, b: bool, c: f32, }; test "structs" { var foo: StructFoo = undefined; @memset(@ptrCast([*]u8, &foo), 0, @sizeOf(StructFoo)); foo.a += 1; foo.b = foo.a == 1; try testFoo(foo); testMutation(&foo); try expect(foo.c == 100); } fn testFoo(foo: StructFoo) !void { try expect(foo.b); } fn testMutation(foo: *StructFoo) void { foo.c = 100; } test "struct byval assign" { var foo1: StructFoo = undefined; var foo2: StructFoo = undefined; foo1.a = 1234; foo2.a = 0; try expect(foo2.a == 0); foo2 = foo1; try expect(foo2.a == 1234); } const Node = struct { val: Val, next: *Node, }; const Val = struct { x: i32, }; test "struct initializer" { const val = Val{ .x = 42 }; try expect(val.x == 42); } const MemberFnTestFoo = struct { x: i32, fn member(foo: MemberFnTestFoo) i32 { return foo.x; } }; test "call member function directly" { const instance = MemberFnTestFoo{ .x = 1234 }; const result = MemberFnTestFoo.member(instance); try expect(result == 1234); } test "struct point to self" { var root: Node = undefined; root.val.x = 1; var node: Node = undefined; node.next = &root; node.val.x = 2; root.next = &node; try expect(node.next.next.next.val.x == 1); } test "void struct fields" { const foo = VoidStructFieldsFoo{ .a = void{}, .b = 1, .c = void{}, }; try expect(foo.b == 1); try expect(@sizeOf(VoidStructFieldsFoo) == 4); } const VoidStructFieldsFoo = struct { a: void, b: i32, c: void, }; test "member functions" { const r = MemberFnRand{ .seed = 1234 }; try expect(r.getSeed() == 1234); } const MemberFnRand = struct { seed: u32, pub fn getSeed(r: *const MemberFnRand) u32 { return r.seed; } }; test "return struct byval from function" { const bar = makeBar2(1234, 5678); try expect(bar.y == 5678); } const Bar = struct { x: i32, y: i32, }; fn makeBar2(x: i32, y: i32) Bar { return Bar{ .x = x, .y = y, }; }
test/behavior/struct.zig
const std = @import("../std.zig"); const testing = std.testing; const builtin = std.builtin; const fs = std.fs; const mem = std.mem; const File = std.fs.File; const tmpDir = testing.tmpDir; test "readAllAlloc" { var tmp_dir = tmpDir(.{}); defer tmp_dir.cleanup(); var file = try tmp_dir.dir.createFile("test_file", .{ .read = true }); defer file.close(); const buf1 = try file.readAllAlloc(testing.allocator, 0, 1024); defer testing.allocator.free(buf1); testing.expect(buf1.len == 0); const write_buf: []const u8 = "this is a test.\nthis is a test.\nthis is a test.\nthis is a test.\n"; try file.writeAll(write_buf); try file.seekTo(0); const file_size = try file.getEndPos(); // max_bytes > file_size const buf2 = try file.readAllAlloc(testing.allocator, file_size, 1024); defer testing.allocator.free(buf2); testing.expectEqual(write_buf.len, buf2.len); testing.expect(std.mem.eql(u8, write_buf, buf2)); try file.seekTo(0); // max_bytes == file_size const buf3 = try file.readAllAlloc(testing.allocator, file_size, write_buf.len); defer testing.allocator.free(buf3); testing.expectEqual(write_buf.len, buf3.len); testing.expect(std.mem.eql(u8, write_buf, buf3)); // max_bytes < file_size testing.expectError(error.FileTooBig, file.readAllAlloc(testing.allocator, file_size, write_buf.len - 1)); } test "directory operations on files" { var tmp_dir = tmpDir(.{}); defer tmp_dir.cleanup(); const test_file_name = "test_file"; var file = try tmp_dir.dir.createFile(test_file_name, .{ .read = true }); file.close(); testing.expectError(error.PathAlreadyExists, tmp_dir.dir.makeDir(test_file_name)); testing.expectError(error.NotDir, tmp_dir.dir.openDir(test_file_name, .{})); testing.expectError(error.NotDir, tmp_dir.dir.deleteDir(test_file_name)); if (builtin.os.tag != .wasi) { // TODO: use Dir's realpath function once that exists const absolute_path = blk: { const relative_path = try fs.path.join(testing.allocator, &[_][]const u8{ "zig-cache", "tmp", tmp_dir.sub_path[0..], test_file_name }); defer testing.allocator.free(relative_path); break :blk try fs.realpathAlloc(testing.allocator, relative_path); }; defer testing.allocator.free(absolute_path); testing.expectError(error.PathAlreadyExists, fs.makeDirAbsolute(absolute_path)); testing.expectError(error.NotDir, fs.deleteDirAbsolute(absolute_path)); } // ensure the file still exists and is a file as a sanity check file = try tmp_dir.dir.openFile(test_file_name, .{}); const stat = try file.stat(); testing.expect(stat.kind == .File); file.close(); } test "file operations on directories" { var tmp_dir = tmpDir(.{}); defer tmp_dir.cleanup(); const test_dir_name = "test_dir"; try tmp_dir.dir.makeDir(test_dir_name); testing.expectError(error.IsDir, tmp_dir.dir.createFile(test_dir_name, .{})); testing.expectError(error.IsDir, tmp_dir.dir.deleteFile(test_dir_name)); // Currently, WASI will return error.Unexpected (via ENOTCAPABLE) when attempting fd_read on a directory handle. // TODO: Re-enable on WASI once https://github.com/bytecodealliance/wasmtime/issues/1935 is resolved. if (builtin.os.tag != .wasi) { testing.expectError(error.IsDir, tmp_dir.dir.readFileAlloc(testing.allocator, test_dir_name, std.math.maxInt(usize))); } // Note: The `.write = true` is necessary to ensure the error occurs on all platforms. // TODO: Add a read-only test as well, see https://github.com/ziglang/zig/issues/5732 testing.expectError(error.IsDir, tmp_dir.dir.openFile(test_dir_name, .{ .write = true })); if (builtin.os.tag != .wasi) { // TODO: use Dir's realpath function once that exists const absolute_path = blk: { const relative_path = try fs.path.join(testing.allocator, &[_][]const u8{ "zig-cache", "tmp", tmp_dir.sub_path[0..], test_dir_name }); defer testing.allocator.free(relative_path); break :blk try fs.realpathAlloc(testing.allocator, relative_path); }; defer testing.allocator.free(absolute_path); testing.expectError(error.IsDir, fs.createFileAbsolute(absolute_path, .{})); testing.expectError(error.IsDir, fs.deleteFileAbsolute(absolute_path)); } // ensure the directory still exists as a sanity check var dir = try tmp_dir.dir.openDir(test_dir_name, .{}); dir.close(); } test "openSelfExe" { if (builtin.os.tag == .wasi) return error.SkipZigTest; const self_exe_file = try std.fs.openSelfExe(.{}); self_exe_file.close(); } test "makePath, put some files in it, deleteTree" { var tmp = tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.makePath("os_test_tmp" ++ fs.path.sep_str ++ "b" ++ fs.path.sep_str ++ "c"); try tmp.dir.writeFile("os_test_tmp" ++ fs.path.sep_str ++ "b" ++ fs.path.sep_str ++ "c" ++ fs.path.sep_str ++ "file.txt", "nonsense"); try tmp.dir.writeFile("os_test_tmp" ++ fs.path.sep_str ++ "b" ++ fs.path.sep_str ++ "file2.txt", "blah"); try tmp.dir.deleteTree("os_test_tmp"); if (tmp.dir.openDir("os_test_tmp", .{})) |dir| { @panic("expected error"); } else |err| { testing.expect(err == error.FileNotFound); } } test "access file" { if (builtin.os.tag == .wasi) return error.SkipZigTest; var tmp = tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.makePath("os_test_tmp"); if (tmp.dir.access("os_test_tmp" ++ fs.path.sep_str ++ "file.txt", .{})) |ok| { @panic("expected error"); } else |err| { testing.expect(err == error.FileNotFound); } try tmp.dir.writeFile("os_test_tmp" ++ fs.path.sep_str ++ "file.txt", ""); try tmp.dir.access("os_test_tmp" ++ fs.path.sep_str ++ "file.txt", .{}); try tmp.dir.deleteTree("os_test_tmp"); } test "sendfile" { var tmp = tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.makePath("os_test_tmp"); defer tmp.dir.deleteTree("os_test_tmp") catch {}; var dir = try tmp.dir.openDir("os_test_tmp", .{}); defer dir.close(); const line1 = "line1\n"; const line2 = "second line\n"; var vecs = [_]std.os.iovec_const{ .{ .iov_base = line1, .iov_len = line1.len, }, .{ .iov_base = line2, .iov_len = line2.len, }, }; var src_file = try dir.createFile("sendfile1.txt", .{ .read = true }); defer src_file.close(); try src_file.writevAll(&vecs); var dest_file = try dir.createFile("sendfile2.txt", .{ .read = true }); defer dest_file.close(); const header1 = "header1\n"; const header2 = "second header\n"; const trailer1 = "trailer1\n"; const trailer2 = "second trailer\n"; var hdtr = [_]std.os.iovec_const{ .{ .iov_base = header1, .iov_len = header1.len, }, .{ .iov_base = header2, .iov_len = header2.len, }, .{ .iov_base = trailer1, .iov_len = trailer1.len, }, .{ .iov_base = trailer2, .iov_len = trailer2.len, }, }; var written_buf: [100]u8 = undefined; try dest_file.writeFileAll(src_file, .{ .in_offset = 1, .in_len = 10, .headers_and_trailers = &hdtr, .header_count = 2, }); const amt = try dest_file.preadAll(&written_buf, 0); testing.expect(mem.eql(u8, written_buf[0..amt], "header1\nsecond header\nine1\nsecontrailer1\nsecond trailer\n")); } test "fs.copyFile" { const data = "u6wj+JmdF3qHsFPE BUlH2g4gJCmEz0PP"; const src_file = "tmp_test_copy_file.txt"; const dest_file = "tmp_test_copy_file2.txt"; const dest_file2 = "tmp_test_copy_file3.txt"; var tmp = tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(src_file, data); defer tmp.dir.deleteFile(src_file) catch {}; try tmp.dir.copyFile(src_file, tmp.dir, dest_file, .{}); defer tmp.dir.deleteFile(dest_file) catch {}; try tmp.dir.copyFile(src_file, tmp.dir, dest_file2, .{ .override_mode = File.default_mode }); defer tmp.dir.deleteFile(dest_file2) catch {}; try expectFileContents(tmp.dir, dest_file, data); try expectFileContents(tmp.dir, dest_file2, data); } fn expectFileContents(dir: fs.Dir, file_path: []const u8, data: []const u8) !void { const contents = try dir.readFileAlloc(testing.allocator, file_path, 1000); defer testing.allocator.free(contents); testing.expectEqualSlices(u8, data, contents); } test "AtomicFile" { const test_out_file = "tmp_atomic_file_test_dest.txt"; const test_content = \\ hello! \\ this is a test file ; var tmp = tmpDir(.{}); defer tmp.cleanup(); { var af = try tmp.dir.atomicFile(test_out_file, .{}); defer af.deinit(); try af.file.writeAll(test_content); try af.finish(); } const content = try tmp.dir.readFileAlloc(testing.allocator, test_out_file, 9999); defer testing.allocator.free(content); testing.expect(mem.eql(u8, content, test_content)); try tmp.dir.deleteFile(test_out_file); } test "realpath" { if (builtin.os.tag == .wasi) return error.SkipZigTest; var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; testing.expectError(error.FileNotFound, fs.realpath("definitely_bogus_does_not_exist1234", &buf)); } const FILE_LOCK_TEST_SLEEP_TIME = 5 * std.time.ns_per_ms; test "open file with exclusive nonblocking lock twice" { if (builtin.os.tag == .wasi) return error.SkipZigTest; const dir = fs.cwd(); const filename = "file_nonblocking_lock_test.txt"; const file1 = try dir.createFile(filename, .{ .lock = .Exclusive, .lock_nonblocking = true }); defer file1.close(); const file2 = dir.createFile(filename, .{ .lock = .Exclusive, .lock_nonblocking = true }); std.debug.assert(std.meta.eql(file2, error.WouldBlock)); dir.deleteFile(filename) catch |err| switch (err) { error.FileNotFound => {}, else => return err, }; } test "open file with lock twice, make sure it wasn't open at the same time" { if (builtin.single_threaded) return error.SkipZigTest; if (std.io.is_async) { // This test starts its own threads and is not compatible with async I/O. return error.SkipZigTest; } const filename = "file_lock_test.txt"; var contexts = [_]FileLockTestContext{ .{ .filename = filename, .create = true, .lock = .Exclusive }, .{ .filename = filename, .create = true, .lock = .Exclusive }, }; try run_lock_file_test(&contexts); // Check for an error var was_error = false; for (contexts) |context, idx| { if (context.err) |err| { was_error = true; std.debug.warn("\nError in context {}: {}\n", .{ idx, err }); } } if (was_error) builtin.panic("There was an error in contexts", null); std.debug.assert(!contexts[0].overlaps(&contexts[1])); fs.cwd().deleteFile(filename) catch |err| switch (err) { error.FileNotFound => {}, else => return err, }; } test "create file, lock and read from multiple process at once" { if (builtin.single_threaded) return error.SkipZigTest; if (std.io.is_async) { // This test starts its own threads and is not compatible with async I/O. return error.SkipZigTest; } if (true) { // https://github.com/ziglang/zig/issues/5006 return error.SkipZigTest; } const filename = "file_read_lock_test.txt"; const filedata = "Hello, world!\n"; try fs.cwd().writeFile(filename, filedata); var contexts = [_]FileLockTestContext{ .{ .filename = filename, .create = false, .lock = .Shared }, .{ .filename = filename, .create = false, .lock = .Shared }, .{ .filename = filename, .create = false, .lock = .Exclusive }, }; try run_lock_file_test(&contexts); var was_error = false; for (contexts) |context, idx| { if (context.err) |err| { was_error = true; std.debug.warn("\nError in context {}: {}\n", .{ idx, err }); } } if (was_error) builtin.panic("There was an error in contexts", null); std.debug.assert(contexts[0].overlaps(&contexts[1])); std.debug.assert(!contexts[2].overlaps(&contexts[0])); std.debug.assert(!contexts[2].overlaps(&contexts[1])); if (contexts[0].bytes_read.? != filedata.len) { std.debug.warn("\n bytes_read: {}, expected: {} \n", .{ contexts[0].bytes_read, filedata.len }); } std.debug.assert(contexts[0].bytes_read.? == filedata.len); std.debug.assert(contexts[1].bytes_read.? == filedata.len); fs.cwd().deleteFile(filename) catch |err| switch (err) { error.FileNotFound => {}, else => return err, }; } test "open file with exclusive nonblocking lock twice (absolute paths)" { if (builtin.os.tag == .wasi) return error.SkipZigTest; const allocator = testing.allocator; const file_paths: [1][]const u8 = .{"zig-test-absolute-paths.txt"}; const filename = try fs.path.resolve(allocator, &file_paths); defer allocator.free(filename); const file1 = try fs.createFileAbsolute(filename, .{ .lock = .Exclusive, .lock_nonblocking = true }); const file2 = fs.createFileAbsolute(filename, .{ .lock = .Exclusive, .lock_nonblocking = true }); file1.close(); testing.expectError(error.WouldBlock, file2); try fs.deleteFileAbsolute(filename); } const FileLockTestContext = struct { filename: []const u8, pid: if (builtin.os.tag == .windows) ?void else ?std.os.pid_t = null, // use file.createFile create: bool, // the type of lock to use lock: File.Lock, // Output variables err: ?(File.OpenError || std.os.ReadError) = null, start_time: i64 = 0, end_time: i64 = 0, bytes_read: ?usize = null, fn overlaps(self: *const @This(), other: *const @This()) bool { return (self.start_time < other.end_time) and (self.end_time > other.start_time); } fn run(ctx: *@This()) void { var file: File = undefined; if (ctx.create) { file = fs.cwd().createFile(ctx.filename, .{ .lock = ctx.lock }) catch |err| { ctx.err = err; return; }; } else { file = fs.cwd().openFile(ctx.filename, .{ .lock = ctx.lock }) catch |err| { ctx.err = err; return; }; } defer file.close(); ctx.start_time = std.time.milliTimestamp(); if (!ctx.create) { var buffer: [100]u8 = undefined; ctx.bytes_read = 0; while (true) { const amt = file.read(buffer[0..]) catch |err| { ctx.err = err; return; }; if (amt == 0) break; ctx.bytes_read.? += amt; } } std.time.sleep(FILE_LOCK_TEST_SLEEP_TIME); ctx.end_time = std.time.milliTimestamp(); } }; fn run_lock_file_test(contexts: []FileLockTestContext) !void { var threads = std.ArrayList(*std.Thread).init(testing.allocator); defer { for (threads.items) |thread| { thread.wait(); } threads.deinit(); } for (contexts) |*ctx, idx| { try threads.append(try std.Thread.spawn(ctx, FileLockTestContext.run)); } }
lib/std/fs/test.zig
const std = @import("std"); const Type = @import("Type.zig"); const Tokenizer = @import("Tokenizer.zig"); const Compilation = @import("Compilation.zig"); const Source = @import("Source.zig"); const Attribute = @import("Attribute.zig"); const Tree = @This(); pub const Token = struct { id: Id, /// This location contains the actual token slice which might be generated. /// If it is generated then there is guaranteed to be at least one /// expansion location. loc: Source.Location, expansion_locs: ?[*]Source.Location = null, pub fn expansionSlice(tok: Token) []const Source.Location { const locs = tok.expansion_locs orelse return &[0]Source.Location{}; var i: usize = 0; while (locs[i].id != .unused) : (i += 1) {} return locs[0..i]; } pub fn addExpansionLocation(tok: *Token, gpa: std.mem.Allocator, new: []const Source.Location) !void { if (new.len == 0 or tok.id == .whitespace) return; var list = std.ArrayList(Source.Location).init(gpa); defer { std.mem.set(Source.Location, list.items.ptr[list.items.len..list.capacity], .{}); // add a sentinel since the allocator is not guaranteed // to return the exact desired size list.items.ptr[list.capacity - 1].byte_offset = 1; tok.expansion_locs = list.items.ptr; } if (tok.expansion_locs) |locs| { var i: usize = 0; while (locs[i].id != .unused) : (i += 1) {} list.items = locs[0..i]; while (locs[i].byte_offset != 1) : (i += 1) {} list.capacity = i + 1; } const min_len = std.math.max(list.items.len + new.len + 1, 4); const wanted_len = std.math.ceilPowerOfTwo(usize, min_len) catch return error.OutOfMemory; try list.ensureTotalCapacity(wanted_len); for (new) |new_loc| { if (new_loc.id == .generated) continue; list.appendAssumeCapacity(new_loc); } } pub fn free(expansion_locs: ?[*]Source.Location, gpa: std.mem.Allocator) void { const locs = expansion_locs orelse return; var i: usize = 0; while (locs[i].id != .unused) : (i += 1) {} while (locs[i].byte_offset != 1) : (i += 1) {} gpa.free(locs[0 .. i + 1]); } pub fn dupe(tok: Token, gpa: std.mem.Allocator) !Token { var copy = tok; copy.expansion_locs = null; try copy.addExpansionLocation(gpa, tok.expansionSlice()); return copy; } pub const List = std.MultiArrayList(Token); pub const Id = Tokenizer.Token.Id; }; pub const TokenIndex = u32; pub const NodeIndex = enum(u32) { none, _ }; pub const ValueMap = std.AutoHashMap(NodeIndex, u64); comp: *Compilation, arena: std.heap.ArenaAllocator, generated: []const u8, tokens: Token.List.Slice, nodes: Node.List.Slice, data: []const NodeIndex, root_decls: []const NodeIndex, strings: []const u8, value_map: ValueMap, pub fn deinit(tree: *Tree) void { tree.comp.gpa.free(tree.root_decls); tree.comp.gpa.free(tree.data); tree.comp.gpa.free(tree.strings); tree.nodes.deinit(tree.comp.gpa); tree.arena.deinit(); tree.value_map.deinit(); } pub const Node = struct { tag: Tag, ty: Type = .{ .specifier = .void }, data: Data, pub const Range = struct { start: u32, end: u32 }; pub const Data = union { decl: struct { name: TokenIndex, node: NodeIndex = .none, }, decl_ref: TokenIndex, range: Range, if3: struct { cond: NodeIndex, body: u32, }, str: struct { index: u32, len: u32, }, un: NodeIndex, bin: struct { lhs: NodeIndex, rhs: NodeIndex, }, member: struct { lhs: NodeIndex, name: TokenIndex, }, union_init: struct { field_index: u32, node: NodeIndex, }, int: u64, float: f32, double: f64, pub fn forDecl(data: Data, tree: Tree) struct { decls: []const NodeIndex, cond: NodeIndex, incr: NodeIndex, body: NodeIndex, } { const items = tree.data[data.range.start..data.range.end]; const decls = items[0 .. items.len - 3]; return .{ .decls = decls, .cond = items[items.len - 3], .incr = items[items.len - 2], .body = items[items.len - 1], }; } pub fn forStmt(data: Data, tree: Tree) struct { init: NodeIndex, cond: NodeIndex, incr: NodeIndex, body: NodeIndex, } { const items = tree.data[data.if3.body..]; return .{ .init = items[0], .cond = items[1], .incr = items[2], .body = data.if3.cond, }; } }; pub const List = std.MultiArrayList(Node); }; pub const Tag = enum(u8) { /// Only appears at index 0 and reaching it is always a result of a bug. invalid, // ====== Decl ====== // _Static_assert static_assert, // function prototype fn_proto, static_fn_proto, inline_fn_proto, inline_static_fn_proto, noreturn_fn_proto, noreturn_static_fn_proto, noreturn_inline_fn_proto, noreturn_inline_static_fn_proto, // function definition fn_def, static_fn_def, inline_fn_def, inline_static_fn_def, noreturn_fn_def, noreturn_static_fn_def, noreturn_inline_fn_def, noreturn_inline_static_fn_def, // variable declaration @"var", extern_var, static_var, // same as static_var, used for __func__, __FUNCTION__ and __PRETTY_FUNCTION__ implicit_static_var, threadlocal_var, threadlocal_extern_var, threadlocal_static_var, // typedef declaration typedef, // container declarations /// { lhs; rhs; } struct_decl_two, /// { lhs; rhs; } union_decl_two, /// { lhs, rhs, } enum_decl_two, /// { range } struct_decl, /// { range } union_decl, /// { range } enum_decl, /// name = node enum_field_decl, /// ty name : node /// name == 0 means unnamed record_field_decl, /// Used when a record has an unnamed record as a field indirect_record_field_decl, // ====== Stmt ====== labeled_stmt, /// { first; second; } first and second may be null compound_stmt_two, /// { data } compound_stmt, /// if (first) data[second] else data[second+1]; if_then_else_stmt, /// if (first); else second; if_else_stmt, /// if (first) second; second may be null if_then_stmt, /// switch (first) second switch_stmt, /// case first: second case_stmt, /// default: first default_stmt, /// while (first) second while_stmt, /// do second while(first); do_while_stmt, /// for (data[..]; data[len-3]; data[len-2]) data[len-1] for_decl_stmt, /// for (;;;) first forever_stmt, /// for (data[first]; data[first+1]; data[first+2]) second for_stmt, /// goto first; goto_stmt, /// goto *un; computed_goto_stmt, // continue; first and second unused continue_stmt, // break; first and second unused break_stmt, // null statement (just a semicolon); first and second unused null_stmt, /// return first; first may be null return_stmt, // ====== Expr ====== /// lhs , rhs comma_expr, /// lhs ?: rhs binary_cond_expr, /// lhs ? data[0] : data[1] cond_expr, /// lhs = rhs assign_expr, /// lhs *= rhs mul_assign_expr, /// lhs /= rhs div_assign_expr, /// lhs %= rhs mod_assign_expr, /// lhs += rhs add_assign_expr, /// lhs -= rhs sub_assign_expr, /// lhs <<= rhs shl_assign_expr, /// lhs >>= rhs shr_assign_expr, /// lhs &= rhs bit_and_assign_expr, /// lhs ^= rhs bit_xor_assign_expr, /// lhs |= rhs bit_or_assign_expr, /// lhs || rhs bool_or_expr, /// lhs && rhs bool_and_expr, /// lhs | rhs bit_or_expr, /// lhs ^ rhs bit_xor_expr, /// lhs & rhs bit_and_expr, /// lhs == rhs equal_expr, /// lhs != rhs not_equal_expr, /// lhs < rhs less_than_expr, /// lhs <= rhs less_than_equal_expr, /// lhs > rhs greater_than_expr, /// lhs >= rhs greater_than_equal_expr, /// lhs << rhs shl_expr, /// lhs >> rhs shr_expr, /// lhs + rhs add_expr, /// lhs - rhs sub_expr, /// lhs * rhs mul_expr, /// lhs / rhs div_expr, /// lhs % rhs mod_expr, /// Explicit (type)un cast_expr, /// &un addr_of_expr, /// &&decl_ref addr_of_label, /// *un deref_expr, /// +un plus_expr, /// -un negate_expr, /// ~un bit_not_expr, /// !un bool_not_expr, /// ++un pre_inc_expr, /// --un pre_dec_expr, /// lhs[rhs] lhs is pointer/array type, rhs is integer type array_access_expr, /// first(second) second may be 0 call_expr_one, /// data[0](data[1..]) call_expr, /// lhs.member member_access_expr, /// lhs->member member_access_ptr_expr, /// un++ post_inc_expr, /// un-- post_dec_expr, /// (un) paren_expr, /// decl decl_ref_expr, /// decl_ref enumeration_ref, /// integer literal, always unsigned int_literal, /// f32 literal float_literal, /// f64 literal double_literal, /// tree.str[index..][0..len] string_literal_expr, /// sizeof(un?) sizeof_expr, /// _Alignof(un?) alignof_expr, /// _Generic(controlling lhs, chosen rhs) generic_expr_one, /// _Generic(controlling range[0], chosen range[1], rest range[2..]) generic_expr, /// ty: un generic_association_expr, // default: un generic_default_expr, /// __builtin_choose_expr(lhs, data[0], data[1]) builtin_choose_expr, // ====== Initializer expressions ====== /// { lhs, rhs } array_init_expr_two, /// { range } array_init_expr, /// { lhs, rhs } struct_init_expr_two, /// { range } struct_init_expr, /// { union_init } union_init_expr, /// (ty){ un } compound_literal_expr, // ====== Implicit casts ====== /// Convert T[] to T * array_to_pointer, /// Converts an lvalue to an rvalue lval_to_rval, /// Convert a function type to a pointer to a function function_to_pointer, /// Convert a pointer type to a _Bool pointer_to_bool, /// Convert a pointer type to an integer type pointer_to_int, /// Convert _Bool to an integer type bool_to_int, /// Convert _Bool to a floating type bool_to_float, /// Convert a _Bool to a pointer; will cause a warning bool_to_pointer, /// Convert an integer type to _Bool int_to_bool, /// Convert an integer to a floating int_to_float, /// Convert an integer type to a pointer type int_to_pointer, /// Convert a floating type to a _Bool float_to_bool, /// Convert a floating type to an integer float_to_int, /// Convert one integer type to another int_cast, /// Convert one floating type to another float_cast, /// Convert pointer to one with same child type but more CV-quals, /// OR to appropriately-qualified void * /// only appears on the branches of a conditional expr qual_cast, /// Convert type to void; only appears on the branches of a conditional expr to_void, /// Convert a literal 0 to a null pointer null_to_pointer, /// Inserted at the end of a function body if no return stmt is found. /// ty is the functions return type implicit_return, /// Inserted in array_init_expr to represent unspecified elements. /// data.int contains the amount of elements. array_filler_expr, /// Inserted in record and scalar initializers for unspecified elements. default_init_expr, /// attribute argument identifier (see `mode` attribute) attr_arg_ident, /// rhs can be none attr_params_two, /// range attr_params, pub fn isImplicit(tag: Tag) bool { return switch (tag) { .array_to_pointer, .lval_to_rval, .function_to_pointer, .pointer_to_bool, .pointer_to_int, .bool_to_int, .bool_to_float, .bool_to_pointer, .int_to_bool, .int_to_float, .int_to_pointer, .float_to_bool, .float_to_int, .int_cast, .float_cast, .to_void, .implicit_return, .qual_cast, .null_to_pointer, .array_filler_expr, .default_init_expr, .implicit_static_var, => true, else => false, }; } }; pub fn isLval(nodes: Node.List.Slice, extra: []const NodeIndex, value_map: ValueMap, node: NodeIndex) bool { var is_const: bool = undefined; return isLvalExtra(nodes, extra, value_map, node, &is_const); } pub fn isLvalExtra(nodes: Node.List.Slice, extra: []const NodeIndex, value_map: ValueMap, node: NodeIndex, is_const: *bool) bool { is_const.* = false; switch (nodes.items(.tag)[@enumToInt(node)]) { .compound_literal_expr => { is_const.* = nodes.items(.ty)[@enumToInt(node)].isConst(); return true; }, .string_literal_expr => return true, .member_access_ptr_expr => { const lhs_expr = nodes.items(.data)[@enumToInt(node)].member.lhs; const ptr_ty = nodes.items(.ty)[@enumToInt(lhs_expr)]; if (ptr_ty.isPtr()) is_const.* = ptr_ty.elemType().isConst(); return true; }, .array_access_expr => { const lhs_expr = nodes.items(.data)[@enumToInt(node)].bin.lhs; if (lhs_expr != .none) { const array_ty = nodes.items(.ty)[@enumToInt(lhs_expr)]; if (array_ty.isPtr() or array_ty.isArray()) is_const.* = array_ty.elemType().isConst(); } return true; }, .decl_ref_expr => { const decl_ty = nodes.items(.ty)[@enumToInt(node)]; is_const.* = decl_ty.isConst(); return true; }, .deref_expr => { const data = nodes.items(.data)[@enumToInt(node)]; const operand_ty = nodes.items(.ty)[@enumToInt(data.un)]; if (operand_ty.isFunc()) return false; if (operand_ty.isPtr() or operand_ty.isArray()) is_const.* = operand_ty.elemType().isConst(); return true; }, .member_access_expr => { const data = nodes.items(.data)[@enumToInt(node)]; return isLvalExtra(nodes, extra, value_map, data.member.lhs, is_const); }, .paren_expr => { const data = nodes.items(.data)[@enumToInt(node)]; return isLvalExtra(nodes, extra, value_map, data.un, is_const); }, .builtin_choose_expr => { const data = nodes.items(.data)[@enumToInt(node)]; if (value_map.get(data.if3.cond)) |val| { const offset = @boolToInt(val == 0); return isLvalExtra(nodes, extra, value_map, extra[data.if3.body + offset], is_const); } return false; }, else => return false, } } pub fn dumpStr(bytes: []const u8, tag: Tag, writer: anytype) !void { switch (tag) { .string_literal_expr => try writer.print("\"{}\"", .{std.zig.fmtEscapes(bytes[0 .. bytes.len - 1])}), else => unreachable, } } pub fn tokSlice(tree: Tree, tok_i: TokenIndex) []const u8 { if (tree.tokens.items(.id)[tok_i].lexeme()) |some| return some; const loc = tree.tokens.items(.loc)[tok_i]; var tmp_tokenizer = Tokenizer{ .buf = tree.comp.getSource(loc.id).buf, .comp = tree.comp, .index = loc.byte_offset, .source = .generated, }; const tok = tmp_tokenizer.next(); return tmp_tokenizer.buf[tok.start..tok.end]; } pub fn dump(tree: Tree, writer: anytype) @TypeOf(writer).Error!void { for (tree.root_decls) |i| { try tree.dumpNode(i, 0, writer); try writer.writeByte('\n'); } } fn dumpNode(tree: Tree, node: NodeIndex, level: u32, w: anytype) @TypeOf(w).Error!void { const delta = 2; const half = delta / 2; const win = @import("builtin").os.tag == .windows; const TYPE = if (win) "" else "\x1b[35;1m"; const TAG = if (win) "" else "\x1b[36;1m"; const IMPLICIT = if (win) "" else "\x1b[34;1m"; const NAME = if (win) "" else "\x1b[91;1m"; const LITERAL = if (win) "" else "\x1b[32;1m"; const ATTRIBUTE = if (win) "" else "\x1b[93;1m"; const RESET = if (win) "" else "\x1b[0m"; std.debug.assert(node != .none); const tag = tree.nodes.items(.tag)[@enumToInt(node)]; const data = tree.nodes.items(.data)[@enumToInt(node)]; const ty = tree.nodes.items(.ty)[@enumToInt(node)]; try w.writeByteNTimes(' ', level); if (tag.isImplicit()) { try w.print(IMPLICIT ++ "{s}: " ++ TYPE ++ "'", .{@tagName(tag)}); } else { try w.print(TAG ++ "{s}: " ++ TYPE ++ "'", .{@tagName(tag)}); } try ty.dump(w); try w.writeAll("'"); if (isLval(tree.nodes, tree.data, tree.value_map, node)) { try w.writeAll(ATTRIBUTE ++ " lvalue"); } if (tree.value_map.get(node)) |val| { if (ty.isUnsignedInt(tree.comp)) try w.print(LITERAL ++ " (value: {d})" ++ RESET, .{val}) else try w.print(LITERAL ++ " (value: {d})" ++ RESET, .{@bitCast(i64, val)}); } try w.writeAll("\n" ++ RESET); if (ty.specifier == .attributed) { for (ty.data.attributed.attributes) |attr| { const attr_name = tree.tokSlice(attr.name); try w.writeByteNTimes(' ', level + half); try w.print(ATTRIBUTE ++ "attr: {s}\n" ++ RESET, .{attr_name}); if (attr.params != .none) { try tree.dumpNode(attr.params, level + delta, w); } } } switch (tag) { .invalid => unreachable, .static_assert => { try w.writeByteNTimes(' ', level + 1); try w.writeAll("condition:\n"); try tree.dumpNode(data.bin.lhs, level + delta, w); if (data.bin.rhs != .none) { try w.writeByteNTimes(' ', level + 1); try w.writeAll("diagnostic:\n"); try tree.dumpNode(data.bin.rhs, level + delta, w); } }, .fn_proto, .static_fn_proto, .inline_fn_proto, .inline_static_fn_proto, .noreturn_fn_proto, .noreturn_static_fn_proto, .noreturn_inline_fn_proto, .noreturn_inline_static_fn_proto, => { try w.writeByteNTimes(' ', level + half); try w.print("name: " ++ NAME ++ "{s}\n" ++ RESET, .{tree.tokSlice(data.decl.name)}); }, .fn_def, .static_fn_def, .inline_fn_def, .inline_static_fn_def, .noreturn_fn_def, .noreturn_static_fn_def, .noreturn_inline_fn_def, .noreturn_inline_static_fn_def, => { try w.writeByteNTimes(' ', level + half); try w.print("name: " ++ NAME ++ "{s}\n" ++ RESET, .{tree.tokSlice(data.decl.name)}); try w.writeByteNTimes(' ', level + half); try w.writeAll("body:\n"); try tree.dumpNode(data.decl.node, level + delta, w); }, .typedef, .@"var", .extern_var, .static_var, .implicit_static_var, .threadlocal_var, .threadlocal_extern_var, .threadlocal_static_var, => { try w.writeByteNTimes(' ', level + half); try w.print("name: " ++ NAME ++ "{s}\n" ++ RESET, .{tree.tokSlice(data.decl.name)}); if (data.decl.node != .none) { try w.writeByteNTimes(' ', level + half); try w.writeAll("init:\n"); try tree.dumpNode(data.decl.node, level + delta, w); } }, .enum_field_decl => { try w.writeByteNTimes(' ', level + half); try w.print("name: " ++ NAME ++ "{s}\n" ++ RESET, .{tree.tokSlice(data.decl.name)}); if (data.decl.node != .none) { try w.writeByteNTimes(' ', level + half); try w.writeAll("value:\n"); try tree.dumpNode(data.decl.node, level + delta, w); } }, .record_field_decl => { if (data.decl.name != 0) { try w.writeByteNTimes(' ', level + half); try w.print("name: " ++ NAME ++ "{s}\n" ++ RESET, .{tree.tokSlice(data.decl.name)}); } if (data.decl.node != .none) { try w.writeByteNTimes(' ', level + half); try w.writeAll("bits:\n"); try tree.dumpNode(data.decl.node, level + delta, w); } }, .indirect_record_field_decl => {}, .compound_stmt, .array_init_expr, .struct_init_expr, .enum_decl, .struct_decl, .union_decl, .attr_params, => { for (tree.data[data.range.start..data.range.end]) |stmt, i| { if (i != 0) try w.writeByte('\n'); try tree.dumpNode(stmt, level + delta, w); } }, .compound_stmt_two, .array_init_expr_two, .struct_init_expr_two, .enum_decl_two, .struct_decl_two, .union_decl_two, .attr_params_two, => { if (data.bin.lhs != .none) try tree.dumpNode(data.bin.lhs, level + delta, w); if (data.bin.rhs != .none) try tree.dumpNode(data.bin.rhs, level + delta, w); }, .union_init_expr => { try w.writeByteNTimes(' ', level + half); try w.print("field index: " ++ LITERAL ++ "{d}\n" ++ RESET, .{data.union_init.field_index}); if (data.union_init.node != .none) { try tree.dumpNode(data.union_init.node, level + delta, w); } }, .compound_literal_expr => { try tree.dumpNode(data.un, level + half, w); }, .labeled_stmt => { try w.writeByteNTimes(' ', level + half); try w.print("label: " ++ LITERAL ++ "{s}\n" ++ RESET, .{tree.tokSlice(data.decl.name)}); if (data.decl.node != .none) { try w.writeByteNTimes(' ', level + half); try w.writeAll("stmt:\n"); try tree.dumpNode(data.decl.node, level + delta, w); } }, .case_stmt => { try w.writeByteNTimes(' ', level + half); try w.writeAll("value:\n"); try tree.dumpNode(data.bin.lhs, level + delta, w); if (data.bin.rhs != .none) { try w.writeByteNTimes(' ', level + half); try w.writeAll("stmt:\n"); try tree.dumpNode(data.bin.rhs, level + delta, w); } }, .default_stmt => { if (data.un != .none) { try w.writeByteNTimes(' ', level + half); try w.writeAll("stmt:\n"); try tree.dumpNode(data.un, level + delta, w); } }, .cond_expr, .if_then_else_stmt, .builtin_choose_expr => { try w.writeByteNTimes(' ', level + half); try w.writeAll("cond:\n"); try tree.dumpNode(data.if3.cond, level + delta, w); try w.writeByteNTimes(' ', level + half); try w.writeAll("then:\n"); try tree.dumpNode(tree.data[data.if3.body], level + delta, w); try w.writeByteNTimes(' ', level + half); try w.writeAll("else:\n"); try tree.dumpNode(tree.data[data.if3.body + 1], level + delta, w); }, .if_else_stmt => { try w.writeByteNTimes(' ', level + half); try w.writeAll("cond:\n"); try tree.dumpNode(data.bin.lhs, level + delta, w); try w.writeByteNTimes(' ', level + half); try w.writeAll("else:\n"); try tree.dumpNode(data.bin.rhs, level + delta, w); }, .if_then_stmt => { try w.writeByteNTimes(' ', level + half); try w.writeAll("cond:\n"); try tree.dumpNode(data.bin.lhs, level + delta, w); if (data.bin.rhs != .none) { try w.writeByteNTimes(' ', level + half); try w.writeAll("then:\n"); try tree.dumpNode(data.bin.rhs, level + delta, w); } }, .switch_stmt, .while_stmt, .do_while_stmt => { try w.writeByteNTimes(' ', level + half); try w.writeAll("cond:\n"); try tree.dumpNode(data.bin.lhs, level + delta, w); if (data.bin.rhs != .none) { try w.writeByteNTimes(' ', level + half); try w.writeAll("body:\n"); try tree.dumpNode(data.bin.rhs, level + delta, w); } }, .for_decl_stmt => { const for_decl = data.forDecl(tree); try w.writeByteNTimes(' ', level + half); try w.writeAll("decl:\n"); for (for_decl.decls) |decl| { try tree.dumpNode(decl, level + delta, w); try w.writeByte('\n'); } if (for_decl.cond != .none) { try w.writeByteNTimes(' ', level + half); try w.writeAll("cond:\n"); try tree.dumpNode(for_decl.cond, level + delta, w); } if (for_decl.incr != .none) { try w.writeByteNTimes(' ', level + half); try w.writeAll("incr:\n"); try tree.dumpNode(for_decl.incr, level + delta, w); } if (for_decl.body != .none) { try w.writeByteNTimes(' ', level + half); try w.writeAll("body:\n"); try tree.dumpNode(for_decl.body, level + delta, w); } }, .forever_stmt => { if (data.un != .none) { try w.writeByteNTimes(' ', level + half); try w.writeAll("body:\n"); try tree.dumpNode(data.un, level + delta, w); } }, .for_stmt => { const for_stmt = data.forStmt(tree); if (for_stmt.init != .none) { try w.writeByteNTimes(' ', level + half); try w.writeAll("init:\n"); try tree.dumpNode(for_stmt.init, level + delta, w); } if (for_stmt.cond != .none) { try w.writeByteNTimes(' ', level + half); try w.writeAll("cond:\n"); try tree.dumpNode(for_stmt.cond, level + delta, w); } if (for_stmt.incr != .none) { try w.writeByteNTimes(' ', level + half); try w.writeAll("incr:\n"); try tree.dumpNode(for_stmt.incr, level + delta, w); } if (for_stmt.body != .none) { try w.writeByteNTimes(' ', level + half); try w.writeAll("body:\n"); try tree.dumpNode(for_stmt.body, level + delta, w); } }, .goto_stmt, .addr_of_label => { try w.writeByteNTimes(' ', level + half); try w.print("label: " ++ LITERAL ++ "{s}\n" ++ RESET, .{tree.tokSlice(data.decl_ref)}); }, .continue_stmt, .break_stmt, .implicit_return, .null_stmt => {}, .return_stmt => { if (data.un != .none) { try w.writeByteNTimes(' ', level + half); try w.writeAll("expr:\n"); try tree.dumpNode(data.un, level + delta, w); } }, .string_literal_expr => { try w.writeByteNTimes(' ', level + half); try w.writeAll("data: " ++ LITERAL); try dumpStr(tree.strings[data.str.index..][0..data.str.len], tag, w); try w.writeAll("\n" ++ RESET); }, .attr_arg_ident => { try w.writeByteNTimes(' ', level + half); try w.print(ATTRIBUTE ++ "name: {s}\n" ++ RESET, .{tree.tokSlice(data.decl_ref)}); }, .call_expr => { try w.writeByteNTimes(' ', level + half); try w.writeAll("lhs:\n"); try tree.dumpNode(tree.data[data.range.start], level + delta, w); try w.writeByteNTimes(' ', level + half); try w.writeAll("args:\n"); for (tree.data[data.range.start + 1 .. data.range.end]) |arg| try tree.dumpNode(arg, level + delta, w); }, .call_expr_one => { try w.writeByteNTimes(' ', level + half); try w.writeAll("lhs:\n"); try tree.dumpNode(data.bin.lhs, level + delta, w); if (data.bin.rhs != .none) { try w.writeByteNTimes(' ', level + half); try w.writeAll("arg:\n"); try tree.dumpNode(data.bin.rhs, level + delta, w); } }, .comma_expr, .binary_cond_expr, .assign_expr, .mul_assign_expr, .div_assign_expr, .mod_assign_expr, .add_assign_expr, .sub_assign_expr, .shl_assign_expr, .shr_assign_expr, .bit_and_assign_expr, .bit_xor_assign_expr, .bit_or_assign_expr, .bool_or_expr, .bool_and_expr, .bit_or_expr, .bit_xor_expr, .bit_and_expr, .equal_expr, .not_equal_expr, .less_than_expr, .less_than_equal_expr, .greater_than_expr, .greater_than_equal_expr, .shl_expr, .shr_expr, .add_expr, .sub_expr, .mul_expr, .div_expr, .mod_expr, => { try w.writeByteNTimes(' ', level + 1); try w.writeAll("lhs:\n"); try tree.dumpNode(data.bin.lhs, level + delta, w); try w.writeByteNTimes(' ', level + 1); try w.writeAll("rhs:\n"); try tree.dumpNode(data.bin.rhs, level + delta, w); }, .cast_expr, .addr_of_expr, .computed_goto_stmt, .deref_expr, .plus_expr, .negate_expr, .bit_not_expr, .bool_not_expr, .pre_inc_expr, .pre_dec_expr, .post_inc_expr, .post_dec_expr, .paren_expr, => { try w.writeByteNTimes(' ', level + 1); try w.writeAll("operand:\n"); try tree.dumpNode(data.un, level + delta, w); }, .decl_ref_expr => { try w.writeByteNTimes(' ', level + 1); try w.print("name: " ++ NAME ++ "{s}\n" ++ RESET, .{tree.tokSlice(data.decl_ref)}); }, .enumeration_ref => { try w.writeByteNTimes(' ', level + 1); try w.print("name: " ++ NAME ++ "{s}\n" ++ RESET, .{tree.tokSlice(data.decl_ref)}); }, .int_literal => { try w.writeByteNTimes(' ', level + 1); try w.print("value: " ++ LITERAL ++ "{d}\n" ++ RESET, .{data.int}); }, .float_literal => { try w.writeByteNTimes(' ', level + 1); try w.print("value: " ++ LITERAL ++ "{d}\n" ++ RESET, .{data.float}); }, .double_literal => { try w.writeByteNTimes(' ', level + 1); try w.print("value: " ++ LITERAL ++ "{d}\n" ++ RESET, .{data.double}); }, .member_access_expr, .member_access_ptr_expr => { if (data.member.lhs != .none) { try w.writeByteNTimes(' ', level + 1); try w.writeAll("lhs:\n"); try tree.dumpNode(data.member.lhs, level + delta, w); } try w.writeByteNTimes(' ', level + 1); try w.print("name: " ++ NAME ++ "{s}\n" ++ RESET, .{tree.tokSlice(data.member.name)}); }, .array_access_expr => { if (data.bin.lhs != .none) { try w.writeByteNTimes(' ', level + 1); try w.writeAll("lhs:\n"); try tree.dumpNode(data.bin.lhs, level + delta, w); } try w.writeByteNTimes(' ', level + 1); try w.writeAll("index:\n"); try tree.dumpNode(data.bin.rhs, level + delta, w); }, .sizeof_expr, .alignof_expr => { if (data.un != .none) { try w.writeByteNTimes(' ', level + 1); try w.writeAll("expr:\n"); try tree.dumpNode(data.un, level + delta, w); } }, .generic_expr_one => { try w.writeByteNTimes(' ', level + 1); try w.writeAll("controlling:\n"); try tree.dumpNode(data.bin.lhs, level + delta, w); try w.writeByteNTimes(' ', level + 1); try w.writeAll("chosen:\n"); try tree.dumpNode(data.bin.rhs, level + delta, w); }, .generic_expr => { const nodes = tree.data[data.range.start..data.range.end]; try w.writeByteNTimes(' ', level + 1); try w.writeAll("controlling:\n"); try tree.dumpNode(nodes[0], level + delta, w); try w.writeByteNTimes(' ', level + 1); try w.writeAll("chosen:\n"); try tree.dumpNode(nodes[1], level + delta, w); try w.writeByteNTimes(' ', level + 1); try w.writeAll("rest:\n"); for (nodes[2..]) |expr| { try tree.dumpNode(expr, level + delta, w); } }, .generic_association_expr, .generic_default_expr => { try tree.dumpNode(data.un, level + delta, w); }, .array_to_pointer, .lval_to_rval, .function_to_pointer, .pointer_to_bool, .pointer_to_int, .bool_to_int, .bool_to_float, .bool_to_pointer, .int_to_bool, .int_to_float, .int_to_pointer, .float_to_bool, .float_to_int, .int_cast, .float_cast, .to_void, .qual_cast, .null_to_pointer, => { try tree.dumpNode(data.un, level + delta, w); }, .array_filler_expr => { try w.writeByteNTimes(' ', level + 1); try w.print("count: " ++ LITERAL ++ "{d}\n" ++ RESET, .{data.int}); }, .default_init_expr => {}, } }
src/Tree.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const mem = std.mem; const math = std.math; const assert = std.debug.assert; const meta = std.meta; usingnamespace @import("http.zig"); pub const HandlerFn = fn handle(Request, Response, []const u8) callconv(.Async) anyerror!void; pub const ErrorHandler = struct { handler: fn (Request, Response) void, err: anyerror, }; pub fn Router(comptime handlers: anytype) HandlerFn { comptime var routes: []const Route = &[_]Route{}; comptime var err_handlers: []const ErrorHandler = &[_]ErrorHandler{}; inline for (handlers) |handler| { switch (@TypeOf(handler)) { ErrorHandler => { err_handlers = (err_handlers ++ &[_]ErrorHandler{handler}); }, Route => { routes = (routes ++ &[_]Route{handler}); }, else => |f_type| @compileError("unsupported handler type " ++ @typeName(f_type)), } } if (routes.len == 0) { @compileError("Router must have at least one route"); } return struct { fn handle(req: Request, res: Response, path: []const u8) callconv(.Async) !void { if (req.path[0] == '*') { @panic("Todo server request"); } inline for (routes) |route| { comptime var type_info = @typeInfo(@TypeOf(route.handler)).Fn; comptime var err: ?type = switch (@typeInfo(type_info.return_type.?)) { .ErrorUnion => @typeInfo(type_info.return_type.?).ErrorUnion.error_set, else => null, }; // try matching path to route if (err == null) { if (match(route, err, req, res, path)) { res.status_code = .Ok; return; } } else { if (match(route, err, req, res, path) catch |e| { if (err_handlers.len == 0) { return e; } else { return handleError(e, req, res); } }) { res.status_code = .Ok; return; } } } // not found return if (err_handlers.len == 0) error.FileNotFound else handleError(error.FileNotFound, req, res); } fn handleError(err: anyerror, req: Request, res: Response) !void { inline for (err_handlers) |e| { if (err == e.err) { return e.handler(req, res); } } return err; } }.handle; } pub const Route = struct { path: []const u8, method: ?[]const u8, handler: anytype, }; /// returns true if request matched route pub fn match( comptime route: Route, comptime Errs: ?type, req: Request, res: Response, path: []const u8, ) if (Errs != null) Errs.?!bool else bool { // TODO this can be improved const handler = route.handler; const has_args = @typeInfo(@TypeOf(handler)).Fn.args.len == 3; const Args = if (has_args) @typeInfo(@typeInfo(@TypeOf(handler)).Fn.args[2].arg_type.?).Pointer.child else void; var args: Args = undefined; comptime var used: if (has_args) [@typeInfo(Args).Struct.fields.len]bool else void = undefined; if (has_args) { comptime mem.set(bool, &used, false); } const State = enum { Start, Path, AmperStart, AmperFirst, Format, }; comptime var state = State.Start; comptime var index = 0; comptime var begin = 0; comptime var fmt_begin = 0; // worst-case scenario every byte in route needs to be percentage encoded comptime var pathbuf: [route.path.len * 3]u8 = undefined; comptime var optional = false; var path_index: usize = 0; var len: usize = undefined; inline for (route.path) |c, i| { comptime if (state == .Start and c == '*') { state = .Path; break; }; switch (state) { .Start => comptime switch (c) { '/' => { pathbuf[index] = '/'; state = .Path; index += 1; }, else => @compileError("route must begin with a '/'"), }, .Path => switch (c) { '?' => { if (!optional) { @compileError("previous character is not optional"); } else { optional = false; index -= 1; const r = pathbuf[begin..index]; begin = index; if (path.len < r.len or !mem.eql(u8, r, path[path_index .. path_index + r.len])) { return false; } path_index += r.len; if (path.len > path_index and path[path_index] == pathbuf[begin]) { path_index += 1; } } }, 'a'...'z', 'A'...'Z', '0'...'9', '-', '.', '_', '~', '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '@', '%', '/' => comptime { pathbuf[index] = c; index += 1; if (c == '%') { state = .AmperStart; } optional = true; }, '{' => { if (!has_args) { @compileError("handler does not take path arguments"); } optional = false; state = .Format; fmt_begin = i + 1; const r = pathbuf[begin..index]; begin = index; if (path.len < r.len or !mem.eql(u8, r, path[path_index .. path_index + r.len])) { return false; } path_index += r.len; }, else => comptime { const hex_digits = "0123456789ABCDEF"; pathbuf[index] = '%'; pathbuf[index + 1] = hex_digits[(c & 0xF0) >> 4]; pathbuf[index + 2] = hex_digits[c & 0x0F]; index += 3; optional = true; }, }, .AmperStart, .AmperFirst => comptime switch (c) { '0'...'9', 'a'...'f', 'A'...'F' => { pathbuf[index] = c; index += 1; if (state == .AmperStart) { state = .AmperFirst; } else { state = .Path; } }, else => @compileError("'%' must be followed by two hexadecimal digits"), }, .Format => switch (c) { '}' => { comptime var radix = 10; comptime var number = true; comptime var field_name: []const u8 = undefined; comptime var field_type: type = undefined; comptime var delim: []const u8 = "/."; comptime { const Fstate = enum { Name, Radix, Done, Fmt, }; var fstate = .Name; var fmt = route.path[fmt_begin..i]; if (fmt.len == 0) { @compileError("path argument's name must at least one character"); } for (fmt) |fc, fi| { switch (fstate) { .Name => switch (fc) { ';' => { if (fi == 0) { @compileError("path argument's name must at least one character"); } field_name = fmt[0..fi]; canUse(Args, field_name, &used); field_type = @TypeOf(@field(args, field_name)); verifyField(field_type, &number); if (number) { fstate = .Fmt; } else { delim = fmt[fi + 1 ..]; fstate = .Done; break; } }, else => {}, }, .Radix => switch (fc) { '0'...'9' => { radix *= 10; radix += fc - '0'; }, else => @compileError("radix must be a number"), }, .Fmt => switch (fc) { 'r', 'R' => { radix = 0; fstate = .Radix; }, 'x', 'X' => { radix = 16; fstate = .Done; }, else => @compileError("invalid format character"), }, .Done => @compileError("unexpected character after format '" ++ fmt[fi .. fi + 1] ++ "'"), else => unreachable, } } if (fstate == .Name) { field_name = fmt[0..]; canUse(Args, field_name, &used); field_type = @TypeOf(@field(args, field_name)); verifyField(field_type, &number); } if (radix < 2 or radix > 36) { @compileError("radix must be in range [2,36]"); } } len = 0; if (number) { @field(args, field_name) = getNum(field_type, path[path_index..], radix, &len); } else { if (delim.len != 0) { @field(args, field_name) = getString(path[path_index..], delim, &len); } else { @field(args, field_name) = path[path_index..]; len += path[path_index..].len; } } // route is incorrect if the argument given is zero sized if (len == 0) { return false; } path_index += len; state = .Path; }, else => {}, }, } } if (state != .Path) { @compileError("Invalid route"); } comptime if (has_args) { for (used) |u, i| { if (!u) { @compileError("handler argument '" ++ @typeInfo(Args).Struct.fields[i].name ++ "' is not given in the path"); } } }; const r = pathbuf[begin..index]; if (!mem.eql(u8, r, path[path_index..]) and route.path[0] != '*') { return false; } if (route.method) |m| { if (!mem.eql(u8, req.method, m)) { res.status_code = .MethodNotAllowed; // routing was successful but method was not allowed return true; // todo return false and try to find a route with correct method } } if (has_args) { if (Errs != null) { try handler(req, res, &args); } else { handler(req, res, &args); } } else { if (Errs != null) { try handler(req, res); } else { handler(req, res); } } return true; } fn canUse(comptime Args: type, comptime field_name: []const u8, used: []bool) void { const index = meta.fieldIndex(Args, field_name) orelse { @compileError("handler does not take argument '" ++ field_name ++ "'"); }; if (used[index]) { @compileError("argument '" ++ field_name ++ "' already used"); } else { used[index] = true; } } fn verifyField(comptime field: type, number: *bool) void { number.* = @typeInfo(field) == .Int; if (!number.*) { assert(@typeInfo(field) == .Pointer); const ptr = @typeInfo(field).Pointer; assert(ptr.is_const and ptr.size == .Slice and ptr.child == u8); } } fn getNum(comptime T: type, path: []const u8, radix: u8, len: *usize) T { const signed = @typeInfo(T).Int.is_signed; var sign = if (signed) false; var res: T = 0; for (path) |c, i| { if (signed and c == '-' and i == 1) { sign = true; } const value = switch (c) { '0'...'9' => c - '0', 'A'...'Z' => c - 'A' + 10, 'a'...'z' => c - 'a' + 10, else => break, }; if (value >= radix) break; if (res != 0) res = math.mul(T, res, @intCast(T, radix)) catch break; res = math.add(T, res, @intCast(T, value)) catch break; len.* += 1; } if (signed and sign) { res = -res; } return res; } fn getString(path: []const u8, delim: []const u8, len: *usize) []const u8 { for (path) |c, i| { var done = false; for (delim) |d| { done = done or c == d; } if (done) { len.* = i; return path[0..i]; } } len.* = path.len; return path; }
src/routez/router.zig
const builtin = @import("builtin"); const c = @import("c.zig"); const assert = @import("std").debug.assert; // we wrap the c module for 3 reasons: // 1. to avoid accidentally calling the non-thread-safe functions // 2. patch up some of the types to remove nullability // 3. some functions have been augmented by zig_llvm.cpp to be more powerful, // such as ZigLLVMTargetMachineEmitToFile pub const AttributeIndex = c_uint; pub const Bool = c_int; pub const BuilderRef = removeNullability(c.LLVMBuilderRef); pub const ContextRef = removeNullability(c.LLVMContextRef); pub const ModuleRef = removeNullability(c.LLVMModuleRef); pub const ValueRef = removeNullability(c.LLVMValueRef); pub const TypeRef = removeNullability(c.LLVMTypeRef); pub const BasicBlockRef = removeNullability(c.LLVMBasicBlockRef); pub const AttributeRef = removeNullability(c.LLVMAttributeRef); pub const TargetRef = removeNullability(c.LLVMTargetRef); pub const TargetMachineRef = removeNullability(c.LLVMTargetMachineRef); pub const TargetDataRef = removeNullability(c.LLVMTargetDataRef); pub const DIBuilder = c.ZigLLVMDIBuilder; pub const ABIAlignmentOfType = c.LLVMABIAlignmentOfType; pub const AddAttributeAtIndex = c.LLVMAddAttributeAtIndex; pub const AddFunction = c.LLVMAddFunction; pub const AddGlobal = c.LLVMAddGlobal; pub const AddModuleCodeViewFlag = c.ZigLLVMAddModuleCodeViewFlag; pub const AddModuleDebugInfoFlag = c.ZigLLVMAddModuleDebugInfoFlag; pub const ArrayType = c.LLVMArrayType; pub const BuildLoad = c.LLVMBuildLoad; pub const ClearCurrentDebugLocation = c.ZigLLVMClearCurrentDebugLocation; pub const ConstAllOnes = c.LLVMConstAllOnes; pub const ConstArray = c.LLVMConstArray; pub const ConstBitCast = c.LLVMConstBitCast; pub const ConstInt = c.LLVMConstInt; pub const ConstIntOfArbitraryPrecision = c.LLVMConstIntOfArbitraryPrecision; pub const ConstNeg = c.LLVMConstNeg; pub const ConstNull = c.LLVMConstNull; pub const ConstStringInContext = c.LLVMConstStringInContext; pub const ConstStructInContext = c.LLVMConstStructInContext; pub const CopyStringRepOfTargetData = c.LLVMCopyStringRepOfTargetData; pub const CreateBuilderInContext = c.LLVMCreateBuilderInContext; pub const CreateCompileUnit = c.ZigLLVMCreateCompileUnit; pub const CreateDIBuilder = c.ZigLLVMCreateDIBuilder; pub const CreateEnumAttribute = c.LLVMCreateEnumAttribute; pub const CreateFile = c.ZigLLVMCreateFile; pub const CreateStringAttribute = c.LLVMCreateStringAttribute; pub const CreateTargetDataLayout = c.LLVMCreateTargetDataLayout; pub const CreateTargetMachine = c.LLVMCreateTargetMachine; pub const DIBuilderFinalize = c.ZigLLVMDIBuilderFinalize; pub const DisposeBuilder = c.LLVMDisposeBuilder; pub const DisposeDIBuilder = c.ZigLLVMDisposeDIBuilder; pub const DisposeMessage = c.LLVMDisposeMessage; pub const DisposeModule = c.LLVMDisposeModule; pub const DisposeTargetData = c.LLVMDisposeTargetData; pub const DisposeTargetMachine = c.LLVMDisposeTargetMachine; pub const DoubleTypeInContext = c.LLVMDoubleTypeInContext; pub const DumpModule = c.LLVMDumpModule; pub const FP128TypeInContext = c.LLVMFP128TypeInContext; pub const FloatTypeInContext = c.LLVMFloatTypeInContext; pub const GetEnumAttributeKindForName = c.LLVMGetEnumAttributeKindForName; pub const GetHostCPUName = c.ZigLLVMGetHostCPUName; pub const GetMDKindIDInContext = c.LLVMGetMDKindIDInContext; pub const GetNativeFeatures = c.ZigLLVMGetNativeFeatures; pub const GetUndef = c.LLVMGetUndef; pub const HalfTypeInContext = c.LLVMHalfTypeInContext; pub const InitializeAllAsmParsers = c.LLVMInitializeAllAsmParsers; pub const InitializeAllAsmPrinters = c.LLVMInitializeAllAsmPrinters; pub const InitializeAllTargetInfos = c.LLVMInitializeAllTargetInfos; pub const InitializeAllTargetMCs = c.LLVMInitializeAllTargetMCs; pub const InitializeAllTargets = c.LLVMInitializeAllTargets; pub const InsertBasicBlockInContext = c.LLVMInsertBasicBlockInContext; pub const Int128TypeInContext = c.LLVMInt128TypeInContext; pub const Int16TypeInContext = c.LLVMInt16TypeInContext; pub const Int1TypeInContext = c.LLVMInt1TypeInContext; pub const Int32TypeInContext = c.LLVMInt32TypeInContext; pub const Int64TypeInContext = c.LLVMInt64TypeInContext; pub const Int8TypeInContext = c.LLVMInt8TypeInContext; pub const IntPtrTypeForASInContext = c.LLVMIntPtrTypeForASInContext; pub const IntPtrTypeInContext = c.LLVMIntPtrTypeInContext; pub const IntTypeInContext = c.LLVMIntTypeInContext; pub const LabelTypeInContext = c.LLVMLabelTypeInContext; pub const MDNodeInContext = c.LLVMMDNodeInContext; pub const MDStringInContext = c.LLVMMDStringInContext; pub const MetadataTypeInContext = c.LLVMMetadataTypeInContext; pub const ModuleCreateWithNameInContext = c.LLVMModuleCreateWithNameInContext; pub const PPCFP128TypeInContext = c.LLVMPPCFP128TypeInContext; pub const PointerType = c.LLVMPointerType; pub const SetAlignment = c.LLVMSetAlignment; pub const SetDataLayout = c.LLVMSetDataLayout; pub const SetGlobalConstant = c.LLVMSetGlobalConstant; pub const SetInitializer = c.LLVMSetInitializer; pub const SetLinkage = c.LLVMSetLinkage; pub const SetTarget = c.LLVMSetTarget; pub const SetUnnamedAddr = c.LLVMSetUnnamedAddr; pub const SetVolatile = c.LLVMSetVolatile; pub const StructTypeInContext = c.LLVMStructTypeInContext; pub const TokenTypeInContext = c.LLVMTokenTypeInContext; pub const VoidTypeInContext = c.LLVMVoidTypeInContext; pub const X86FP80TypeInContext = c.LLVMX86FP80TypeInContext; pub const X86MMXTypeInContext = c.LLVMX86MMXTypeInContext; pub const GetElementType = LLVMGetElementType; extern fn LLVMGetElementType(Ty: TypeRef) TypeRef; pub const TypeOf = LLVMTypeOf; extern fn LLVMTypeOf(Val: ValueRef) TypeRef; pub const BuildStore = LLVMBuildStore; extern fn LLVMBuildStore(arg0: BuilderRef, Val: ValueRef, Ptr: ValueRef) ?ValueRef; pub const BuildAlloca = LLVMBuildAlloca; extern fn LLVMBuildAlloca(arg0: BuilderRef, Ty: TypeRef, Name: ?[*]const u8) ?ValueRef; pub const ConstInBoundsGEP = LLVMConstInBoundsGEP; pub extern fn LLVMConstInBoundsGEP(ConstantVal: ValueRef, ConstantIndices: [*]ValueRef, NumIndices: c_uint) ?ValueRef; pub const GetTargetFromTriple = LLVMGetTargetFromTriple; extern fn LLVMGetTargetFromTriple(Triple: [*]const u8, T: *TargetRef, ErrorMessage: ?*[*]u8) Bool; pub const VerifyModule = LLVMVerifyModule; extern fn LLVMVerifyModule(M: ModuleRef, Action: VerifierFailureAction, OutMessage: *?[*]u8) Bool; pub const GetInsertBlock = LLVMGetInsertBlock; extern fn LLVMGetInsertBlock(Builder: BuilderRef) BasicBlockRef; pub const FunctionType = LLVMFunctionType; extern fn LLVMFunctionType( ReturnType: TypeRef, ParamTypes: [*]TypeRef, ParamCount: c_uint, IsVarArg: Bool, ) ?TypeRef; pub const GetParam = LLVMGetParam; extern fn LLVMGetParam(Fn: ValueRef, Index: c_uint) ValueRef; pub const AppendBasicBlockInContext = LLVMAppendBasicBlockInContext; extern fn LLVMAppendBasicBlockInContext(C: ContextRef, Fn: ValueRef, Name: [*]const u8) ?BasicBlockRef; pub const PositionBuilderAtEnd = LLVMPositionBuilderAtEnd; extern fn LLVMPositionBuilderAtEnd(Builder: BuilderRef, Block: BasicBlockRef) void; pub const AbortProcessAction = VerifierFailureAction.LLVMAbortProcessAction; pub const PrintMessageAction = VerifierFailureAction.LLVMPrintMessageAction; pub const ReturnStatusAction = VerifierFailureAction.LLVMReturnStatusAction; pub const VerifierFailureAction = c.LLVMVerifierFailureAction; pub const CodeGenLevelNone = c.LLVMCodeGenOptLevel.LLVMCodeGenLevelNone; pub const CodeGenLevelLess = c.LLVMCodeGenOptLevel.LLVMCodeGenLevelLess; pub const CodeGenLevelDefault = c.LLVMCodeGenOptLevel.LLVMCodeGenLevelDefault; pub const CodeGenLevelAggressive = c.LLVMCodeGenOptLevel.LLVMCodeGenLevelAggressive; pub const CodeGenOptLevel = c.LLVMCodeGenOptLevel; pub const RelocDefault = c.LLVMRelocMode.LLVMRelocDefault; pub const RelocStatic = c.LLVMRelocMode.LLVMRelocStatic; pub const RelocPIC = c.LLVMRelocMode.LLVMRelocPIC; pub const RelocDynamicNoPic = c.LLVMRelocMode.LLVMRelocDynamicNoPic; pub const RelocMode = c.LLVMRelocMode; pub const CodeModelDefault = c.LLVMCodeModel.LLVMCodeModelDefault; pub const CodeModelJITDefault = c.LLVMCodeModel.LLVMCodeModelJITDefault; pub const CodeModelSmall = c.LLVMCodeModel.LLVMCodeModelSmall; pub const CodeModelKernel = c.LLVMCodeModel.LLVMCodeModelKernel; pub const CodeModelMedium = c.LLVMCodeModel.LLVMCodeModelMedium; pub const CodeModelLarge = c.LLVMCodeModel.LLVMCodeModelLarge; pub const CodeModel = c.LLVMCodeModel; pub const EmitAssembly = EmitOutputType.ZigLLVM_EmitAssembly; pub const EmitBinary = EmitOutputType.ZigLLVM_EmitBinary; pub const EmitLLVMIr = EmitOutputType.ZigLLVM_EmitLLVMIr; pub const EmitOutputType = c.ZigLLVM_EmitOutputType; pub const CCallConv = c.LLVMCCallConv; pub const FastCallConv = c.LLVMFastCallConv; pub const ColdCallConv = c.LLVMColdCallConv; pub const WebKitJSCallConv = c.LLVMWebKitJSCallConv; pub const AnyRegCallConv = c.LLVMAnyRegCallConv; pub const X86StdcallCallConv = c.LLVMX86StdcallCallConv; pub const X86FastcallCallConv = c.LLVMX86FastcallCallConv; pub const CallConv = c.LLVMCallConv; pub const FnInline = extern enum.{ Auto, Always, Never, }; fn removeNullability(comptime T: type) type { comptime assert(@typeId(T) == builtin.TypeId.Optional); return T.Child; } pub const BuildRet = LLVMBuildRet; extern fn LLVMBuildRet(arg0: BuilderRef, V: ?ValueRef) ?ValueRef; pub const TargetMachineEmitToFile = ZigLLVMTargetMachineEmitToFile; extern fn ZigLLVMTargetMachineEmitToFile( targ_machine_ref: TargetMachineRef, module_ref: ModuleRef, filename: [*]const u8, output_type: EmitOutputType, error_message: *[*]u8, is_debug: bool, is_small: bool, ) bool; pub const BuildCall = ZigLLVMBuildCall; extern fn ZigLLVMBuildCall(B: BuilderRef, Fn: ValueRef, Args: [*]ValueRef, NumArgs: c_uint, CC: c_uint, fn_inline: FnInline, Name: [*]const u8) ?ValueRef; pub const PrivateLinkage = c.LLVMLinkage.LLVMPrivateLinkage;
src-self-hosted/llvm.zig